SemaExpr.cpp 564 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/ASTMutationListener.h"
  19. #include "clang/AST/CXXInheritance.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/ExprOpenMP.h"
  27. #include "clang/AST/RecursiveASTVisitor.h"
  28. #include "clang/AST/TypeLoc.h"
  29. #include "clang/Basic/PartialDiagnostic.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Lex/LiteralSupport.h"
  33. #include "clang/Lex/Preprocessor.h"
  34. #include "clang/Sema/AnalysisBasedWarnings.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Designator.h"
  38. #include "clang/Sema/Initialization.h"
  39. #include "clang/Sema/Lookup.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/Scope.h"
  42. #include "clang/Sema/ScopeInfo.h"
  43. #include "clang/Sema/SemaFixItUtils.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/Support/ConvertUTF.h"
  46. using namespace clang;
  47. using namespace sema;
  48. /// \brief Determine whether the use of this declaration is valid, without
  49. /// emitting diagnostics.
  50. bool Sema::CanUseDecl(NamedDecl *D) {
  51. // See if this is an auto-typed variable whose initializer we are parsing.
  52. if (ParsingInitForAutoVars.count(D))
  53. return false;
  54. // See if this is a deleted function.
  55. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  56. if (FD->isDeleted())
  57. return false;
  58. // If the function has a deduced return type, and we can't deduce it,
  59. // then we can't use it either.
  60. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  61. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  62. return false;
  63. }
  64. // See if this function is unavailable.
  65. if (D->getAvailability() == AR_Unavailable &&
  66. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  67. return false;
  68. return true;
  69. }
  70. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  71. // Warn if this is used but marked unused.
  72. if (D->hasAttr<UnusedAttr>()) {
  73. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  74. if (DC && !DC->hasAttr<UnusedAttr>())
  75. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  76. }
  77. }
  78. static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
  79. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  80. if (!OMD)
  81. return false;
  82. const ObjCInterfaceDecl *OID = OMD->getClassInterface();
  83. if (!OID)
  84. return false;
  85. for (const ObjCCategoryDecl *Cat : OID->visible_categories())
  86. if (ObjCMethodDecl *CatMeth =
  87. Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
  88. if (!CatMeth->hasAttr<AvailabilityAttr>())
  89. return true;
  90. return false;
  91. }
  92. static AvailabilityResult
  93. DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
  94. const ObjCInterfaceDecl *UnknownObjCClass,
  95. bool ObjCPropertyAccess) {
  96. // See if this declaration is unavailable or deprecated.
  97. std::string Message;
  98. AvailabilityResult Result = D->getAvailability(&Message);
  99. // For typedefs, if the typedef declaration appears available look
  100. // to the underlying type to see if it is more restrictive.
  101. while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  102. if (Result == AR_Available) {
  103. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  104. D = TT->getDecl();
  105. Result = D->getAvailability(&Message);
  106. continue;
  107. }
  108. }
  109. break;
  110. }
  111. // Forward class declarations get their attributes from their definition.
  112. if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
  113. if (IDecl->getDefinition()) {
  114. D = IDecl->getDefinition();
  115. Result = D->getAvailability(&Message);
  116. }
  117. }
  118. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
  119. if (Result == AR_Available) {
  120. const DeclContext *DC = ECD->getDeclContext();
  121. if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
  122. Result = TheEnumDecl->getAvailability(&Message);
  123. }
  124. const ObjCPropertyDecl *ObjCPDecl = nullptr;
  125. if (Result == AR_Deprecated || Result == AR_Unavailable ||
  126. AR_NotYetIntroduced) {
  127. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  128. if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
  129. AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
  130. if (PDeclResult == Result)
  131. ObjCPDecl = PD;
  132. }
  133. }
  134. }
  135. switch (Result) {
  136. case AR_Available:
  137. break;
  138. case AR_Deprecated:
  139. if (S.getCurContextAvailability() != AR_Deprecated)
  140. S.EmitAvailabilityWarning(Sema::AD_Deprecation,
  141. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  142. ObjCPropertyAccess);
  143. break;
  144. case AR_NotYetIntroduced: {
  145. // Don't do this for enums, they can't be redeclared.
  146. if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
  147. break;
  148. bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
  149. // Objective-C method declarations in categories are not modelled as
  150. // redeclarations, so manually look for a redeclaration in a category
  151. // if necessary.
  152. if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
  153. Warn = false;
  154. // In general, D will point to the most recent redeclaration. However,
  155. // for `@class A;` decls, this isn't true -- manually go through the
  156. // redecl chain in that case.
  157. if (Warn && isa<ObjCInterfaceDecl>(D))
  158. for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
  159. Redecl = Redecl->getPreviousDecl())
  160. if (!Redecl->hasAttr<AvailabilityAttr>() ||
  161. Redecl->getAttr<AvailabilityAttr>()->isInherited())
  162. Warn = false;
  163. if (Warn)
  164. S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
  165. UnknownObjCClass, ObjCPDecl,
  166. ObjCPropertyAccess);
  167. break;
  168. }
  169. case AR_Unavailable:
  170. if (S.getCurContextAvailability() != AR_Unavailable)
  171. S.EmitAvailabilityWarning(Sema::AD_Unavailable,
  172. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  173. ObjCPropertyAccess);
  174. break;
  175. }
  176. return Result;
  177. }
  178. /// \brief Emit a note explaining that this function is deleted.
  179. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  180. assert(Decl->isDeleted());
  181. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  182. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  183. // If the method was explicitly defaulted, point at that declaration.
  184. if (!Method->isImplicit())
  185. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  186. // Try to diagnose why this special member function was implicitly
  187. // deleted. This might fail, if that reason no longer applies.
  188. CXXSpecialMember CSM = getSpecialMember(Method);
  189. if (CSM != CXXInvalid)
  190. ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
  191. return;
  192. }
  193. if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
  194. if (CXXConstructorDecl *BaseCD =
  195. const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
  196. Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
  197. if (BaseCD->isDeleted()) {
  198. NoteDeletedFunction(BaseCD);
  199. } else {
  200. // FIXME: An explanation of why exactly it can't be inherited
  201. // would be nice.
  202. Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
  203. }
  204. return;
  205. }
  206. }
  207. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  208. << Decl << true;
  209. }
  210. /// \brief Determine whether a FunctionDecl was ever declared with an
  211. /// explicit storage class.
  212. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  213. for (auto I : D->redecls()) {
  214. if (I->getStorageClass() != SC_None)
  215. return true;
  216. }
  217. return false;
  218. }
  219. /// \brief Check whether we're in an extern inline function and referring to a
  220. /// variable or function with internal linkage (C11 6.7.4p3).
  221. ///
  222. /// This is only a warning because we used to silently accept this code, but
  223. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  224. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  225. /// and so while there may still be user mistakes, most of the time we can't
  226. /// prove that there are errors.
  227. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  228. const NamedDecl *D,
  229. SourceLocation Loc) {
  230. // This is disabled under C++; there are too many ways for this to fire in
  231. // contexts where the warning is a false positive, or where it is technically
  232. // correct but benign.
  233. if (S.getLangOpts().CPlusPlus)
  234. return;
  235. // Check if this is an inlined function or method.
  236. FunctionDecl *Current = S.getCurFunctionDecl();
  237. if (!Current)
  238. return;
  239. if (!Current->isInlined())
  240. return;
  241. if (!Current->isExternallyVisible())
  242. return;
  243. // Check if the decl has internal linkage.
  244. if (D->getFormalLinkage() != InternalLinkage)
  245. return;
  246. // Downgrade from ExtWarn to Extension if
  247. // (1) the supposedly external inline function is in the main file,
  248. // and probably won't be included anywhere else.
  249. // (2) the thing we're referencing is a pure function.
  250. // (3) the thing we're referencing is another inline function.
  251. // This last can give us false negatives, but it's better than warning on
  252. // wrappers for simple C library functions.
  253. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  254. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  255. if (!DowngradeWarning && UsedFn)
  256. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  257. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  258. : diag::ext_internal_in_extern_inline)
  259. << /*IsVar=*/!UsedFn << D;
  260. S.MaybeSuggestAddingStaticToDecl(Current);
  261. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  262. << D;
  263. }
  264. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  265. const FunctionDecl *First = Cur->getFirstDecl();
  266. // Suggest "static" on the function, if possible.
  267. if (!hasAnyExplicitStorageClass(First)) {
  268. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  269. Diag(DeclBegin, diag::note_convert_inline_to_static)
  270. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  271. }
  272. }
  273. /// \brief Determine whether the use of this declaration is valid, and
  274. /// emit any corresponding diagnostics.
  275. ///
  276. /// This routine diagnoses various problems with referencing
  277. /// declarations that can occur when using a declaration. For example,
  278. /// it might warn if a deprecated or unavailable declaration is being
  279. /// used, or produce an error (and return true) if a C++0x deleted
  280. /// function is being used.
  281. ///
  282. /// \returns true if there was an error (this declaration cannot be
  283. /// referenced), false otherwise.
  284. ///
  285. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  286. const ObjCInterfaceDecl *UnknownObjCClass,
  287. bool ObjCPropertyAccess) {
  288. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  289. // If there were any diagnostics suppressed by template argument deduction,
  290. // emit them now.
  291. SuppressedDiagnosticsMap::iterator
  292. Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  293. if (Pos != SuppressedDiagnostics.end()) {
  294. SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
  295. for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
  296. Diag(Suppressed[I].first, Suppressed[I].second);
  297. // Clear out the list of suppressed diagnostics, so that we don't emit
  298. // them again for this specialization. However, we don't obsolete this
  299. // entry from the table, because we want to avoid ever emitting these
  300. // diagnostics again.
  301. Suppressed.clear();
  302. }
  303. // C++ [basic.start.main]p3:
  304. // The function 'main' shall not be used within a program.
  305. if (cast<FunctionDecl>(D)->isMain())
  306. Diag(Loc, diag::ext_main_used);
  307. }
  308. // See if this is an auto-typed variable whose initializer we are parsing.
  309. if (ParsingInitForAutoVars.count(D)) {
  310. const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
  311. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  312. << D->getDeclName() << (unsigned)AT->getKeyword();
  313. return true;
  314. }
  315. // See if this is a deleted function.
  316. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  317. if (FD->isDeleted()) {
  318. Diag(Loc, diag::err_deleted_function_use);
  319. NoteDeletedFunction(FD);
  320. return true;
  321. }
  322. // If the function has a deduced return type, and we can't deduce it,
  323. // then we can't use it either.
  324. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  325. DeduceReturnType(FD, Loc))
  326. return true;
  327. }
  328. DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
  329. ObjCPropertyAccess);
  330. DiagnoseUnusedOfDecl(*this, D, Loc);
  331. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  332. return false;
  333. }
  334. /// \brief Retrieve the message suffix that should be added to a
  335. /// diagnostic complaining about the given function being deleted or
  336. /// unavailable.
  337. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  338. std::string Message;
  339. if (FD->getAvailability(&Message))
  340. return ": " + Message;
  341. return std::string();
  342. }
  343. /// DiagnoseSentinelCalls - This routine checks whether a call or
  344. /// message-send is to a declaration with the sentinel attribute, and
  345. /// if so, it checks that the requirements of the sentinel are
  346. /// satisfied.
  347. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  348. ArrayRef<Expr *> Args) {
  349. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  350. if (!attr)
  351. return;
  352. // The number of formal parameters of the declaration.
  353. unsigned numFormalParams;
  354. // The kind of declaration. This is also an index into a %select in
  355. // the diagnostic.
  356. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  357. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  358. numFormalParams = MD->param_size();
  359. calleeType = CT_Method;
  360. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  361. numFormalParams = FD->param_size();
  362. calleeType = CT_Function;
  363. } else if (isa<VarDecl>(D)) {
  364. QualType type = cast<ValueDecl>(D)->getType();
  365. const FunctionType *fn = nullptr;
  366. if (const PointerType *ptr = type->getAs<PointerType>()) {
  367. fn = ptr->getPointeeType()->getAs<FunctionType>();
  368. if (!fn) return;
  369. calleeType = CT_Function;
  370. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  371. fn = ptr->getPointeeType()->castAs<FunctionType>();
  372. calleeType = CT_Block;
  373. } else {
  374. return;
  375. }
  376. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  377. numFormalParams = proto->getNumParams();
  378. } else {
  379. numFormalParams = 0;
  380. }
  381. } else {
  382. return;
  383. }
  384. // "nullPos" is the number of formal parameters at the end which
  385. // effectively count as part of the variadic arguments. This is
  386. // useful if you would prefer to not have *any* formal parameters,
  387. // but the language forces you to have at least one.
  388. unsigned nullPos = attr->getNullPos();
  389. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  390. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  391. // The number of arguments which should follow the sentinel.
  392. unsigned numArgsAfterSentinel = attr->getSentinel();
  393. // If there aren't enough arguments for all the formal parameters,
  394. // the sentinel, and the args after the sentinel, complain.
  395. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  396. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  397. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  398. return;
  399. }
  400. // Otherwise, find the sentinel expression.
  401. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  402. if (!sentinelExpr) return;
  403. if (sentinelExpr->isValueDependent()) return;
  404. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  405. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  406. // or 'NULL' if those are actually defined in the context. Only use
  407. // 'nil' for ObjC methods, where it's much more likely that the
  408. // variadic arguments form a list of object pointers.
  409. SourceLocation MissingNilLoc
  410. = getLocForEndOfToken(sentinelExpr->getLocEnd());
  411. std::string NullValue;
  412. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  413. NullValue = "nil";
  414. else if (getLangOpts().CPlusPlus11)
  415. NullValue = "nullptr";
  416. else if (PP.isMacroDefined("NULL"))
  417. NullValue = "NULL";
  418. else
  419. NullValue = "(void*) 0";
  420. if (MissingNilLoc.isInvalid())
  421. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  422. else
  423. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  424. << int(calleeType)
  425. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  426. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  427. }
  428. SourceRange Sema::getExprRange(Expr *E) const {
  429. return E ? E->getSourceRange() : SourceRange();
  430. }
  431. //===----------------------------------------------------------------------===//
  432. // Standard Promotions and Conversions
  433. //===----------------------------------------------------------------------===//
  434. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  435. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  436. // Handle any placeholder expressions which made it here.
  437. if (E->getType()->isPlaceholderType()) {
  438. ExprResult result = CheckPlaceholderExpr(E);
  439. if (result.isInvalid()) return ExprError();
  440. E = result.get();
  441. }
  442. QualType Ty = E->getType();
  443. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  444. if (Ty->isFunctionType()) {
  445. // If we are here, we are not calling a function but taking
  446. // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
  447. if (getLangOpts().OpenCL) {
  448. if (Diagnose)
  449. Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
  450. return ExprError();
  451. }
  452. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  453. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  454. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  455. return ExprError();
  456. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  457. CK_FunctionToPointerDecay).get();
  458. } else if (Ty->isArrayType()) {
  459. // In C90 mode, arrays only promote to pointers if the array expression is
  460. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  461. // type 'array of type' is converted to an expression that has type 'pointer
  462. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  463. // that has type 'array of type' ...". The relevant change is "an lvalue"
  464. // (C90) to "an expression" (C99).
  465. //
  466. // C++ 4.2p1:
  467. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  468. // T" can be converted to an rvalue of type "pointer to T".
  469. //
  470. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  471. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  472. CK_ArrayToPointerDecay).get();
  473. }
  474. return E;
  475. }
  476. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  477. // Check to see if we are dereferencing a null pointer. If so,
  478. // and if not volatile-qualified, this is undefined behavior that the
  479. // optimizer will delete, so warn about it. People sometimes try to use this
  480. // to get a deterministic trap and are surprised by clang's behavior. This
  481. // only handles the pattern "*null", which is a very syntactic check.
  482. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  483. if (UO->getOpcode() == UO_Deref &&
  484. UO->getSubExpr()->IgnoreParenCasts()->
  485. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  486. !UO->getType().isVolatileQualified()) {
  487. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  488. S.PDiag(diag::warn_indirection_through_null)
  489. << UO->getSubExpr()->getSourceRange());
  490. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  491. S.PDiag(diag::note_indirection_through_null));
  492. }
  493. }
  494. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  495. SourceLocation AssignLoc,
  496. const Expr* RHS) {
  497. const ObjCIvarDecl *IV = OIRE->getDecl();
  498. if (!IV)
  499. return;
  500. DeclarationName MemberName = IV->getDeclName();
  501. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  502. if (!Member || !Member->isStr("isa"))
  503. return;
  504. const Expr *Base = OIRE->getBase();
  505. QualType BaseType = Base->getType();
  506. if (OIRE->isArrow())
  507. BaseType = BaseType->getPointeeType();
  508. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  509. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  510. ObjCInterfaceDecl *ClassDeclared = nullptr;
  511. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  512. if (!ClassDeclared->getSuperClass()
  513. && (*ClassDeclared->ivar_begin()) == IV) {
  514. if (RHS) {
  515. NamedDecl *ObjectSetClass =
  516. S.LookupSingleName(S.TUScope,
  517. &S.Context.Idents.get("object_setClass"),
  518. SourceLocation(), S.LookupOrdinaryName);
  519. if (ObjectSetClass) {
  520. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
  521. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  522. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  523. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  524. AssignLoc), ",") <<
  525. FixItHint::CreateInsertion(RHSLocEnd, ")");
  526. }
  527. else
  528. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  529. } else {
  530. NamedDecl *ObjectGetClass =
  531. S.LookupSingleName(S.TUScope,
  532. &S.Context.Idents.get("object_getClass"),
  533. SourceLocation(), S.LookupOrdinaryName);
  534. if (ObjectGetClass)
  535. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  536. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  537. FixItHint::CreateReplacement(
  538. SourceRange(OIRE->getOpLoc(),
  539. OIRE->getLocEnd()), ")");
  540. else
  541. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  542. }
  543. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  544. }
  545. }
  546. }
  547. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  548. // Handle any placeholder expressions which made it here.
  549. if (E->getType()->isPlaceholderType()) {
  550. ExprResult result = CheckPlaceholderExpr(E);
  551. if (result.isInvalid()) return ExprError();
  552. E = result.get();
  553. }
  554. // C++ [conv.lval]p1:
  555. // A glvalue of a non-function, non-array type T can be
  556. // converted to a prvalue.
  557. if (!E->isGLValue()) return E;
  558. QualType T = E->getType();
  559. assert(!T.isNull() && "r-value conversion on typeless expression?");
  560. // We don't want to throw lvalue-to-rvalue casts on top of
  561. // expressions of certain types in C++.
  562. if (getLangOpts().CPlusPlus &&
  563. (E->getType() == Context.OverloadTy ||
  564. T->isDependentType() ||
  565. T->isRecordType()))
  566. return E;
  567. // The C standard is actually really unclear on this point, and
  568. // DR106 tells us what the result should be but not why. It's
  569. // generally best to say that void types just doesn't undergo
  570. // lvalue-to-rvalue at all. Note that expressions of unqualified
  571. // 'void' type are never l-values, but qualified void can be.
  572. if (T->isVoidType())
  573. return E;
  574. // OpenCL usually rejects direct accesses to values of 'half' type.
  575. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
  576. T->isHalfType()) {
  577. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  578. << 0 << T;
  579. return ExprError();
  580. }
  581. CheckForNullPointerDereference(*this, E);
  582. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  583. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  584. &Context.Idents.get("object_getClass"),
  585. SourceLocation(), LookupOrdinaryName);
  586. if (ObjectGetClass)
  587. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  588. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  589. FixItHint::CreateReplacement(
  590. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  591. else
  592. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  593. }
  594. else if (const ObjCIvarRefExpr *OIRE =
  595. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  596. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  597. // C++ [conv.lval]p1:
  598. // [...] If T is a non-class type, the type of the prvalue is the
  599. // cv-unqualified version of T. Otherwise, the type of the
  600. // rvalue is T.
  601. //
  602. // C99 6.3.2.1p2:
  603. // If the lvalue has qualified type, the value has the unqualified
  604. // version of the type of the lvalue; otherwise, the value has the
  605. // type of the lvalue.
  606. if (T.hasQualifiers())
  607. T = T.getUnqualifiedType();
  608. if (T->isMemberPointerType() &&
  609. Context.getTargetInfo().getCXXABI().isMicrosoft())
  610. RequireCompleteType(E->getExprLoc(), T, 0);
  611. UpdateMarkingForLValueToRValue(E);
  612. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  613. // balance that.
  614. if (getLangOpts().ObjCAutoRefCount &&
  615. E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  616. ExprNeedsCleanups = true;
  617. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  618. nullptr, VK_RValue);
  619. // C11 6.3.2.1p2:
  620. // ... if the lvalue has atomic type, the value has the non-atomic version
  621. // of the type of the lvalue ...
  622. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  623. T = Atomic->getValueType().getUnqualifiedType();
  624. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  625. nullptr, VK_RValue);
  626. }
  627. return Res;
  628. }
  629. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  630. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  631. if (Res.isInvalid())
  632. return ExprError();
  633. Res = DefaultLvalueConversion(Res.get());
  634. if (Res.isInvalid())
  635. return ExprError();
  636. return Res;
  637. }
  638. /// CallExprUnaryConversions - a special case of an unary conversion
  639. /// performed on a function designator of a call expression.
  640. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  641. QualType Ty = E->getType();
  642. ExprResult Res = E;
  643. // Only do implicit cast for a function type, but not for a pointer
  644. // to function type.
  645. if (Ty->isFunctionType()) {
  646. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  647. CK_FunctionToPointerDecay).get();
  648. if (Res.isInvalid())
  649. return ExprError();
  650. }
  651. Res = DefaultLvalueConversion(Res.get());
  652. if (Res.isInvalid())
  653. return ExprError();
  654. return Res.get();
  655. }
  656. /// UsualUnaryConversions - Performs various conversions that are common to most
  657. /// operators (C99 6.3). The conversions of array and function types are
  658. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  659. /// apply if the array is an argument to the sizeof or address (&) operators.
  660. /// In these instances, this routine should *not* be called.
  661. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  662. // First, convert to an r-value.
  663. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  664. if (Res.isInvalid())
  665. return ExprError();
  666. E = Res.get();
  667. QualType Ty = E->getType();
  668. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  669. // Half FP have to be promoted to float unless it is natively supported
  670. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  671. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  672. // Try to perform integral promotions if the object has a theoretically
  673. // promotable type.
  674. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  675. // C99 6.3.1.1p2:
  676. //
  677. // The following may be used in an expression wherever an int or
  678. // unsigned int may be used:
  679. // - an object or expression with an integer type whose integer
  680. // conversion rank is less than or equal to the rank of int
  681. // and unsigned int.
  682. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  683. //
  684. // If an int can represent all values of the original type, the
  685. // value is converted to an int; otherwise, it is converted to an
  686. // unsigned int. These are called the integer promotions. All
  687. // other types are unchanged by the integer promotions.
  688. QualType PTy = Context.isPromotableBitField(E);
  689. if (!PTy.isNull()) {
  690. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  691. return E;
  692. }
  693. if (Ty->isPromotableIntegerType()) {
  694. QualType PT = Context.getPromotedIntegerType(Ty);
  695. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  696. return E;
  697. }
  698. }
  699. return E;
  700. }
  701. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  702. /// do not have a prototype. Arguments that have type float or __fp16
  703. /// are promoted to double. All other argument types are converted by
  704. /// UsualUnaryConversions().
  705. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  706. QualType Ty = E->getType();
  707. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  708. ExprResult Res = UsualUnaryConversions(E);
  709. if (Res.isInvalid())
  710. return ExprError();
  711. E = Res.get();
  712. // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  713. // double.
  714. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  715. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  716. BTy->getKind() == BuiltinType::Float))
  717. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  718. // C++ performs lvalue-to-rvalue conversion as a default argument
  719. // promotion, even on class types, but note:
  720. // C++11 [conv.lval]p2:
  721. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  722. // operand or a subexpression thereof the value contained in the
  723. // referenced object is not accessed. Otherwise, if the glvalue
  724. // has a class type, the conversion copy-initializes a temporary
  725. // of type T from the glvalue and the result of the conversion
  726. // is a prvalue for the temporary.
  727. // FIXME: add some way to gate this entire thing for correctness in
  728. // potentially potentially evaluated contexts.
  729. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  730. ExprResult Temp = PerformCopyInitialization(
  731. InitializedEntity::InitializeTemporary(E->getType()),
  732. E->getExprLoc(), E);
  733. if (Temp.isInvalid())
  734. return ExprError();
  735. E = Temp.get();
  736. }
  737. return E;
  738. }
  739. /// Determine the degree of POD-ness for an expression.
  740. /// Incomplete types are considered POD, since this check can be performed
  741. /// when we're in an unevaluated context.
  742. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  743. if (Ty->isIncompleteType()) {
  744. // C++11 [expr.call]p7:
  745. // After these conversions, if the argument does not have arithmetic,
  746. // enumeration, pointer, pointer to member, or class type, the program
  747. // is ill-formed.
  748. //
  749. // Since we've already performed array-to-pointer and function-to-pointer
  750. // decay, the only such type in C++ is cv void. This also handles
  751. // initializer lists as variadic arguments.
  752. if (Ty->isVoidType())
  753. return VAK_Invalid;
  754. if (Ty->isObjCObjectType())
  755. return VAK_Invalid;
  756. return VAK_Valid;
  757. }
  758. if (Ty.isCXX98PODType(Context))
  759. return VAK_Valid;
  760. // C++11 [expr.call]p7:
  761. // Passing a potentially-evaluated argument of class type (Clause 9)
  762. // having a non-trivial copy constructor, a non-trivial move constructor,
  763. // or a non-trivial destructor, with no corresponding parameter,
  764. // is conditionally-supported with implementation-defined semantics.
  765. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  766. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  767. if (!Record->hasNonTrivialCopyConstructor() &&
  768. !Record->hasNonTrivialMoveConstructor() &&
  769. !Record->hasNonTrivialDestructor())
  770. return VAK_ValidInCXX11;
  771. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  772. return VAK_Valid;
  773. if (Ty->isObjCObjectType())
  774. return VAK_Invalid;
  775. if (getLangOpts().MSVCCompat)
  776. return VAK_MSVCUndefined;
  777. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  778. // permitted to reject them. We should consider doing so.
  779. return VAK_Undefined;
  780. }
  781. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  782. // Don't allow one to pass an Objective-C interface to a vararg.
  783. const QualType &Ty = E->getType();
  784. VarArgKind VAK = isValidVarArgType(Ty);
  785. // Complain about passing non-POD types through varargs.
  786. switch (VAK) {
  787. case VAK_ValidInCXX11:
  788. DiagRuntimeBehavior(
  789. E->getLocStart(), nullptr,
  790. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  791. << Ty << CT);
  792. // Fall through.
  793. case VAK_Valid:
  794. if (Ty->isRecordType()) {
  795. // This is unlikely to be what the user intended. If the class has a
  796. // 'c_str' member function, the user probably meant to call that.
  797. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  798. PDiag(diag::warn_pass_class_arg_to_vararg)
  799. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  800. }
  801. break;
  802. case VAK_Undefined:
  803. case VAK_MSVCUndefined:
  804. DiagRuntimeBehavior(
  805. E->getLocStart(), nullptr,
  806. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  807. << getLangOpts().CPlusPlus11 << Ty << CT);
  808. break;
  809. case VAK_Invalid:
  810. if (Ty->isObjCObjectType())
  811. DiagRuntimeBehavior(
  812. E->getLocStart(), nullptr,
  813. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  814. << Ty << CT);
  815. else
  816. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  817. << isa<InitListExpr>(E) << Ty << CT;
  818. break;
  819. }
  820. }
  821. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  822. /// will create a trap if the resulting type is not a POD type.
  823. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  824. FunctionDecl *FDecl) {
  825. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  826. // Strip the unbridged-cast placeholder expression off, if applicable.
  827. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  828. (CT == VariadicMethod ||
  829. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  830. E = stripARCUnbridgedCast(E);
  831. // Otherwise, do normal placeholder checking.
  832. } else {
  833. ExprResult ExprRes = CheckPlaceholderExpr(E);
  834. if (ExprRes.isInvalid())
  835. return ExprError();
  836. E = ExprRes.get();
  837. }
  838. }
  839. ExprResult ExprRes = DefaultArgumentPromotion(E);
  840. if (ExprRes.isInvalid())
  841. return ExprError();
  842. E = ExprRes.get();
  843. // Diagnostics regarding non-POD argument types are
  844. // emitted along with format string checking in Sema::CheckFunctionCall().
  845. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  846. // Turn this into a trap.
  847. CXXScopeSpec SS;
  848. SourceLocation TemplateKWLoc;
  849. UnqualifiedId Name;
  850. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  851. E->getLocStart());
  852. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  853. Name, true, false);
  854. if (TrapFn.isInvalid())
  855. return ExprError();
  856. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  857. E->getLocStart(), None,
  858. E->getLocEnd());
  859. if (Call.isInvalid())
  860. return ExprError();
  861. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  862. Call.get(), E);
  863. if (Comma.isInvalid())
  864. return ExprError();
  865. return Comma.get();
  866. }
  867. if (!getLangOpts().CPlusPlus &&
  868. RequireCompleteType(E->getExprLoc(), E->getType(),
  869. diag::err_call_incomplete_argument))
  870. return ExprError();
  871. return E;
  872. }
  873. /// \brief Converts an integer to complex float type. Helper function of
  874. /// UsualArithmeticConversions()
  875. ///
  876. /// \return false if the integer expression is an integer type and is
  877. /// successfully converted to the complex type.
  878. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  879. ExprResult &ComplexExpr,
  880. QualType IntTy,
  881. QualType ComplexTy,
  882. bool SkipCast) {
  883. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  884. if (SkipCast) return false;
  885. if (IntTy->isIntegerType()) {
  886. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  887. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  888. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  889. CK_FloatingRealToComplex);
  890. } else {
  891. assert(IntTy->isComplexIntegerType());
  892. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  893. CK_IntegralComplexToFloatingComplex);
  894. }
  895. return false;
  896. }
  897. /// \brief Handle arithmetic conversion with complex types. Helper function of
  898. /// UsualArithmeticConversions()
  899. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  900. ExprResult &RHS, QualType LHSType,
  901. QualType RHSType,
  902. bool IsCompAssign) {
  903. // if we have an integer operand, the result is the complex type.
  904. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  905. /*skipCast*/false))
  906. return LHSType;
  907. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  908. /*skipCast*/IsCompAssign))
  909. return RHSType;
  910. // This handles complex/complex, complex/float, or float/complex.
  911. // When both operands are complex, the shorter operand is converted to the
  912. // type of the longer, and that is the type of the result. This corresponds
  913. // to what is done when combining two real floating-point operands.
  914. // The fun begins when size promotion occur across type domains.
  915. // From H&S 6.3.4: When one operand is complex and the other is a real
  916. // floating-point type, the less precise type is converted, within it's
  917. // real or complex domain, to the precision of the other type. For example,
  918. // when combining a "long double" with a "double _Complex", the
  919. // "double _Complex" is promoted to "long double _Complex".
  920. // Compute the rank of the two types, regardless of whether they are complex.
  921. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  922. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  923. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  924. QualType LHSElementType =
  925. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  926. QualType RHSElementType =
  927. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  928. QualType ResultType = S.Context.getComplexType(LHSElementType);
  929. if (Order < 0) {
  930. // Promote the precision of the LHS if not an assignment.
  931. ResultType = S.Context.getComplexType(RHSElementType);
  932. if (!IsCompAssign) {
  933. if (LHSComplexType)
  934. LHS =
  935. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  936. else
  937. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  938. }
  939. } else if (Order > 0) {
  940. // Promote the precision of the RHS.
  941. if (RHSComplexType)
  942. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  943. else
  944. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  945. }
  946. return ResultType;
  947. }
  948. /// \brief Hande arithmetic conversion from integer to float. Helper function
  949. /// of UsualArithmeticConversions()
  950. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  951. ExprResult &IntExpr,
  952. QualType FloatTy, QualType IntTy,
  953. bool ConvertFloat, bool ConvertInt) {
  954. if (IntTy->isIntegerType()) {
  955. if (ConvertInt)
  956. // Convert intExpr to the lhs floating point type.
  957. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  958. CK_IntegralToFloating);
  959. return FloatTy;
  960. }
  961. // Convert both sides to the appropriate complex float.
  962. assert(IntTy->isComplexIntegerType());
  963. QualType result = S.Context.getComplexType(FloatTy);
  964. // _Complex int -> _Complex float
  965. if (ConvertInt)
  966. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  967. CK_IntegralComplexToFloatingComplex);
  968. // float -> _Complex float
  969. if (ConvertFloat)
  970. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  971. CK_FloatingRealToComplex);
  972. return result;
  973. }
  974. /// \brief Handle arithmethic conversion with floating point types. Helper
  975. /// function of UsualArithmeticConversions()
  976. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  977. ExprResult &RHS, QualType LHSType,
  978. QualType RHSType, bool IsCompAssign) {
  979. bool LHSFloat = LHSType->isRealFloatingType();
  980. bool RHSFloat = RHSType->isRealFloatingType();
  981. // If we have two real floating types, convert the smaller operand
  982. // to the bigger result.
  983. if (LHSFloat && RHSFloat) {
  984. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  985. if (order > 0) {
  986. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  987. return LHSType;
  988. }
  989. assert(order < 0 && "illegal float comparison");
  990. if (!IsCompAssign)
  991. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  992. return RHSType;
  993. }
  994. if (LHSFloat) {
  995. // Half FP has to be promoted to float unless it is natively supported
  996. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  997. LHSType = S.Context.FloatTy;
  998. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  999. /*convertFloat=*/!IsCompAssign,
  1000. /*convertInt=*/ true);
  1001. }
  1002. assert(RHSFloat);
  1003. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  1004. /*convertInt=*/ true,
  1005. /*convertFloat=*/!IsCompAssign);
  1006. }
  1007. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1008. namespace {
  1009. /// These helper callbacks are placed in an anonymous namespace to
  1010. /// permit their use as function template parameters.
  1011. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1012. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1013. }
  1014. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1015. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1016. CK_IntegralComplexCast);
  1017. }
  1018. }
  1019. /// \brief Handle integer arithmetic conversions. Helper function of
  1020. /// UsualArithmeticConversions()
  1021. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1022. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1023. ExprResult &RHS, QualType LHSType,
  1024. QualType RHSType, bool IsCompAssign) {
  1025. // The rules for this case are in C99 6.3.1.8
  1026. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1027. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1028. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1029. if (LHSSigned == RHSSigned) {
  1030. // Same signedness; use the higher-ranked type
  1031. if (order >= 0) {
  1032. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1033. return LHSType;
  1034. } else if (!IsCompAssign)
  1035. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1036. return RHSType;
  1037. } else if (order != (LHSSigned ? 1 : -1)) {
  1038. // The unsigned type has greater than or equal rank to the
  1039. // signed type, so use the unsigned type
  1040. if (RHSSigned) {
  1041. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1042. return LHSType;
  1043. } else if (!IsCompAssign)
  1044. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1045. return RHSType;
  1046. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1047. // The two types are different widths; if we are here, that
  1048. // means the signed type is larger than the unsigned type, so
  1049. // use the signed type.
  1050. if (LHSSigned) {
  1051. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1052. return LHSType;
  1053. } else if (!IsCompAssign)
  1054. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1055. return RHSType;
  1056. } else {
  1057. // The signed type is higher-ranked than the unsigned type,
  1058. // but isn't actually any bigger (like unsigned int and long
  1059. // on most 32-bit systems). Use the unsigned type corresponding
  1060. // to the signed type.
  1061. QualType result =
  1062. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1063. RHS = (*doRHSCast)(S, RHS.get(), result);
  1064. if (!IsCompAssign)
  1065. LHS = (*doLHSCast)(S, LHS.get(), result);
  1066. return result;
  1067. }
  1068. }
  1069. /// \brief Handle conversions with GCC complex int extension. Helper function
  1070. /// of UsualArithmeticConversions()
  1071. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1072. ExprResult &RHS, QualType LHSType,
  1073. QualType RHSType,
  1074. bool IsCompAssign) {
  1075. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1076. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1077. if (LHSComplexInt && RHSComplexInt) {
  1078. QualType LHSEltType = LHSComplexInt->getElementType();
  1079. QualType RHSEltType = RHSComplexInt->getElementType();
  1080. QualType ScalarType =
  1081. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1082. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1083. return S.Context.getComplexType(ScalarType);
  1084. }
  1085. if (LHSComplexInt) {
  1086. QualType LHSEltType = LHSComplexInt->getElementType();
  1087. QualType ScalarType =
  1088. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1089. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1090. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1091. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1092. CK_IntegralRealToComplex);
  1093. return ComplexType;
  1094. }
  1095. assert(RHSComplexInt);
  1096. QualType RHSEltType = RHSComplexInt->getElementType();
  1097. QualType ScalarType =
  1098. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1099. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1100. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1101. if (!IsCompAssign)
  1102. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1103. CK_IntegralRealToComplex);
  1104. return ComplexType;
  1105. }
  1106. /// UsualArithmeticConversions - Performs various conversions that are common to
  1107. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1108. /// routine returns the first non-arithmetic type found. The client is
  1109. /// responsible for emitting appropriate error diagnostics.
  1110. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1111. bool IsCompAssign) {
  1112. if (!IsCompAssign) {
  1113. LHS = UsualUnaryConversions(LHS.get());
  1114. if (LHS.isInvalid())
  1115. return QualType();
  1116. }
  1117. RHS = UsualUnaryConversions(RHS.get());
  1118. if (RHS.isInvalid())
  1119. return QualType();
  1120. // For conversion purposes, we ignore any qualifiers.
  1121. // For example, "const float" and "float" are equivalent.
  1122. QualType LHSType =
  1123. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1124. QualType RHSType =
  1125. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1126. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1127. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1128. LHSType = AtomicLHS->getValueType();
  1129. // If both types are identical, no conversion is needed.
  1130. if (LHSType == RHSType)
  1131. return LHSType;
  1132. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1133. // The caller can deal with this (e.g. pointer + int).
  1134. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1135. return QualType();
  1136. // Apply unary and bitfield promotions to the LHS's type.
  1137. QualType LHSUnpromotedType = LHSType;
  1138. if (LHSType->isPromotableIntegerType())
  1139. LHSType = Context.getPromotedIntegerType(LHSType);
  1140. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1141. if (!LHSBitfieldPromoteTy.isNull())
  1142. LHSType = LHSBitfieldPromoteTy;
  1143. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1144. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1145. // If both types are identical, no conversion is needed.
  1146. if (LHSType == RHSType)
  1147. return LHSType;
  1148. // At this point, we have two different arithmetic types.
  1149. // Handle complex types first (C99 6.3.1.8p1).
  1150. if (LHSType->isComplexType() || RHSType->isComplexType())
  1151. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1152. IsCompAssign);
  1153. // Now handle "real" floating types (i.e. float, double, long double).
  1154. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1155. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1156. IsCompAssign);
  1157. // Handle GCC complex int extension.
  1158. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1159. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1160. IsCompAssign);
  1161. // Finally, we have two differing integer types.
  1162. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1163. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1164. }
  1165. //===----------------------------------------------------------------------===//
  1166. // Semantic Analysis for various Expression Types
  1167. //===----------------------------------------------------------------------===//
  1168. ExprResult
  1169. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1170. SourceLocation DefaultLoc,
  1171. SourceLocation RParenLoc,
  1172. Expr *ControllingExpr,
  1173. ArrayRef<ParsedType> ArgTypes,
  1174. ArrayRef<Expr *> ArgExprs) {
  1175. unsigned NumAssocs = ArgTypes.size();
  1176. assert(NumAssocs == ArgExprs.size());
  1177. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1178. for (unsigned i = 0; i < NumAssocs; ++i) {
  1179. if (ArgTypes[i])
  1180. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1181. else
  1182. Types[i] = nullptr;
  1183. }
  1184. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1185. ControllingExpr,
  1186. llvm::makeArrayRef(Types, NumAssocs),
  1187. ArgExprs);
  1188. delete [] Types;
  1189. return ER;
  1190. }
  1191. ExprResult
  1192. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1193. SourceLocation DefaultLoc,
  1194. SourceLocation RParenLoc,
  1195. Expr *ControllingExpr,
  1196. ArrayRef<TypeSourceInfo *> Types,
  1197. ArrayRef<Expr *> Exprs) {
  1198. unsigned NumAssocs = Types.size();
  1199. assert(NumAssocs == Exprs.size());
  1200. // Decay and strip qualifiers for the controlling expression type, and handle
  1201. // placeholder type replacement. See committee discussion from WG14 DR423.
  1202. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1203. if (R.isInvalid())
  1204. return ExprError();
  1205. ControllingExpr = R.get();
  1206. // The controlling expression is an unevaluated operand, so side effects are
  1207. // likely unintended.
  1208. if (ActiveTemplateInstantiations.empty() &&
  1209. ControllingExpr->HasSideEffects(Context, false))
  1210. Diag(ControllingExpr->getExprLoc(),
  1211. diag::warn_side_effects_unevaluated_context);
  1212. bool TypeErrorFound = false,
  1213. IsResultDependent = ControllingExpr->isTypeDependent(),
  1214. ContainsUnexpandedParameterPack
  1215. = ControllingExpr->containsUnexpandedParameterPack();
  1216. for (unsigned i = 0; i < NumAssocs; ++i) {
  1217. if (Exprs[i]->containsUnexpandedParameterPack())
  1218. ContainsUnexpandedParameterPack = true;
  1219. if (Types[i]) {
  1220. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1221. ContainsUnexpandedParameterPack = true;
  1222. if (Types[i]->getType()->isDependentType()) {
  1223. IsResultDependent = true;
  1224. } else {
  1225. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1226. // complete object type other than a variably modified type."
  1227. unsigned D = 0;
  1228. if (Types[i]->getType()->isIncompleteType())
  1229. D = diag::err_assoc_type_incomplete;
  1230. else if (!Types[i]->getType()->isObjectType())
  1231. D = diag::err_assoc_type_nonobject;
  1232. else if (Types[i]->getType()->isVariablyModifiedType())
  1233. D = diag::err_assoc_type_variably_modified;
  1234. if (D != 0) {
  1235. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1236. << Types[i]->getTypeLoc().getSourceRange()
  1237. << Types[i]->getType();
  1238. TypeErrorFound = true;
  1239. }
  1240. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1241. // selection shall specify compatible types."
  1242. for (unsigned j = i+1; j < NumAssocs; ++j)
  1243. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1244. Context.typesAreCompatible(Types[i]->getType(),
  1245. Types[j]->getType())) {
  1246. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1247. diag::err_assoc_compatible_types)
  1248. << Types[j]->getTypeLoc().getSourceRange()
  1249. << Types[j]->getType()
  1250. << Types[i]->getType();
  1251. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1252. diag::note_compat_assoc)
  1253. << Types[i]->getTypeLoc().getSourceRange()
  1254. << Types[i]->getType();
  1255. TypeErrorFound = true;
  1256. }
  1257. }
  1258. }
  1259. }
  1260. if (TypeErrorFound)
  1261. return ExprError();
  1262. // If we determined that the generic selection is result-dependent, don't
  1263. // try to compute the result expression.
  1264. if (IsResultDependent)
  1265. return new (Context) GenericSelectionExpr(
  1266. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1267. ContainsUnexpandedParameterPack);
  1268. SmallVector<unsigned, 1> CompatIndices;
  1269. unsigned DefaultIndex = -1U;
  1270. for (unsigned i = 0; i < NumAssocs; ++i) {
  1271. if (!Types[i])
  1272. DefaultIndex = i;
  1273. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1274. Types[i]->getType()))
  1275. CompatIndices.push_back(i);
  1276. }
  1277. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1278. // type compatible with at most one of the types named in its generic
  1279. // association list."
  1280. if (CompatIndices.size() > 1) {
  1281. // We strip parens here because the controlling expression is typically
  1282. // parenthesized in macro definitions.
  1283. ControllingExpr = ControllingExpr->IgnoreParens();
  1284. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1285. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1286. << (unsigned) CompatIndices.size();
  1287. for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
  1288. E = CompatIndices.end(); I != E; ++I) {
  1289. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1290. diag::note_compat_assoc)
  1291. << Types[*I]->getTypeLoc().getSourceRange()
  1292. << Types[*I]->getType();
  1293. }
  1294. return ExprError();
  1295. }
  1296. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1297. // its controlling expression shall have type compatible with exactly one of
  1298. // the types named in its generic association list."
  1299. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1300. // We strip parens here because the controlling expression is typically
  1301. // parenthesized in macro definitions.
  1302. ControllingExpr = ControllingExpr->IgnoreParens();
  1303. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1304. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1305. return ExprError();
  1306. }
  1307. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1308. // type name that is compatible with the type of the controlling expression,
  1309. // then the result expression of the generic selection is the expression
  1310. // in that generic association. Otherwise, the result expression of the
  1311. // generic selection is the expression in the default generic association."
  1312. unsigned ResultIndex =
  1313. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1314. return new (Context) GenericSelectionExpr(
  1315. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1316. ContainsUnexpandedParameterPack, ResultIndex);
  1317. }
  1318. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1319. /// location of the token and the offset of the ud-suffix within it.
  1320. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1321. unsigned Offset) {
  1322. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1323. S.getLangOpts());
  1324. }
  1325. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1326. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1327. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1328. IdentifierInfo *UDSuffix,
  1329. SourceLocation UDSuffixLoc,
  1330. ArrayRef<Expr*> Args,
  1331. SourceLocation LitEndLoc) {
  1332. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1333. QualType ArgTy[2];
  1334. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1335. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1336. if (ArgTy[ArgIdx]->isArrayType())
  1337. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1338. }
  1339. DeclarationName OpName =
  1340. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1341. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1342. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1343. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1344. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1345. /*AllowRaw*/false, /*AllowTemplate*/false,
  1346. /*AllowStringTemplate*/false) == Sema::LOLR_Error)
  1347. return ExprError();
  1348. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1349. }
  1350. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1351. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1352. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1353. /// multiple tokens. However, the common case is that StringToks points to one
  1354. /// string.
  1355. ///
  1356. ExprResult
  1357. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1358. assert(!StringToks.empty() && "Must have at least one string!");
  1359. StringLiteralParser Literal(StringToks, PP);
  1360. if (Literal.hadError)
  1361. return ExprError();
  1362. SmallVector<SourceLocation, 4> StringTokLocs;
  1363. for (unsigned i = 0; i != StringToks.size(); ++i)
  1364. StringTokLocs.push_back(StringToks[i].getLocation());
  1365. QualType CharTy = Context.CharTy;
  1366. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1367. if (Literal.isWide()) {
  1368. CharTy = Context.getWideCharType();
  1369. Kind = StringLiteral::Wide;
  1370. } else if (Literal.isUTF8()) {
  1371. Kind = StringLiteral::UTF8;
  1372. } else if (Literal.isUTF16()) {
  1373. CharTy = Context.Char16Ty;
  1374. Kind = StringLiteral::UTF16;
  1375. } else if (Literal.isUTF32()) {
  1376. CharTy = Context.Char32Ty;
  1377. Kind = StringLiteral::UTF32;
  1378. } else if (Literal.isPascal()) {
  1379. CharTy = Context.UnsignedCharTy;
  1380. }
  1381. QualType CharTyConst = CharTy;
  1382. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1383. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1384. CharTyConst.addConst();
  1385. // Get an array type for the string, according to C99 6.4.5. This includes
  1386. // the nul terminator character as well as the string length for pascal
  1387. // strings.
  1388. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1389. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1390. ArrayType::Normal, 0);
  1391. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1392. if (getLangOpts().OpenCL) {
  1393. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1394. }
  1395. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1396. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1397. Kind, Literal.Pascal, StrTy,
  1398. &StringTokLocs[0],
  1399. StringTokLocs.size());
  1400. if (Literal.getUDSuffix().empty())
  1401. return Lit;
  1402. // We're building a user-defined literal.
  1403. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1404. SourceLocation UDSuffixLoc =
  1405. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1406. Literal.getUDSuffixOffset());
  1407. // Make sure we're allowed user-defined literals here.
  1408. if (!UDLScope)
  1409. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1410. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1411. // operator "" X (str, len)
  1412. QualType SizeType = Context.getSizeType();
  1413. DeclarationName OpName =
  1414. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1415. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1416. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1417. QualType ArgTy[] = {
  1418. Context.getArrayDecayedType(StrTy), SizeType
  1419. };
  1420. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1421. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1422. /*AllowRaw*/false, /*AllowTemplate*/false,
  1423. /*AllowStringTemplate*/true)) {
  1424. case LOLR_Cooked: {
  1425. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1426. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1427. StringTokLocs[0]);
  1428. Expr *Args[] = { Lit, LenArg };
  1429. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1430. }
  1431. case LOLR_StringTemplate: {
  1432. TemplateArgumentListInfo ExplicitArgs;
  1433. unsigned CharBits = Context.getIntWidth(CharTy);
  1434. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1435. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1436. TemplateArgument TypeArg(CharTy);
  1437. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1438. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1439. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1440. Value = Lit->getCodeUnit(I);
  1441. TemplateArgument Arg(Context, Value, CharTy);
  1442. TemplateArgumentLocInfo ArgInfo;
  1443. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1444. }
  1445. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1446. &ExplicitArgs);
  1447. }
  1448. case LOLR_Raw:
  1449. case LOLR_Template:
  1450. llvm_unreachable("unexpected literal operator lookup result");
  1451. case LOLR_Error:
  1452. return ExprError();
  1453. }
  1454. llvm_unreachable("unexpected literal operator lookup result");
  1455. }
  1456. ExprResult
  1457. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1458. SourceLocation Loc,
  1459. const CXXScopeSpec *SS) {
  1460. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1461. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1462. }
  1463. /// BuildDeclRefExpr - Build an expression that references a
  1464. /// declaration that does not require a closure capture.
  1465. ExprResult
  1466. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1467. const DeclarationNameInfo &NameInfo,
  1468. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1469. const TemplateArgumentListInfo *TemplateArgs) {
  1470. if (getLangOpts().CUDA)
  1471. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1472. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1473. if (CheckCUDATarget(Caller, Callee)) {
  1474. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1475. << IdentifyCUDATarget(Callee) << D->getIdentifier()
  1476. << IdentifyCUDATarget(Caller);
  1477. Diag(D->getLocation(), diag::note_previous_decl)
  1478. << D->getIdentifier();
  1479. return ExprError();
  1480. }
  1481. }
  1482. bool RefersToCapturedVariable =
  1483. isa<VarDecl>(D) &&
  1484. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1485. DeclRefExpr *E;
  1486. if (isa<VarTemplateSpecializationDecl>(D)) {
  1487. VarTemplateSpecializationDecl *VarSpec =
  1488. cast<VarTemplateSpecializationDecl>(D);
  1489. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1490. : NestedNameSpecifierLoc(),
  1491. VarSpec->getTemplateKeywordLoc(), D,
  1492. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1493. FoundD, TemplateArgs);
  1494. } else {
  1495. assert(!TemplateArgs && "No template arguments for non-variable"
  1496. " template specialization references");
  1497. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1498. : NestedNameSpecifierLoc(),
  1499. SourceLocation(), D, RefersToCapturedVariable,
  1500. NameInfo, Ty, VK, FoundD);
  1501. }
  1502. MarkDeclRefReferenced(E);
  1503. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1504. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1505. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1506. recordUseOfEvaluatedWeak(E);
  1507. // Just in case we're building an illegal pointer-to-member.
  1508. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1509. if (FD && FD->isBitField())
  1510. E->setObjectKind(OK_BitField);
  1511. return E;
  1512. }
  1513. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1514. /// possibly a list of template arguments.
  1515. ///
  1516. /// If this produces template arguments, it is permitted to call
  1517. /// DecomposeTemplateName.
  1518. ///
  1519. /// This actually loses a lot of source location information for
  1520. /// non-standard name kinds; we should consider preserving that in
  1521. /// some way.
  1522. void
  1523. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1524. TemplateArgumentListInfo &Buffer,
  1525. DeclarationNameInfo &NameInfo,
  1526. const TemplateArgumentListInfo *&TemplateArgs) {
  1527. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1528. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1529. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1530. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1531. Id.TemplateId->NumArgs);
  1532. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1533. TemplateName TName = Id.TemplateId->Template.get();
  1534. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1535. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1536. TemplateArgs = &Buffer;
  1537. } else {
  1538. NameInfo = GetNameFromUnqualifiedId(Id);
  1539. TemplateArgs = nullptr;
  1540. }
  1541. }
  1542. static void emitEmptyLookupTypoDiagnostic(
  1543. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1544. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1545. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1546. DeclContext *Ctx =
  1547. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1548. if (!TC) {
  1549. // Emit a special diagnostic for failed member lookups.
  1550. // FIXME: computing the declaration context might fail here (?)
  1551. if (Ctx)
  1552. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1553. << SS.getRange();
  1554. else
  1555. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1556. return;
  1557. }
  1558. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1559. bool DroppedSpecifier =
  1560. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1561. unsigned NoteID =
  1562. (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
  1563. ? diag::note_implicit_param_decl
  1564. : diag::note_previous_decl;
  1565. if (!Ctx)
  1566. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1567. SemaRef.PDiag(NoteID));
  1568. else
  1569. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1570. << Typo << Ctx << DroppedSpecifier
  1571. << SS.getRange(),
  1572. SemaRef.PDiag(NoteID));
  1573. }
  1574. /// Diagnose an empty lookup.
  1575. ///
  1576. /// \return false if new lookup candidates were found
  1577. bool
  1578. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1579. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1580. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1581. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1582. DeclarationName Name = R.getLookupName();
  1583. unsigned diagnostic = diag::err_undeclared_var_use;
  1584. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1585. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1586. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1587. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1588. diagnostic = diag::err_undeclared_use;
  1589. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1590. }
  1591. // If the original lookup was an unqualified lookup, fake an
  1592. // unqualified lookup. This is useful when (for example) the
  1593. // original lookup would not have found something because it was a
  1594. // dependent name.
  1595. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1596. while (DC) {
  1597. if (isa<CXXRecordDecl>(DC)) {
  1598. LookupQualifiedName(R, DC);
  1599. if (!R.empty()) {
  1600. // Don't give errors about ambiguities in this lookup.
  1601. R.suppressDiagnostics();
  1602. // During a default argument instantiation the CurContext points
  1603. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1604. // function parameter list, hence add an explicit check.
  1605. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1606. ActiveTemplateInstantiations.back().Kind ==
  1607. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1608. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1609. bool isInstance = CurMethod &&
  1610. CurMethod->isInstance() &&
  1611. DC == CurMethod->getParent() && !isDefaultArgument;
  1612. // Give a code modification hint to insert 'this->'.
  1613. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1614. // Actually quite difficult!
  1615. if (getLangOpts().MSVCCompat)
  1616. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1617. if (isInstance) {
  1618. Diag(R.getNameLoc(), diagnostic) << Name
  1619. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1620. CheckCXXThisCapture(R.getNameLoc());
  1621. } else {
  1622. Diag(R.getNameLoc(), diagnostic) << Name;
  1623. }
  1624. // Do we really want to note all of these?
  1625. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1626. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1627. // Return true if we are inside a default argument instantiation
  1628. // and the found name refers to an instance member function, otherwise
  1629. // the function calling DiagnoseEmptyLookup will try to create an
  1630. // implicit member call and this is wrong for default argument.
  1631. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1632. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1633. return true;
  1634. }
  1635. // Tell the callee to try to recover.
  1636. return false;
  1637. }
  1638. R.clear();
  1639. }
  1640. // In Microsoft mode, if we are performing lookup from within a friend
  1641. // function definition declared at class scope then we must set
  1642. // DC to the lexical parent to be able to search into the parent
  1643. // class.
  1644. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1645. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1646. DC->getLexicalParent()->isRecord())
  1647. DC = DC->getLexicalParent();
  1648. else
  1649. DC = DC->getParent();
  1650. }
  1651. // We didn't find anything, so try to correct for a typo.
  1652. TypoCorrection Corrected;
  1653. if (S && Out) {
  1654. SourceLocation TypoLoc = R.getNameLoc();
  1655. assert(!ExplicitTemplateArgs &&
  1656. "Diagnosing an empty lookup with explicit template args!");
  1657. *Out = CorrectTypoDelayed(
  1658. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1659. [=](const TypoCorrection &TC) {
  1660. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1661. diagnostic, diagnostic_suggest);
  1662. },
  1663. nullptr, CTK_ErrorRecovery);
  1664. if (*Out)
  1665. return true;
  1666. } else if (S && (Corrected =
  1667. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1668. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1669. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1670. bool DroppedSpecifier =
  1671. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1672. R.setLookupName(Corrected.getCorrection());
  1673. bool AcceptableWithRecovery = false;
  1674. bool AcceptableWithoutRecovery = false;
  1675. NamedDecl *ND = Corrected.getCorrectionDecl();
  1676. if (ND) {
  1677. if (Corrected.isOverloaded()) {
  1678. OverloadCandidateSet OCS(R.getNameLoc(),
  1679. OverloadCandidateSet::CSK_Normal);
  1680. OverloadCandidateSet::iterator Best;
  1681. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1682. CDEnd = Corrected.end();
  1683. CD != CDEnd; ++CD) {
  1684. if (FunctionTemplateDecl *FTD =
  1685. dyn_cast<FunctionTemplateDecl>(*CD))
  1686. AddTemplateOverloadCandidate(
  1687. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1688. Args, OCS);
  1689. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1690. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1691. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1692. Args, OCS);
  1693. }
  1694. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1695. case OR_Success:
  1696. ND = Best->Function;
  1697. Corrected.setCorrectionDecl(ND);
  1698. break;
  1699. default:
  1700. // FIXME: Arbitrarily pick the first declaration for the note.
  1701. Corrected.setCorrectionDecl(ND);
  1702. break;
  1703. }
  1704. }
  1705. R.addDecl(ND);
  1706. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1707. CXXRecordDecl *Record = nullptr;
  1708. if (Corrected.getCorrectionSpecifier()) {
  1709. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1710. Record = Ty->getAsCXXRecordDecl();
  1711. }
  1712. if (!Record)
  1713. Record = cast<CXXRecordDecl>(
  1714. ND->getDeclContext()->getRedeclContext());
  1715. R.setNamingClass(Record);
  1716. }
  1717. AcceptableWithRecovery =
  1718. isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
  1719. // FIXME: If we ended up with a typo for a type name or
  1720. // Objective-C class name, we're in trouble because the parser
  1721. // is in the wrong place to recover. Suggest the typo
  1722. // correction, but don't make it a fix-it since we're not going
  1723. // to recover well anyway.
  1724. AcceptableWithoutRecovery =
  1725. isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1726. } else {
  1727. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1728. // because we aren't able to recover.
  1729. AcceptableWithoutRecovery = true;
  1730. }
  1731. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1732. unsigned NoteID = (Corrected.getCorrectionDecl() &&
  1733. isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
  1734. ? diag::note_implicit_param_decl
  1735. : diag::note_previous_decl;
  1736. if (SS.isEmpty())
  1737. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1738. PDiag(NoteID), AcceptableWithRecovery);
  1739. else
  1740. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1741. << Name << computeDeclContext(SS, false)
  1742. << DroppedSpecifier << SS.getRange(),
  1743. PDiag(NoteID), AcceptableWithRecovery);
  1744. // Tell the callee whether to try to recover.
  1745. return !AcceptableWithRecovery;
  1746. }
  1747. }
  1748. R.clear();
  1749. // Emit a special diagnostic for failed member lookups.
  1750. // FIXME: computing the declaration context might fail here (?)
  1751. if (!SS.isEmpty()) {
  1752. Diag(R.getNameLoc(), diag::err_no_member)
  1753. << Name << computeDeclContext(SS, false)
  1754. << SS.getRange();
  1755. return true;
  1756. }
  1757. // Give up, we can't recover.
  1758. Diag(R.getNameLoc(), diagnostic) << Name;
  1759. return true;
  1760. }
  1761. /// In Microsoft mode, if we are inside a template class whose parent class has
  1762. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1763. /// assume the identifier is a member of a dependent base class. We can only
  1764. /// recover successfully in static methods, instance methods, and other contexts
  1765. /// where 'this' is available. This doesn't precisely match MSVC's
  1766. /// instantiation model, but it's close enough.
  1767. static Expr *
  1768. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1769. DeclarationNameInfo &NameInfo,
  1770. SourceLocation TemplateKWLoc,
  1771. const TemplateArgumentListInfo *TemplateArgs) {
  1772. // Only try to recover from lookup into dependent bases in static methods or
  1773. // contexts where 'this' is available.
  1774. QualType ThisType = S.getCurrentThisType();
  1775. const CXXRecordDecl *RD = nullptr;
  1776. if (!ThisType.isNull())
  1777. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1778. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1779. RD = MD->getParent();
  1780. if (!RD || !RD->hasAnyDependentBases())
  1781. return nullptr;
  1782. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1783. // is available, suggest inserting 'this->' as a fixit.
  1784. SourceLocation Loc = NameInfo.getLoc();
  1785. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1786. DB << NameInfo.getName() << RD;
  1787. if (!ThisType.isNull()) {
  1788. DB << FixItHint::CreateInsertion(Loc, "this->");
  1789. return CXXDependentScopeMemberExpr::Create(
  1790. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1791. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1792. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1793. }
  1794. // Synthesize a fake NNS that points to the derived class. This will
  1795. // perform name lookup during template instantiation.
  1796. CXXScopeSpec SS;
  1797. auto *NNS =
  1798. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1799. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1800. return DependentScopeDeclRefExpr::Create(
  1801. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1802. TemplateArgs);
  1803. }
  1804. ExprResult
  1805. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1806. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1807. bool HasTrailingLParen, bool IsAddressOfOperand,
  1808. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1809. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1810. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1811. "cannot be direct & operand and have a trailing lparen");
  1812. if (SS.isInvalid())
  1813. return ExprError();
  1814. TemplateArgumentListInfo TemplateArgsBuffer;
  1815. // Decompose the UnqualifiedId into the following data.
  1816. DeclarationNameInfo NameInfo;
  1817. const TemplateArgumentListInfo *TemplateArgs;
  1818. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1819. DeclarationName Name = NameInfo.getName();
  1820. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1821. SourceLocation NameLoc = NameInfo.getLoc();
  1822. // C++ [temp.dep.expr]p3:
  1823. // An id-expression is type-dependent if it contains:
  1824. // -- an identifier that was declared with a dependent type,
  1825. // (note: handled after lookup)
  1826. // -- a template-id that is dependent,
  1827. // (note: handled in BuildTemplateIdExpr)
  1828. // -- a conversion-function-id that specifies a dependent type,
  1829. // -- a nested-name-specifier that contains a class-name that
  1830. // names a dependent type.
  1831. // Determine whether this is a member of an unknown specialization;
  1832. // we need to handle these differently.
  1833. bool DependentID = false;
  1834. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1835. Name.getCXXNameType()->isDependentType()) {
  1836. DependentID = true;
  1837. } else if (SS.isSet()) {
  1838. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1839. if (RequireCompleteDeclContext(SS, DC))
  1840. return ExprError();
  1841. } else {
  1842. DependentID = true;
  1843. }
  1844. }
  1845. if (DependentID)
  1846. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1847. IsAddressOfOperand, TemplateArgs);
  1848. // Perform the required lookup.
  1849. LookupResult R(*this, NameInfo,
  1850. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1851. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1852. if (TemplateArgs) {
  1853. // Lookup the template name again to correctly establish the context in
  1854. // which it was found. This is really unfortunate as we already did the
  1855. // lookup to determine that it was a template name in the first place. If
  1856. // this becomes a performance hit, we can work harder to preserve those
  1857. // results until we get here but it's likely not worth it.
  1858. bool MemberOfUnknownSpecialization;
  1859. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1860. MemberOfUnknownSpecialization);
  1861. if (MemberOfUnknownSpecialization ||
  1862. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1863. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1864. IsAddressOfOperand, TemplateArgs);
  1865. } else {
  1866. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1867. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1868. // If the result might be in a dependent base class, this is a dependent
  1869. // id-expression.
  1870. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1871. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1872. IsAddressOfOperand, TemplateArgs);
  1873. // If this reference is in an Objective-C method, then we need to do
  1874. // some special Objective-C lookup, too.
  1875. if (IvarLookupFollowUp) {
  1876. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1877. if (E.isInvalid())
  1878. return ExprError();
  1879. if (Expr *Ex = E.getAs<Expr>())
  1880. return Ex;
  1881. }
  1882. }
  1883. if (R.isAmbiguous())
  1884. return ExprError();
  1885. // This could be an implicitly declared function reference (legal in C90,
  1886. // extension in C99, forbidden in C++).
  1887. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1888. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1889. if (D) R.addDecl(D);
  1890. }
  1891. // Determine whether this name might be a candidate for
  1892. // argument-dependent lookup.
  1893. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1894. if (R.empty() && !ADL) {
  1895. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1896. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1897. TemplateKWLoc, TemplateArgs))
  1898. return E;
  1899. }
  1900. // Don't diagnose an empty lookup for inline assembly.
  1901. if (IsInlineAsmIdentifier)
  1902. return ExprError();
  1903. // If this name wasn't predeclared and if this is not a function
  1904. // call, diagnose the problem.
  1905. TypoExpr *TE = nullptr;
  1906. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1907. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1908. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1909. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1910. "Typo correction callback misconfigured");
  1911. if (CCC) {
  1912. // Make sure the callback knows what the typo being diagnosed is.
  1913. CCC->setTypoName(II);
  1914. if (SS.isValid())
  1915. CCC->setTypoNNS(SS.getScopeRep());
  1916. }
  1917. if (DiagnoseEmptyLookup(S, SS, R,
  1918. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1919. nullptr, None, &TE)) {
  1920. if (TE && KeywordReplacement) {
  1921. auto &State = getTypoExprState(TE);
  1922. auto BestTC = State.Consumer->getNextCorrection();
  1923. if (BestTC.isKeyword()) {
  1924. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1925. if (State.DiagHandler)
  1926. State.DiagHandler(BestTC);
  1927. KeywordReplacement->startToken();
  1928. KeywordReplacement->setKind(II->getTokenID());
  1929. KeywordReplacement->setIdentifierInfo(II);
  1930. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1931. // Clean up the state associated with the TypoExpr, since it has
  1932. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1933. clearDelayedTypo(TE);
  1934. // Signal that a correction to a keyword was performed by returning a
  1935. // valid-but-null ExprResult.
  1936. return (Expr*)nullptr;
  1937. }
  1938. State.Consumer->resetCorrectionStream();
  1939. }
  1940. return TE ? TE : ExprError();
  1941. }
  1942. assert(!R.empty() &&
  1943. "DiagnoseEmptyLookup returned false but added no results");
  1944. // If we found an Objective-C instance variable, let
  1945. // LookupInObjCMethod build the appropriate expression to
  1946. // reference the ivar.
  1947. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1948. R.clear();
  1949. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1950. // In a hopelessly buggy code, Objective-C instance variable
  1951. // lookup fails and no expression will be built to reference it.
  1952. if (!E.isInvalid() && !E.get())
  1953. return ExprError();
  1954. return E;
  1955. }
  1956. }
  1957. // This is guaranteed from this point on.
  1958. assert(!R.empty() || ADL);
  1959. // Check whether this might be a C++ implicit instance member access.
  1960. // C++ [class.mfct.non-static]p3:
  1961. // When an id-expression that is not part of a class member access
  1962. // syntax and not used to form a pointer to member is used in the
  1963. // body of a non-static member function of class X, if name lookup
  1964. // resolves the name in the id-expression to a non-static non-type
  1965. // member of some class C, the id-expression is transformed into a
  1966. // class member access expression using (*this) as the
  1967. // postfix-expression to the left of the . operator.
  1968. //
  1969. // But we don't actually need to do this for '&' operands if R
  1970. // resolved to a function or overloaded function set, because the
  1971. // expression is ill-formed if it actually works out to be a
  1972. // non-static member function:
  1973. //
  1974. // C++ [expr.ref]p4:
  1975. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1976. // [t]he expression can be used only as the left-hand operand of a
  1977. // member function call.
  1978. //
  1979. // There are other safeguards against such uses, but it's important
  1980. // to get this right here so that we don't end up making a
  1981. // spuriously dependent expression if we're inside a dependent
  1982. // instance method.
  1983. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  1984. bool MightBeImplicitMember;
  1985. if (!IsAddressOfOperand)
  1986. MightBeImplicitMember = true;
  1987. else if (!SS.isEmpty())
  1988. MightBeImplicitMember = false;
  1989. else if (R.isOverloadedResult())
  1990. MightBeImplicitMember = false;
  1991. else if (R.isUnresolvableResult())
  1992. MightBeImplicitMember = true;
  1993. else
  1994. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  1995. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  1996. isa<MSPropertyDecl>(R.getFoundDecl());
  1997. if (MightBeImplicitMember)
  1998. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  1999. R, TemplateArgs, S);
  2000. }
  2001. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2002. // In C++1y, if this is a variable template id, then check it
  2003. // in BuildTemplateIdExpr().
  2004. // The single lookup result must be a variable template declaration.
  2005. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  2006. Id.TemplateId->Kind == TNK_Var_template) {
  2007. assert(R.getAsSingle<VarTemplateDecl>() &&
  2008. "There should only be one declaration found.");
  2009. }
  2010. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2011. }
  2012. return BuildDeclarationNameExpr(SS, R, ADL);
  2013. }
  2014. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2015. /// declaration name, generally during template instantiation.
  2016. /// There's a large number of things which don't need to be done along
  2017. /// this path.
  2018. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2019. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2020. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2021. DeclContext *DC = computeDeclContext(SS, false);
  2022. if (!DC)
  2023. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2024. NameInfo, /*TemplateArgs=*/nullptr);
  2025. if (RequireCompleteDeclContext(SS, DC))
  2026. return ExprError();
  2027. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2028. LookupQualifiedName(R, DC);
  2029. if (R.isAmbiguous())
  2030. return ExprError();
  2031. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2032. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2033. NameInfo, /*TemplateArgs=*/nullptr);
  2034. if (R.empty()) {
  2035. Diag(NameInfo.getLoc(), diag::err_no_member)
  2036. << NameInfo.getName() << DC << SS.getRange();
  2037. return ExprError();
  2038. }
  2039. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2040. // Diagnose a missing typename if this resolved unambiguously to a type in
  2041. // a dependent context. If we can recover with a type, downgrade this to
  2042. // a warning in Microsoft compatibility mode.
  2043. unsigned DiagID = diag::err_typename_missing;
  2044. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2045. DiagID = diag::ext_typename_missing;
  2046. SourceLocation Loc = SS.getBeginLoc();
  2047. auto D = Diag(Loc, DiagID);
  2048. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2049. << SourceRange(Loc, NameInfo.getEndLoc());
  2050. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2051. // context.
  2052. if (!RecoveryTSI)
  2053. return ExprError();
  2054. // Only issue the fixit if we're prepared to recover.
  2055. D << FixItHint::CreateInsertion(Loc, "typename ");
  2056. // Recover by pretending this was an elaborated type.
  2057. QualType Ty = Context.getTypeDeclType(TD);
  2058. TypeLocBuilder TLB;
  2059. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2060. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2061. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2062. QTL.setElaboratedKeywordLoc(SourceLocation());
  2063. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2064. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2065. return ExprEmpty();
  2066. }
  2067. // Defend against this resolving to an implicit member access. We usually
  2068. // won't get here if this might be a legitimate a class member (we end up in
  2069. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2070. // a pointer-to-member or in an unevaluated context in C++11.
  2071. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2072. return BuildPossibleImplicitMemberExpr(SS,
  2073. /*TemplateKWLoc=*/SourceLocation(),
  2074. R, /*TemplateArgs=*/nullptr, S);
  2075. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2076. }
  2077. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2078. /// detected that we're currently inside an ObjC method. Perform some
  2079. /// additional lookup.
  2080. ///
  2081. /// Ideally, most of this would be done by lookup, but there's
  2082. /// actually quite a lot of extra work involved.
  2083. ///
  2084. /// Returns a null sentinel to indicate trivial success.
  2085. ExprResult
  2086. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2087. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2088. SourceLocation Loc = Lookup.getNameLoc();
  2089. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2090. // Check for error condition which is already reported.
  2091. if (!CurMethod)
  2092. return ExprError();
  2093. // There are two cases to handle here. 1) scoped lookup could have failed,
  2094. // in which case we should look for an ivar. 2) scoped lookup could have
  2095. // found a decl, but that decl is outside the current instance method (i.e.
  2096. // a global variable). In these two cases, we do a lookup for an ivar with
  2097. // this name, if the lookup sucedes, we replace it our current decl.
  2098. // If we're in a class method, we don't normally want to look for
  2099. // ivars. But if we don't find anything else, and there's an
  2100. // ivar, that's an error.
  2101. bool IsClassMethod = CurMethod->isClassMethod();
  2102. bool LookForIvars;
  2103. if (Lookup.empty())
  2104. LookForIvars = true;
  2105. else if (IsClassMethod)
  2106. LookForIvars = false;
  2107. else
  2108. LookForIvars = (Lookup.isSingleResult() &&
  2109. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2110. ObjCInterfaceDecl *IFace = nullptr;
  2111. if (LookForIvars) {
  2112. IFace = CurMethod->getClassInterface();
  2113. ObjCInterfaceDecl *ClassDeclared;
  2114. ObjCIvarDecl *IV = nullptr;
  2115. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2116. // Diagnose using an ivar in a class method.
  2117. if (IsClassMethod)
  2118. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2119. << IV->getDeclName());
  2120. // If we're referencing an invalid decl, just return this as a silent
  2121. // error node. The error diagnostic was already emitted on the decl.
  2122. if (IV->isInvalidDecl())
  2123. return ExprError();
  2124. // Check if referencing a field with __attribute__((deprecated)).
  2125. if (DiagnoseUseOfDecl(IV, Loc))
  2126. return ExprError();
  2127. // Diagnose the use of an ivar outside of the declaring class.
  2128. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2129. !declaresSameEntity(ClassDeclared, IFace) &&
  2130. !getLangOpts().DebuggerSupport)
  2131. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  2132. // FIXME: This should use a new expr for a direct reference, don't
  2133. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2134. IdentifierInfo &II = Context.Idents.get("self");
  2135. UnqualifiedId SelfName;
  2136. SelfName.setIdentifier(&II, SourceLocation());
  2137. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2138. CXXScopeSpec SelfScopeSpec;
  2139. SourceLocation TemplateKWLoc;
  2140. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2141. SelfName, false, false);
  2142. if (SelfExpr.isInvalid())
  2143. return ExprError();
  2144. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2145. if (SelfExpr.isInvalid())
  2146. return ExprError();
  2147. MarkAnyDeclReferenced(Loc, IV, true);
  2148. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2149. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2150. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2151. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2152. ObjCIvarRefExpr *Result = new (Context)
  2153. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2154. IV->getLocation(), SelfExpr.get(), true, true);
  2155. if (getLangOpts().ObjCAutoRefCount) {
  2156. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2157. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2158. recordUseOfEvaluatedWeak(Result);
  2159. }
  2160. if (CurContext->isClosure())
  2161. Diag(Loc, diag::warn_implicitly_retains_self)
  2162. << FixItHint::CreateInsertion(Loc, "self->");
  2163. }
  2164. return Result;
  2165. }
  2166. } else if (CurMethod->isInstanceMethod()) {
  2167. // We should warn if a local variable hides an ivar.
  2168. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2169. ObjCInterfaceDecl *ClassDeclared;
  2170. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2171. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2172. declaresSameEntity(IFace, ClassDeclared))
  2173. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2174. }
  2175. }
  2176. } else if (Lookup.isSingleResult() &&
  2177. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2178. // If accessing a stand-alone ivar in a class method, this is an error.
  2179. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2180. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2181. << IV->getDeclName());
  2182. }
  2183. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2184. // FIXME. Consolidate this with similar code in LookupName.
  2185. if (unsigned BuiltinID = II->getBuiltinID()) {
  2186. if (!(getLangOpts().CPlusPlus &&
  2187. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2188. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2189. S, Lookup.isForRedeclaration(),
  2190. Lookup.getNameLoc());
  2191. if (D) Lookup.addDecl(D);
  2192. }
  2193. }
  2194. }
  2195. // Sentinel value saying that we didn't do anything special.
  2196. return ExprResult((Expr *)nullptr);
  2197. }
  2198. /// \brief Cast a base object to a member's actual type.
  2199. ///
  2200. /// Logically this happens in three phases:
  2201. ///
  2202. /// * First we cast from the base type to the naming class.
  2203. /// The naming class is the class into which we were looking
  2204. /// when we found the member; it's the qualifier type if a
  2205. /// qualifier was provided, and otherwise it's the base type.
  2206. ///
  2207. /// * Next we cast from the naming class to the declaring class.
  2208. /// If the member we found was brought into a class's scope by
  2209. /// a using declaration, this is that class; otherwise it's
  2210. /// the class declaring the member.
  2211. ///
  2212. /// * Finally we cast from the declaring class to the "true"
  2213. /// declaring class of the member. This conversion does not
  2214. /// obey access control.
  2215. ExprResult
  2216. Sema::PerformObjectMemberConversion(Expr *From,
  2217. NestedNameSpecifier *Qualifier,
  2218. NamedDecl *FoundDecl,
  2219. NamedDecl *Member) {
  2220. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2221. if (!RD)
  2222. return From;
  2223. QualType DestRecordType;
  2224. QualType DestType;
  2225. QualType FromRecordType;
  2226. QualType FromType = From->getType();
  2227. bool PointerConversions = false;
  2228. if (isa<FieldDecl>(Member)) {
  2229. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2230. if (FromType->getAs<PointerType>()) {
  2231. DestType = Context.getPointerType(DestRecordType);
  2232. FromRecordType = FromType->getPointeeType();
  2233. PointerConversions = true;
  2234. } else {
  2235. DestType = DestRecordType;
  2236. FromRecordType = FromType;
  2237. }
  2238. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2239. if (Method->isStatic())
  2240. return From;
  2241. DestType = Method->getThisType(Context);
  2242. DestRecordType = DestType->getPointeeType();
  2243. if (FromType->getAs<PointerType>()) {
  2244. FromRecordType = FromType->getPointeeType();
  2245. PointerConversions = true;
  2246. } else {
  2247. FromRecordType = FromType;
  2248. DestType = DestRecordType;
  2249. }
  2250. } else {
  2251. // No conversion necessary.
  2252. return From;
  2253. }
  2254. if (DestType->isDependentType() || FromType->isDependentType())
  2255. return From;
  2256. // If the unqualified types are the same, no conversion is necessary.
  2257. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2258. return From;
  2259. SourceRange FromRange = From->getSourceRange();
  2260. SourceLocation FromLoc = FromRange.getBegin();
  2261. ExprValueKind VK = From->getValueKind();
  2262. // C++ [class.member.lookup]p8:
  2263. // [...] Ambiguities can often be resolved by qualifying a name with its
  2264. // class name.
  2265. //
  2266. // If the member was a qualified name and the qualified referred to a
  2267. // specific base subobject type, we'll cast to that intermediate type
  2268. // first and then to the object in which the member is declared. That allows
  2269. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2270. //
  2271. // class Base { public: int x; };
  2272. // class Derived1 : public Base { };
  2273. // class Derived2 : public Base { };
  2274. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2275. //
  2276. // void VeryDerived::f() {
  2277. // x = 17; // error: ambiguous base subobjects
  2278. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2279. // }
  2280. if (Qualifier && Qualifier->getAsType()) {
  2281. QualType QType = QualType(Qualifier->getAsType(), 0);
  2282. assert(QType->isRecordType() && "lookup done with non-record type");
  2283. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2284. // In C++98, the qualifier type doesn't actually have to be a base
  2285. // type of the object type, in which case we just ignore it.
  2286. // Otherwise build the appropriate casts.
  2287. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  2288. CXXCastPath BasePath;
  2289. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2290. FromLoc, FromRange, &BasePath))
  2291. return ExprError();
  2292. if (PointerConversions)
  2293. QType = Context.getPointerType(QType);
  2294. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2295. VK, &BasePath).get();
  2296. FromType = QType;
  2297. FromRecordType = QRecordType;
  2298. // If the qualifier type was the same as the destination type,
  2299. // we're done.
  2300. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2301. return From;
  2302. }
  2303. }
  2304. bool IgnoreAccess = false;
  2305. // If we actually found the member through a using declaration, cast
  2306. // down to the using declaration's type.
  2307. //
  2308. // Pointer equality is fine here because only one declaration of a
  2309. // class ever has member declarations.
  2310. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2311. assert(isa<UsingShadowDecl>(FoundDecl));
  2312. QualType URecordType = Context.getTypeDeclType(
  2313. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2314. // We only need to do this if the naming-class to declaring-class
  2315. // conversion is non-trivial.
  2316. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2317. assert(IsDerivedFrom(FromRecordType, URecordType));
  2318. CXXCastPath BasePath;
  2319. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2320. FromLoc, FromRange, &BasePath))
  2321. return ExprError();
  2322. QualType UType = URecordType;
  2323. if (PointerConversions)
  2324. UType = Context.getPointerType(UType);
  2325. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2326. VK, &BasePath).get();
  2327. FromType = UType;
  2328. FromRecordType = URecordType;
  2329. }
  2330. // We don't do access control for the conversion from the
  2331. // declaring class to the true declaring class.
  2332. IgnoreAccess = true;
  2333. }
  2334. CXXCastPath BasePath;
  2335. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2336. FromLoc, FromRange, &BasePath,
  2337. IgnoreAccess))
  2338. return ExprError();
  2339. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2340. VK, &BasePath);
  2341. }
  2342. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2343. const LookupResult &R,
  2344. bool HasTrailingLParen) {
  2345. // Only when used directly as the postfix-expression of a call.
  2346. if (!HasTrailingLParen)
  2347. return false;
  2348. // Never if a scope specifier was provided.
  2349. if (SS.isSet())
  2350. return false;
  2351. // Only in C++ or ObjC++.
  2352. if (!getLangOpts().CPlusPlus)
  2353. return false;
  2354. // Turn off ADL when we find certain kinds of declarations during
  2355. // normal lookup:
  2356. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2357. NamedDecl *D = *I;
  2358. // C++0x [basic.lookup.argdep]p3:
  2359. // -- a declaration of a class member
  2360. // Since using decls preserve this property, we check this on the
  2361. // original decl.
  2362. if (D->isCXXClassMember())
  2363. return false;
  2364. // C++0x [basic.lookup.argdep]p3:
  2365. // -- a block-scope function declaration that is not a
  2366. // using-declaration
  2367. // NOTE: we also trigger this for function templates (in fact, we
  2368. // don't check the decl type at all, since all other decl types
  2369. // turn off ADL anyway).
  2370. if (isa<UsingShadowDecl>(D))
  2371. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2372. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2373. return false;
  2374. // C++0x [basic.lookup.argdep]p3:
  2375. // -- a declaration that is neither a function or a function
  2376. // template
  2377. // And also for builtin functions.
  2378. if (isa<FunctionDecl>(D)) {
  2379. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2380. // But also builtin functions.
  2381. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2382. return false;
  2383. } else if (!isa<FunctionTemplateDecl>(D))
  2384. return false;
  2385. }
  2386. return true;
  2387. }
  2388. /// Diagnoses obvious problems with the use of the given declaration
  2389. /// as an expression. This is only actually called for lookups that
  2390. /// were not overloaded, and it doesn't promise that the declaration
  2391. /// will in fact be used.
  2392. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2393. if (isa<TypedefNameDecl>(D)) {
  2394. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2395. return true;
  2396. }
  2397. if (isa<ObjCInterfaceDecl>(D)) {
  2398. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2399. return true;
  2400. }
  2401. if (isa<NamespaceDecl>(D)) {
  2402. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2403. return true;
  2404. }
  2405. return false;
  2406. }
  2407. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2408. LookupResult &R, bool NeedsADL,
  2409. bool AcceptInvalidDecl) {
  2410. // If this is a single, fully-resolved result and we don't need ADL,
  2411. // just build an ordinary singleton decl ref.
  2412. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2413. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2414. R.getRepresentativeDecl(), nullptr,
  2415. AcceptInvalidDecl);
  2416. // We only need to check the declaration if there's exactly one
  2417. // result, because in the overloaded case the results can only be
  2418. // functions and function templates.
  2419. if (R.isSingleResult() &&
  2420. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2421. return ExprError();
  2422. // Otherwise, just build an unresolved lookup expression. Suppress
  2423. // any lookup-related diagnostics; we'll hash these out later, when
  2424. // we've picked a target.
  2425. R.suppressDiagnostics();
  2426. UnresolvedLookupExpr *ULE
  2427. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2428. SS.getWithLocInContext(Context),
  2429. R.getLookupNameInfo(),
  2430. NeedsADL, R.isOverloadedResult(),
  2431. R.begin(), R.end());
  2432. return ULE;
  2433. }
  2434. /// \brief Complete semantic analysis for a reference to the given declaration.
  2435. ExprResult Sema::BuildDeclarationNameExpr(
  2436. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2437. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2438. bool AcceptInvalidDecl) {
  2439. assert(D && "Cannot refer to a NULL declaration");
  2440. assert(!isa<FunctionTemplateDecl>(D) &&
  2441. "Cannot refer unambiguously to a function template");
  2442. SourceLocation Loc = NameInfo.getLoc();
  2443. if (CheckDeclInExpr(*this, Loc, D))
  2444. return ExprError();
  2445. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2446. // Specifically diagnose references to class templates that are missing
  2447. // a template argument list.
  2448. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2449. << Template << SS.getRange();
  2450. Diag(Template->getLocation(), diag::note_template_decl_here);
  2451. return ExprError();
  2452. }
  2453. // Make sure that we're referring to a value.
  2454. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2455. if (!VD) {
  2456. Diag(Loc, diag::err_ref_non_value)
  2457. << D << SS.getRange();
  2458. Diag(D->getLocation(), diag::note_declared_at);
  2459. return ExprError();
  2460. }
  2461. // Check whether this declaration can be used. Note that we suppress
  2462. // this check when we're going to perform argument-dependent lookup
  2463. // on this function name, because this might not be the function
  2464. // that overload resolution actually selects.
  2465. if (DiagnoseUseOfDecl(VD, Loc))
  2466. return ExprError();
  2467. // Only create DeclRefExpr's for valid Decl's.
  2468. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2469. return ExprError();
  2470. // Handle members of anonymous structs and unions. If we got here,
  2471. // and the reference is to a class member indirect field, then this
  2472. // must be the subject of a pointer-to-member expression.
  2473. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2474. if (!indirectField->isCXXClassMember())
  2475. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2476. indirectField);
  2477. {
  2478. QualType type = VD->getType();
  2479. ExprValueKind valueKind = VK_RValue;
  2480. switch (D->getKind()) {
  2481. // Ignore all the non-ValueDecl kinds.
  2482. #define ABSTRACT_DECL(kind)
  2483. #define VALUE(type, base)
  2484. #define DECL(type, base) \
  2485. case Decl::type:
  2486. #include "clang/AST/DeclNodes.inc"
  2487. llvm_unreachable("invalid value decl kind");
  2488. // These shouldn't make it here.
  2489. case Decl::ObjCAtDefsField:
  2490. case Decl::ObjCIvar:
  2491. llvm_unreachable("forming non-member reference to ivar?");
  2492. // Enum constants are always r-values and never references.
  2493. // Unresolved using declarations are dependent.
  2494. case Decl::EnumConstant:
  2495. case Decl::UnresolvedUsingValue:
  2496. valueKind = VK_RValue;
  2497. break;
  2498. // Fields and indirect fields that got here must be for
  2499. // pointer-to-member expressions; we just call them l-values for
  2500. // internal consistency, because this subexpression doesn't really
  2501. // exist in the high-level semantics.
  2502. case Decl::Field:
  2503. case Decl::IndirectField:
  2504. assert(getLangOpts().CPlusPlus &&
  2505. "building reference to field in C?");
  2506. // These can't have reference type in well-formed programs, but
  2507. // for internal consistency we do this anyway.
  2508. type = type.getNonReferenceType();
  2509. valueKind = VK_LValue;
  2510. break;
  2511. // Non-type template parameters are either l-values or r-values
  2512. // depending on the type.
  2513. case Decl::NonTypeTemplateParm: {
  2514. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2515. type = reftype->getPointeeType();
  2516. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2517. break;
  2518. }
  2519. // For non-references, we need to strip qualifiers just in case
  2520. // the template parameter was declared as 'const int' or whatever.
  2521. valueKind = VK_RValue;
  2522. type = type.getUnqualifiedType();
  2523. break;
  2524. }
  2525. case Decl::Var:
  2526. case Decl::VarTemplateSpecialization:
  2527. case Decl::VarTemplatePartialSpecialization:
  2528. // In C, "extern void blah;" is valid and is an r-value.
  2529. if (!getLangOpts().CPlusPlus &&
  2530. !type.hasQualifiers() &&
  2531. type->isVoidType()) {
  2532. valueKind = VK_RValue;
  2533. break;
  2534. }
  2535. // fallthrough
  2536. case Decl::ImplicitParam:
  2537. case Decl::ParmVar: {
  2538. // These are always l-values.
  2539. valueKind = VK_LValue;
  2540. type = type.getNonReferenceType();
  2541. // FIXME: Does the addition of const really only apply in
  2542. // potentially-evaluated contexts? Since the variable isn't actually
  2543. // captured in an unevaluated context, it seems that the answer is no.
  2544. if (!isUnevaluatedContext()) {
  2545. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2546. if (!CapturedType.isNull())
  2547. type = CapturedType;
  2548. }
  2549. break;
  2550. }
  2551. case Decl::Function: {
  2552. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2553. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2554. type = Context.BuiltinFnTy;
  2555. valueKind = VK_RValue;
  2556. break;
  2557. }
  2558. }
  2559. const FunctionType *fty = type->castAs<FunctionType>();
  2560. // If we're referring to a function with an __unknown_anytype
  2561. // result type, make the entire expression __unknown_anytype.
  2562. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2563. type = Context.UnknownAnyTy;
  2564. valueKind = VK_RValue;
  2565. break;
  2566. }
  2567. // Functions are l-values in C++.
  2568. if (getLangOpts().CPlusPlus) {
  2569. valueKind = VK_LValue;
  2570. break;
  2571. }
  2572. // C99 DR 316 says that, if a function type comes from a
  2573. // function definition (without a prototype), that type is only
  2574. // used for checking compatibility. Therefore, when referencing
  2575. // the function, we pretend that we don't have the full function
  2576. // type.
  2577. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2578. isa<FunctionProtoType>(fty))
  2579. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2580. fty->getExtInfo());
  2581. // Functions are r-values in C.
  2582. valueKind = VK_RValue;
  2583. break;
  2584. }
  2585. case Decl::MSProperty:
  2586. valueKind = VK_LValue;
  2587. break;
  2588. case Decl::CXXMethod:
  2589. // If we're referring to a method with an __unknown_anytype
  2590. // result type, make the entire expression __unknown_anytype.
  2591. // This should only be possible with a type written directly.
  2592. if (const FunctionProtoType *proto
  2593. = dyn_cast<FunctionProtoType>(VD->getType()))
  2594. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2595. type = Context.UnknownAnyTy;
  2596. valueKind = VK_RValue;
  2597. break;
  2598. }
  2599. // C++ methods are l-values if static, r-values if non-static.
  2600. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2601. valueKind = VK_LValue;
  2602. break;
  2603. }
  2604. // fallthrough
  2605. case Decl::CXXConversion:
  2606. case Decl::CXXDestructor:
  2607. case Decl::CXXConstructor:
  2608. valueKind = VK_RValue;
  2609. break;
  2610. }
  2611. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2612. TemplateArgs);
  2613. }
  2614. }
  2615. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2616. SmallString<32> &Target) {
  2617. Target.resize(CharByteWidth * (Source.size() + 1));
  2618. char *ResultPtr = &Target[0];
  2619. const UTF8 *ErrorPtr;
  2620. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2621. (void)success;
  2622. assert(success);
  2623. Target.resize(ResultPtr - &Target[0]);
  2624. }
  2625. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2626. PredefinedExpr::IdentType IT) {
  2627. // Pick the current block, lambda, captured statement or function.
  2628. Decl *currentDecl = nullptr;
  2629. if (const BlockScopeInfo *BSI = getCurBlock())
  2630. currentDecl = BSI->TheDecl;
  2631. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2632. currentDecl = LSI->CallOperator;
  2633. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2634. currentDecl = CSI->TheCapturedDecl;
  2635. else
  2636. currentDecl = getCurFunctionOrMethodDecl();
  2637. if (!currentDecl) {
  2638. Diag(Loc, diag::ext_predef_outside_function);
  2639. currentDecl = Context.getTranslationUnitDecl();
  2640. }
  2641. QualType ResTy;
  2642. StringLiteral *SL = nullptr;
  2643. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2644. ResTy = Context.DependentTy;
  2645. else {
  2646. // Pre-defined identifiers are of type char[x], where x is the length of
  2647. // the string.
  2648. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2649. unsigned Length = Str.length();
  2650. llvm::APInt LengthI(32, Length + 1);
  2651. if (IT == PredefinedExpr::LFunction) {
  2652. ResTy = Context.WideCharTy.withConst();
  2653. SmallString<32> RawChars;
  2654. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2655. Str, RawChars);
  2656. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2657. /*IndexTypeQuals*/ 0);
  2658. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2659. /*Pascal*/ false, ResTy, Loc);
  2660. } else {
  2661. ResTy = Context.CharTy.withConst();
  2662. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2663. /*IndexTypeQuals*/ 0);
  2664. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2665. /*Pascal*/ false, ResTy, Loc);
  2666. }
  2667. }
  2668. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2669. }
  2670. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2671. PredefinedExpr::IdentType IT;
  2672. switch (Kind) {
  2673. default: llvm_unreachable("Unknown simple primary expr!");
  2674. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2675. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2676. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2677. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2678. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2679. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2680. }
  2681. return BuildPredefinedExpr(Loc, IT);
  2682. }
  2683. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2684. SmallString<16> CharBuffer;
  2685. bool Invalid = false;
  2686. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2687. if (Invalid)
  2688. return ExprError();
  2689. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2690. PP, Tok.getKind());
  2691. if (Literal.hadError())
  2692. return ExprError();
  2693. QualType Ty;
  2694. if (Literal.isWide())
  2695. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2696. else if (Literal.isUTF16())
  2697. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2698. else if (Literal.isUTF32())
  2699. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2700. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2701. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2702. else
  2703. Ty = Context.CharTy; // 'x' -> char in C++
  2704. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2705. if (Literal.isWide())
  2706. Kind = CharacterLiteral::Wide;
  2707. else if (Literal.isUTF16())
  2708. Kind = CharacterLiteral::UTF16;
  2709. else if (Literal.isUTF32())
  2710. Kind = CharacterLiteral::UTF32;
  2711. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2712. Tok.getLocation());
  2713. if (Literal.getUDSuffix().empty())
  2714. return Lit;
  2715. // We're building a user-defined literal.
  2716. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2717. SourceLocation UDSuffixLoc =
  2718. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2719. // Make sure we're allowed user-defined literals here.
  2720. if (!UDLScope)
  2721. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2722. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2723. // operator "" X (ch)
  2724. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2725. Lit, Tok.getLocation());
  2726. }
  2727. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2728. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2729. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2730. Context.IntTy, Loc);
  2731. }
  2732. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2733. QualType Ty, SourceLocation Loc) {
  2734. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2735. using llvm::APFloat;
  2736. APFloat Val(Format);
  2737. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2738. // Overflow is always an error, but underflow is only an error if
  2739. // we underflowed to zero (APFloat reports denormals as underflow).
  2740. if ((result & APFloat::opOverflow) ||
  2741. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2742. unsigned diagnostic;
  2743. SmallString<20> buffer;
  2744. if (result & APFloat::opOverflow) {
  2745. diagnostic = diag::warn_float_overflow;
  2746. APFloat::getLargest(Format).toString(buffer);
  2747. } else {
  2748. diagnostic = diag::warn_float_underflow;
  2749. APFloat::getSmallest(Format).toString(buffer);
  2750. }
  2751. S.Diag(Loc, diagnostic)
  2752. << Ty
  2753. << StringRef(buffer.data(), buffer.size());
  2754. }
  2755. bool isExact = (result == APFloat::opOK);
  2756. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2757. }
  2758. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2759. assert(E && "Invalid expression");
  2760. if (E->isValueDependent())
  2761. return false;
  2762. QualType QT = E->getType();
  2763. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2764. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2765. return true;
  2766. }
  2767. llvm::APSInt ValueAPS;
  2768. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2769. if (R.isInvalid())
  2770. return true;
  2771. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2772. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2773. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2774. << ValueAPS.toString(10) << ValueIsPositive;
  2775. return true;
  2776. }
  2777. return false;
  2778. }
  2779. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2780. // Fast path for a single digit (which is quite common). A single digit
  2781. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2782. if (Tok.getLength() == 1) {
  2783. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2784. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2785. }
  2786. SmallString<128> SpellingBuffer;
  2787. // NumericLiteralParser wants to overread by one character. Add padding to
  2788. // the buffer in case the token is copied to the buffer. If getSpelling()
  2789. // returns a StringRef to the memory buffer, it should have a null char at
  2790. // the EOF, so it is also safe.
  2791. SpellingBuffer.resize(Tok.getLength() + 1);
  2792. // Get the spelling of the token, which eliminates trigraphs, etc.
  2793. bool Invalid = false;
  2794. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2795. if (Invalid)
  2796. return ExprError();
  2797. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2798. if (Literal.hadError)
  2799. return ExprError();
  2800. if (Literal.hasUDSuffix()) {
  2801. // We're building a user-defined literal.
  2802. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2803. SourceLocation UDSuffixLoc =
  2804. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2805. // Make sure we're allowed user-defined literals here.
  2806. if (!UDLScope)
  2807. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2808. QualType CookedTy;
  2809. if (Literal.isFloatingLiteral()) {
  2810. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2811. // long double, the literal is treated as a call of the form
  2812. // operator "" X (f L)
  2813. CookedTy = Context.LongDoubleTy;
  2814. } else {
  2815. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2816. // unsigned long long, the literal is treated as a call of the form
  2817. // operator "" X (n ULL)
  2818. CookedTy = Context.UnsignedLongLongTy;
  2819. }
  2820. DeclarationName OpName =
  2821. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2822. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2823. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2824. SourceLocation TokLoc = Tok.getLocation();
  2825. // Perform literal operator lookup to determine if we're building a raw
  2826. // literal or a cooked one.
  2827. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2828. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2829. /*AllowRaw*/true, /*AllowTemplate*/true,
  2830. /*AllowStringTemplate*/false)) {
  2831. case LOLR_Error:
  2832. return ExprError();
  2833. case LOLR_Cooked: {
  2834. Expr *Lit;
  2835. if (Literal.isFloatingLiteral()) {
  2836. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2837. } else {
  2838. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2839. if (Literal.GetIntegerValue(ResultVal))
  2840. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2841. << /* Unsigned */ 1;
  2842. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2843. Tok.getLocation());
  2844. }
  2845. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2846. }
  2847. case LOLR_Raw: {
  2848. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2849. // literal is treated as a call of the form
  2850. // operator "" X ("n")
  2851. unsigned Length = Literal.getUDSuffixOffset();
  2852. QualType StrTy = Context.getConstantArrayType(
  2853. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2854. ArrayType::Normal, 0);
  2855. Expr *Lit = StringLiteral::Create(
  2856. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2857. /*Pascal*/false, StrTy, &TokLoc, 1);
  2858. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2859. }
  2860. case LOLR_Template: {
  2861. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2862. // template), L is treated as a call fo the form
  2863. // operator "" X <'c1', 'c2', ... 'ck'>()
  2864. // where n is the source character sequence c1 c2 ... ck.
  2865. TemplateArgumentListInfo ExplicitArgs;
  2866. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2867. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2868. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2869. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2870. Value = TokSpelling[I];
  2871. TemplateArgument Arg(Context, Value, Context.CharTy);
  2872. TemplateArgumentLocInfo ArgInfo;
  2873. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2874. }
  2875. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2876. &ExplicitArgs);
  2877. }
  2878. case LOLR_StringTemplate:
  2879. llvm_unreachable("unexpected literal operator lookup result");
  2880. }
  2881. }
  2882. Expr *Res;
  2883. if (Literal.isFloatingLiteral()) {
  2884. QualType Ty;
  2885. if (Literal.isFloat)
  2886. Ty = Context.FloatTy;
  2887. else if (!Literal.isLong)
  2888. Ty = Context.DoubleTy;
  2889. else
  2890. Ty = Context.LongDoubleTy;
  2891. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2892. if (Ty == Context.DoubleTy) {
  2893. if (getLangOpts().SinglePrecisionConstants) {
  2894. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2895. } else if (getLangOpts().OpenCL &&
  2896. !((getLangOpts().OpenCLVersion >= 120) ||
  2897. getOpenCLOptions().cl_khr_fp64)) {
  2898. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2899. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2900. }
  2901. }
  2902. } else if (!Literal.isIntegerLiteral()) {
  2903. return ExprError();
  2904. } else {
  2905. QualType Ty;
  2906. // 'long long' is a C99 or C++11 feature.
  2907. if (!getLangOpts().C99 && Literal.isLongLong) {
  2908. if (getLangOpts().CPlusPlus)
  2909. Diag(Tok.getLocation(),
  2910. getLangOpts().CPlusPlus11 ?
  2911. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  2912. else
  2913. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  2914. }
  2915. // Get the value in the widest-possible width.
  2916. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  2917. llvm::APInt ResultVal(MaxWidth, 0);
  2918. if (Literal.GetIntegerValue(ResultVal)) {
  2919. // If this value didn't fit into uintmax_t, error and force to ull.
  2920. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2921. << /* Unsigned */ 1;
  2922. Ty = Context.UnsignedLongLongTy;
  2923. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  2924. "long long is not intmax_t?");
  2925. } else {
  2926. // If this value fits into a ULL, try to figure out what else it fits into
  2927. // according to the rules of C99 6.4.4.1p5.
  2928. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  2929. // be an unsigned int.
  2930. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  2931. // Check from smallest to largest, picking the smallest type we can.
  2932. unsigned Width = 0;
  2933. // Microsoft specific integer suffixes are explicitly sized.
  2934. if (Literal.MicrosoftInteger) {
  2935. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  2936. Width = 8;
  2937. Ty = Context.CharTy;
  2938. } else {
  2939. Width = Literal.MicrosoftInteger;
  2940. Ty = Context.getIntTypeForBitwidth(Width,
  2941. /*Signed=*/!Literal.isUnsigned);
  2942. }
  2943. }
  2944. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  2945. // Are int/unsigned possibilities?
  2946. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2947. // Does it fit in a unsigned int?
  2948. if (ResultVal.isIntN(IntSize)) {
  2949. // Does it fit in a signed int?
  2950. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  2951. Ty = Context.IntTy;
  2952. else if (AllowUnsigned)
  2953. Ty = Context.UnsignedIntTy;
  2954. Width = IntSize;
  2955. }
  2956. }
  2957. // Are long/unsigned long possibilities?
  2958. if (Ty.isNull() && !Literal.isLongLong) {
  2959. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  2960. // Does it fit in a unsigned long?
  2961. if (ResultVal.isIntN(LongSize)) {
  2962. // Does it fit in a signed long?
  2963. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  2964. Ty = Context.LongTy;
  2965. else if (AllowUnsigned)
  2966. Ty = Context.UnsignedLongTy;
  2967. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  2968. // is compatible.
  2969. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  2970. const unsigned LongLongSize =
  2971. Context.getTargetInfo().getLongLongWidth();
  2972. Diag(Tok.getLocation(),
  2973. getLangOpts().CPlusPlus
  2974. ? Literal.isLong
  2975. ? diag::warn_old_implicitly_unsigned_long_cxx
  2976. : /*C++98 UB*/ diag::
  2977. ext_old_implicitly_unsigned_long_cxx
  2978. : diag::warn_old_implicitly_unsigned_long)
  2979. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  2980. : /*will be ill-formed*/ 1);
  2981. Ty = Context.UnsignedLongTy;
  2982. }
  2983. Width = LongSize;
  2984. }
  2985. }
  2986. // Check long long if needed.
  2987. if (Ty.isNull()) {
  2988. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  2989. // Does it fit in a unsigned long long?
  2990. if (ResultVal.isIntN(LongLongSize)) {
  2991. // Does it fit in a signed long long?
  2992. // To be compatible with MSVC, hex integer literals ending with the
  2993. // LL or i64 suffix are always signed in Microsoft mode.
  2994. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  2995. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  2996. Ty = Context.LongLongTy;
  2997. else if (AllowUnsigned)
  2998. Ty = Context.UnsignedLongLongTy;
  2999. Width = LongLongSize;
  3000. }
  3001. }
  3002. // If we still couldn't decide a type, we probably have something that
  3003. // does not fit in a signed long long, but has no U suffix.
  3004. if (Ty.isNull()) {
  3005. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3006. Ty = Context.UnsignedLongLongTy;
  3007. Width = Context.getTargetInfo().getLongLongWidth();
  3008. }
  3009. if (ResultVal.getBitWidth() != Width)
  3010. ResultVal = ResultVal.trunc(Width);
  3011. }
  3012. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3013. }
  3014. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3015. if (Literal.isImaginary)
  3016. Res = new (Context) ImaginaryLiteral(Res,
  3017. Context.getComplexType(Res->getType()));
  3018. return Res;
  3019. }
  3020. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3021. assert(E && "ActOnParenExpr() missing expr");
  3022. return new (Context) ParenExpr(L, R, E);
  3023. }
  3024. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3025. SourceLocation Loc,
  3026. SourceRange ArgRange) {
  3027. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3028. // scalar or vector data type argument..."
  3029. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3030. // type (C99 6.2.5p18) or void.
  3031. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3032. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3033. << T << ArgRange;
  3034. return true;
  3035. }
  3036. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3037. "Scalar types should always be complete");
  3038. return false;
  3039. }
  3040. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3041. SourceLocation Loc,
  3042. SourceRange ArgRange,
  3043. UnaryExprOrTypeTrait TraitKind) {
  3044. // Invalid types must be hard errors for SFINAE in C++.
  3045. if (S.LangOpts.CPlusPlus)
  3046. return true;
  3047. // C99 6.5.3.4p1:
  3048. if (T->isFunctionType() &&
  3049. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3050. // sizeof(function)/alignof(function) is allowed as an extension.
  3051. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3052. << TraitKind << ArgRange;
  3053. return false;
  3054. }
  3055. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3056. // this is an error (OpenCL v1.1 s6.3.k)
  3057. if (T->isVoidType()) {
  3058. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3059. : diag::ext_sizeof_alignof_void_type;
  3060. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3061. return false;
  3062. }
  3063. return true;
  3064. }
  3065. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3066. SourceLocation Loc,
  3067. SourceRange ArgRange,
  3068. UnaryExprOrTypeTrait TraitKind) {
  3069. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3070. // runtime doesn't allow it.
  3071. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3072. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3073. << T << (TraitKind == UETT_SizeOf)
  3074. << ArgRange;
  3075. return true;
  3076. }
  3077. return false;
  3078. }
  3079. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3080. /// pointer type is equal to T) and emit a warning if it is.
  3081. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3082. Expr *E) {
  3083. // Don't warn if the operation changed the type.
  3084. if (T != E->getType())
  3085. return;
  3086. // Now look for array decays.
  3087. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3088. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3089. return;
  3090. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3091. << ICE->getType()
  3092. << ICE->getSubExpr()->getType();
  3093. }
  3094. /// \brief Check the constraints on expression operands to unary type expression
  3095. /// and type traits.
  3096. ///
  3097. /// Completes any types necessary and validates the constraints on the operand
  3098. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3099. /// the expression as it completes the type for that expression through template
  3100. /// instantiation, etc.
  3101. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3102. UnaryExprOrTypeTrait ExprKind) {
  3103. QualType ExprTy = E->getType();
  3104. assert(!ExprTy->isReferenceType());
  3105. if (ExprKind == UETT_VecStep)
  3106. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3107. E->getSourceRange());
  3108. // Whitelist some types as extensions
  3109. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3110. E->getSourceRange(), ExprKind))
  3111. return false;
  3112. // 'alignof' applied to an expression only requires the base element type of
  3113. // the expression to be complete. 'sizeof' requires the expression's type to
  3114. // be complete (and will attempt to complete it if it's an array of unknown
  3115. // bound).
  3116. if (ExprKind == UETT_AlignOf) {
  3117. if (RequireCompleteType(E->getExprLoc(),
  3118. Context.getBaseElementType(E->getType()),
  3119. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3120. E->getSourceRange()))
  3121. return true;
  3122. } else {
  3123. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3124. ExprKind, E->getSourceRange()))
  3125. return true;
  3126. }
  3127. // Completing the expression's type may have changed it.
  3128. ExprTy = E->getType();
  3129. assert(!ExprTy->isReferenceType());
  3130. if (ExprTy->isFunctionType()) {
  3131. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3132. << ExprKind << E->getSourceRange();
  3133. return true;
  3134. }
  3135. // The operand for sizeof and alignof is in an unevaluated expression context,
  3136. // so side effects could result in unintended consequences.
  3137. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3138. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3139. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3140. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3141. E->getSourceRange(), ExprKind))
  3142. return true;
  3143. if (ExprKind == UETT_SizeOf) {
  3144. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3145. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3146. QualType OType = PVD->getOriginalType();
  3147. QualType Type = PVD->getType();
  3148. if (Type->isPointerType() && OType->isArrayType()) {
  3149. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3150. << Type << OType;
  3151. Diag(PVD->getLocation(), diag::note_declared_at);
  3152. }
  3153. }
  3154. }
  3155. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3156. // decays into a pointer and returns an unintended result. This is most
  3157. // likely a typo for "sizeof(array) op x".
  3158. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3159. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3160. BO->getLHS());
  3161. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3162. BO->getRHS());
  3163. }
  3164. }
  3165. return false;
  3166. }
  3167. /// \brief Check the constraints on operands to unary expression and type
  3168. /// traits.
  3169. ///
  3170. /// This will complete any types necessary, and validate the various constraints
  3171. /// on those operands.
  3172. ///
  3173. /// The UsualUnaryConversions() function is *not* called by this routine.
  3174. /// C99 6.3.2.1p[2-4] all state:
  3175. /// Except when it is the operand of the sizeof operator ...
  3176. ///
  3177. /// C++ [expr.sizeof]p4
  3178. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3179. /// standard conversions are not applied to the operand of sizeof.
  3180. ///
  3181. /// This policy is followed for all of the unary trait expressions.
  3182. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3183. SourceLocation OpLoc,
  3184. SourceRange ExprRange,
  3185. UnaryExprOrTypeTrait ExprKind) {
  3186. if (ExprType->isDependentType())
  3187. return false;
  3188. // C++ [expr.sizeof]p2:
  3189. // When applied to a reference or a reference type, the result
  3190. // is the size of the referenced type.
  3191. // C++11 [expr.alignof]p3:
  3192. // When alignof is applied to a reference type, the result
  3193. // shall be the alignment of the referenced type.
  3194. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3195. ExprType = Ref->getPointeeType();
  3196. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3197. // When alignof or _Alignof is applied to an array type, the result
  3198. // is the alignment of the element type.
  3199. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3200. ExprType = Context.getBaseElementType(ExprType);
  3201. if (ExprKind == UETT_VecStep)
  3202. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3203. // Whitelist some types as extensions
  3204. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3205. ExprKind))
  3206. return false;
  3207. if (RequireCompleteType(OpLoc, ExprType,
  3208. diag::err_sizeof_alignof_incomplete_type,
  3209. ExprKind, ExprRange))
  3210. return true;
  3211. if (ExprType->isFunctionType()) {
  3212. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3213. << ExprKind << ExprRange;
  3214. return true;
  3215. }
  3216. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3217. ExprKind))
  3218. return true;
  3219. return false;
  3220. }
  3221. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3222. E = E->IgnoreParens();
  3223. // Cannot know anything else if the expression is dependent.
  3224. if (E->isTypeDependent())
  3225. return false;
  3226. if (E->getObjectKind() == OK_BitField) {
  3227. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3228. << 1 << E->getSourceRange();
  3229. return true;
  3230. }
  3231. ValueDecl *D = nullptr;
  3232. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3233. D = DRE->getDecl();
  3234. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3235. D = ME->getMemberDecl();
  3236. }
  3237. // If it's a field, require the containing struct to have a
  3238. // complete definition so that we can compute the layout.
  3239. //
  3240. // This can happen in C++11 onwards, either by naming the member
  3241. // in a way that is not transformed into a member access expression
  3242. // (in an unevaluated operand, for instance), or by naming the member
  3243. // in a trailing-return-type.
  3244. //
  3245. // For the record, since __alignof__ on expressions is a GCC
  3246. // extension, GCC seems to permit this but always gives the
  3247. // nonsensical answer 0.
  3248. //
  3249. // We don't really need the layout here --- we could instead just
  3250. // directly check for all the appropriate alignment-lowing
  3251. // attributes --- but that would require duplicating a lot of
  3252. // logic that just isn't worth duplicating for such a marginal
  3253. // use-case.
  3254. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3255. // Fast path this check, since we at least know the record has a
  3256. // definition if we can find a member of it.
  3257. if (!FD->getParent()->isCompleteDefinition()) {
  3258. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3259. << E->getSourceRange();
  3260. return true;
  3261. }
  3262. // Otherwise, if it's a field, and the field doesn't have
  3263. // reference type, then it must have a complete type (or be a
  3264. // flexible array member, which we explicitly want to
  3265. // white-list anyway), which makes the following checks trivial.
  3266. if (!FD->getType()->isReferenceType())
  3267. return false;
  3268. }
  3269. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3270. }
  3271. bool Sema::CheckVecStepExpr(Expr *E) {
  3272. E = E->IgnoreParens();
  3273. // Cannot know anything else if the expression is dependent.
  3274. if (E->isTypeDependent())
  3275. return false;
  3276. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3277. }
  3278. /// \brief Build a sizeof or alignof expression given a type operand.
  3279. ExprResult
  3280. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3281. SourceLocation OpLoc,
  3282. UnaryExprOrTypeTrait ExprKind,
  3283. SourceRange R) {
  3284. if (!TInfo)
  3285. return ExprError();
  3286. QualType T = TInfo->getType();
  3287. if (!T->isDependentType() &&
  3288. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3289. return ExprError();
  3290. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3291. return new (Context) UnaryExprOrTypeTraitExpr(
  3292. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3293. }
  3294. /// \brief Build a sizeof or alignof expression given an expression
  3295. /// operand.
  3296. ExprResult
  3297. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3298. UnaryExprOrTypeTrait ExprKind) {
  3299. ExprResult PE = CheckPlaceholderExpr(E);
  3300. if (PE.isInvalid())
  3301. return ExprError();
  3302. E = PE.get();
  3303. // Verify that the operand is valid.
  3304. bool isInvalid = false;
  3305. if (E->isTypeDependent()) {
  3306. // Delay type-checking for type-dependent expressions.
  3307. } else if (ExprKind == UETT_AlignOf) {
  3308. isInvalid = CheckAlignOfExpr(*this, E);
  3309. } else if (ExprKind == UETT_VecStep) {
  3310. isInvalid = CheckVecStepExpr(E);
  3311. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3312. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3313. isInvalid = true;
  3314. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3315. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3316. isInvalid = true;
  3317. } else {
  3318. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3319. }
  3320. if (isInvalid)
  3321. return ExprError();
  3322. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3323. PE = TransformToPotentiallyEvaluated(E);
  3324. if (PE.isInvalid()) return ExprError();
  3325. E = PE.get();
  3326. }
  3327. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3328. return new (Context) UnaryExprOrTypeTraitExpr(
  3329. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3330. }
  3331. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3332. /// expr and the same for @c alignof and @c __alignof
  3333. /// Note that the ArgRange is invalid if isType is false.
  3334. ExprResult
  3335. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3336. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3337. void *TyOrEx, SourceRange ArgRange) {
  3338. // If error parsing type, ignore.
  3339. if (!TyOrEx) return ExprError();
  3340. if (IsType) {
  3341. TypeSourceInfo *TInfo;
  3342. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3343. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3344. }
  3345. Expr *ArgEx = (Expr *)TyOrEx;
  3346. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3347. return Result;
  3348. }
  3349. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3350. bool IsReal) {
  3351. if (V.get()->isTypeDependent())
  3352. return S.Context.DependentTy;
  3353. // _Real and _Imag are only l-values for normal l-values.
  3354. if (V.get()->getObjectKind() != OK_Ordinary) {
  3355. V = S.DefaultLvalueConversion(V.get());
  3356. if (V.isInvalid())
  3357. return QualType();
  3358. }
  3359. // These operators return the element type of a complex type.
  3360. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3361. return CT->getElementType();
  3362. // Otherwise they pass through real integer and floating point types here.
  3363. if (V.get()->getType()->isArithmeticType())
  3364. return V.get()->getType();
  3365. // Test for placeholders.
  3366. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3367. if (PR.isInvalid()) return QualType();
  3368. if (PR.get() != V.get()) {
  3369. V = PR;
  3370. return CheckRealImagOperand(S, V, Loc, IsReal);
  3371. }
  3372. // Reject anything else.
  3373. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3374. << (IsReal ? "__real" : "__imag");
  3375. return QualType();
  3376. }
  3377. ExprResult
  3378. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3379. tok::TokenKind Kind, Expr *Input) {
  3380. UnaryOperatorKind Opc;
  3381. switch (Kind) {
  3382. default: llvm_unreachable("Unknown unary op!");
  3383. case tok::plusplus: Opc = UO_PostInc; break;
  3384. case tok::minusminus: Opc = UO_PostDec; break;
  3385. }
  3386. // Since this might is a postfix expression, get rid of ParenListExprs.
  3387. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3388. if (Result.isInvalid()) return ExprError();
  3389. Input = Result.get();
  3390. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3391. }
  3392. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3393. ///
  3394. /// \return true on error
  3395. static bool checkArithmeticOnObjCPointer(Sema &S,
  3396. SourceLocation opLoc,
  3397. Expr *op) {
  3398. assert(op->getType()->isObjCObjectPointerType());
  3399. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3400. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3401. return false;
  3402. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3403. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3404. << op->getSourceRange();
  3405. return true;
  3406. }
  3407. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3408. auto *BaseNoParens = Base->IgnoreParens();
  3409. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3410. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3411. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3412. }
  3413. ExprResult
  3414. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3415. Expr *idx, SourceLocation rbLoc) {
  3416. if (base && !base->getType().isNull() &&
  3417. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3418. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3419. /*Length=*/nullptr, rbLoc);
  3420. // Since this might be a postfix expression, get rid of ParenListExprs.
  3421. if (isa<ParenListExpr>(base)) {
  3422. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3423. if (result.isInvalid()) return ExprError();
  3424. base = result.get();
  3425. }
  3426. // Handle any non-overload placeholder types in the base and index
  3427. // expressions. We can't handle overloads here because the other
  3428. // operand might be an overloadable type, in which case the overload
  3429. // resolution for the operator overload should get the first crack
  3430. // at the overload.
  3431. bool IsMSPropertySubscript = false;
  3432. if (base->getType()->isNonOverloadPlaceholderType()) {
  3433. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3434. if (!IsMSPropertySubscript) {
  3435. ExprResult result = CheckPlaceholderExpr(base);
  3436. if (result.isInvalid())
  3437. return ExprError();
  3438. base = result.get();
  3439. }
  3440. }
  3441. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3442. ExprResult result = CheckPlaceholderExpr(idx);
  3443. if (result.isInvalid()) return ExprError();
  3444. idx = result.get();
  3445. }
  3446. // Build an unanalyzed expression if either operand is type-dependent.
  3447. if (getLangOpts().CPlusPlus &&
  3448. (base->isTypeDependent() || idx->isTypeDependent())) {
  3449. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3450. VK_LValue, OK_Ordinary, rbLoc);
  3451. }
  3452. // MSDN, property (C++)
  3453. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3454. // This attribute can also be used in the declaration of an empty array in a
  3455. // class or structure definition. For example:
  3456. // __declspec(property(get=GetX, put=PutX)) int x[];
  3457. // The above statement indicates that x[] can be used with one or more array
  3458. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3459. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3460. if (IsMSPropertySubscript) {
  3461. // Build MS property subscript expression if base is MS property reference
  3462. // or MS property subscript.
  3463. return new (Context) MSPropertySubscriptExpr(
  3464. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3465. }
  3466. // Use C++ overloaded-operator rules if either operand has record
  3467. // type. The spec says to do this if either type is *overloadable*,
  3468. // but enum types can't declare subscript operators or conversion
  3469. // operators, so there's nothing interesting for overload resolution
  3470. // to do if there aren't any record types involved.
  3471. //
  3472. // ObjC pointers have their own subscripting logic that is not tied
  3473. // to overload resolution and so should not take this path.
  3474. if (getLangOpts().CPlusPlus &&
  3475. (base->getType()->isRecordType() ||
  3476. (!base->getType()->isObjCObjectPointerType() &&
  3477. idx->getType()->isRecordType()))) {
  3478. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3479. }
  3480. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3481. }
  3482. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3483. Expr *LowerBound,
  3484. SourceLocation ColonLoc, Expr *Length,
  3485. SourceLocation RBLoc) {
  3486. if (Base->getType()->isPlaceholderType() &&
  3487. !Base->getType()->isSpecificPlaceholderType(
  3488. BuiltinType::OMPArraySection)) {
  3489. ExprResult Result = CheckPlaceholderExpr(Base);
  3490. if (Result.isInvalid())
  3491. return ExprError();
  3492. Base = Result.get();
  3493. }
  3494. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3495. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3496. if (Result.isInvalid())
  3497. return ExprError();
  3498. LowerBound = Result.get();
  3499. }
  3500. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3501. ExprResult Result = CheckPlaceholderExpr(Length);
  3502. if (Result.isInvalid())
  3503. return ExprError();
  3504. Length = Result.get();
  3505. }
  3506. // Build an unanalyzed expression if either operand is type-dependent.
  3507. if (Base->isTypeDependent() ||
  3508. (LowerBound &&
  3509. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3510. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3511. return new (Context)
  3512. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3513. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3514. }
  3515. // Perform default conversions.
  3516. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3517. QualType ResultTy;
  3518. if (OriginalTy->isAnyPointerType()) {
  3519. ResultTy = OriginalTy->getPointeeType();
  3520. } else if (OriginalTy->isArrayType()) {
  3521. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3522. } else {
  3523. return ExprError(
  3524. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3525. << Base->getSourceRange());
  3526. }
  3527. // C99 6.5.2.1p1
  3528. if (LowerBound) {
  3529. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3530. LowerBound);
  3531. if (Res.isInvalid())
  3532. return ExprError(Diag(LowerBound->getExprLoc(),
  3533. diag::err_omp_typecheck_section_not_integer)
  3534. << 0 << LowerBound->getSourceRange());
  3535. LowerBound = Res.get();
  3536. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3537. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3538. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3539. << 0 << LowerBound->getSourceRange();
  3540. }
  3541. if (Length) {
  3542. auto Res =
  3543. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3544. if (Res.isInvalid())
  3545. return ExprError(Diag(Length->getExprLoc(),
  3546. diag::err_omp_typecheck_section_not_integer)
  3547. << 1 << Length->getSourceRange());
  3548. Length = Res.get();
  3549. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3550. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3551. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3552. << 1 << Length->getSourceRange();
  3553. }
  3554. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3555. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3556. // type. Note that functions are not objects, and that (in C99 parlance)
  3557. // incomplete types are not object types.
  3558. if (ResultTy->isFunctionType()) {
  3559. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3560. << ResultTy << Base->getSourceRange();
  3561. return ExprError();
  3562. }
  3563. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3564. diag::err_omp_section_incomplete_type, Base))
  3565. return ExprError();
  3566. if (LowerBound) {
  3567. llvm::APSInt LowerBoundValue;
  3568. if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
  3569. // OpenMP 4.0, [2.4 Array Sections]
  3570. // The lower-bound and length must evaluate to non-negative integers.
  3571. if (LowerBoundValue.isNegative()) {
  3572. Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
  3573. << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
  3574. << LowerBound->getSourceRange();
  3575. return ExprError();
  3576. }
  3577. }
  3578. }
  3579. if (Length) {
  3580. llvm::APSInt LengthValue;
  3581. if (Length->EvaluateAsInt(LengthValue, Context)) {
  3582. // OpenMP 4.0, [2.4 Array Sections]
  3583. // The lower-bound and length must evaluate to non-negative integers.
  3584. if (LengthValue.isNegative()) {
  3585. Diag(Length->getExprLoc(), diag::err_omp_section_negative)
  3586. << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3587. << Length->getSourceRange();
  3588. return ExprError();
  3589. }
  3590. }
  3591. } else if (ColonLoc.isValid() &&
  3592. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  3593. !OriginalTy->isVariableArrayType()))) {
  3594. // OpenMP 4.0, [2.4 Array Sections]
  3595. // When the size of the array dimension is not known, the length must be
  3596. // specified explicitly.
  3597. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  3598. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  3599. return ExprError();
  3600. }
  3601. return new (Context)
  3602. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  3603. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3604. }
  3605. ExprResult
  3606. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3607. Expr *Idx, SourceLocation RLoc) {
  3608. Expr *LHSExp = Base;
  3609. Expr *RHSExp = Idx;
  3610. // Perform default conversions.
  3611. if (!LHSExp->getType()->getAs<VectorType>()) {
  3612. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3613. if (Result.isInvalid())
  3614. return ExprError();
  3615. LHSExp = Result.get();
  3616. }
  3617. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3618. if (Result.isInvalid())
  3619. return ExprError();
  3620. RHSExp = Result.get();
  3621. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3622. ExprValueKind VK = VK_LValue;
  3623. ExprObjectKind OK = OK_Ordinary;
  3624. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3625. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3626. // in the subscript position. As a result, we need to derive the array base
  3627. // and index from the expression types.
  3628. Expr *BaseExpr, *IndexExpr;
  3629. QualType ResultType;
  3630. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3631. BaseExpr = LHSExp;
  3632. IndexExpr = RHSExp;
  3633. ResultType = Context.DependentTy;
  3634. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3635. BaseExpr = LHSExp;
  3636. IndexExpr = RHSExp;
  3637. ResultType = PTy->getPointeeType();
  3638. } else if (const ObjCObjectPointerType *PTy =
  3639. LHSTy->getAs<ObjCObjectPointerType>()) {
  3640. BaseExpr = LHSExp;
  3641. IndexExpr = RHSExp;
  3642. // Use custom logic if this should be the pseudo-object subscript
  3643. // expression.
  3644. if (!LangOpts.isSubscriptPointerArithmetic())
  3645. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3646. nullptr);
  3647. ResultType = PTy->getPointeeType();
  3648. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3649. // Handle the uncommon case of "123[Ptr]".
  3650. BaseExpr = RHSExp;
  3651. IndexExpr = LHSExp;
  3652. ResultType = PTy->getPointeeType();
  3653. } else if (const ObjCObjectPointerType *PTy =
  3654. RHSTy->getAs<ObjCObjectPointerType>()) {
  3655. // Handle the uncommon case of "123[Ptr]".
  3656. BaseExpr = RHSExp;
  3657. IndexExpr = LHSExp;
  3658. ResultType = PTy->getPointeeType();
  3659. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3660. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3661. << ResultType << BaseExpr->getSourceRange();
  3662. return ExprError();
  3663. }
  3664. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3665. BaseExpr = LHSExp; // vectors: V[123]
  3666. IndexExpr = RHSExp;
  3667. VK = LHSExp->getValueKind();
  3668. if (VK != VK_RValue)
  3669. OK = OK_VectorComponent;
  3670. // FIXME: need to deal with const...
  3671. ResultType = VTy->getElementType();
  3672. } else if (LHSTy->isArrayType()) {
  3673. // If we see an array that wasn't promoted by
  3674. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3675. // wasn't promoted because of the C90 rule that doesn't
  3676. // allow promoting non-lvalue arrays. Warn, then
  3677. // force the promotion here.
  3678. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3679. LHSExp->getSourceRange();
  3680. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3681. CK_ArrayToPointerDecay).get();
  3682. LHSTy = LHSExp->getType();
  3683. BaseExpr = LHSExp;
  3684. IndexExpr = RHSExp;
  3685. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3686. } else if (RHSTy->isArrayType()) {
  3687. // Same as previous, except for 123[f().a] case
  3688. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3689. RHSExp->getSourceRange();
  3690. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3691. CK_ArrayToPointerDecay).get();
  3692. RHSTy = RHSExp->getType();
  3693. BaseExpr = RHSExp;
  3694. IndexExpr = LHSExp;
  3695. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3696. } else {
  3697. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  3698. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3699. }
  3700. // C99 6.5.2.1p1
  3701. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3702. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3703. << IndexExpr->getSourceRange());
  3704. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3705. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3706. && !IndexExpr->isTypeDependent())
  3707. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3708. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3709. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3710. // type. Note that Functions are not objects, and that (in C99 parlance)
  3711. // incomplete types are not object types.
  3712. if (ResultType->isFunctionType()) {
  3713. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3714. << ResultType << BaseExpr->getSourceRange();
  3715. return ExprError();
  3716. }
  3717. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3718. // GNU extension: subscripting on pointer to void
  3719. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3720. << BaseExpr->getSourceRange();
  3721. // C forbids expressions of unqualified void type from being l-values.
  3722. // See IsCForbiddenLValueType.
  3723. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3724. } else if (!ResultType->isDependentType() &&
  3725. RequireCompleteType(LLoc, ResultType,
  3726. diag::err_subscript_incomplete_type, BaseExpr))
  3727. return ExprError();
  3728. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3729. !ResultType.isCForbiddenLValueType());
  3730. return new (Context)
  3731. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3732. }
  3733. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3734. FunctionDecl *FD,
  3735. ParmVarDecl *Param) {
  3736. if (Param->hasUnparsedDefaultArg()) {
  3737. Diag(CallLoc,
  3738. diag::err_use_of_default_argument_to_function_declared_later) <<
  3739. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3740. Diag(UnparsedDefaultArgLocs[Param],
  3741. diag::note_default_argument_declared_here);
  3742. return ExprError();
  3743. }
  3744. if (Param->hasUninstantiatedDefaultArg()) {
  3745. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3746. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3747. Param);
  3748. // Instantiate the expression.
  3749. MultiLevelTemplateArgumentList MutiLevelArgList
  3750. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3751. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3752. MutiLevelArgList.getInnermost());
  3753. if (Inst.isInvalid())
  3754. return ExprError();
  3755. ExprResult Result;
  3756. {
  3757. // C++ [dcl.fct.default]p5:
  3758. // The names in the [default argument] expression are bound, and
  3759. // the semantic constraints are checked, at the point where the
  3760. // default argument expression appears.
  3761. ContextRAII SavedContext(*this, FD);
  3762. LocalInstantiationScope Local(*this);
  3763. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3764. }
  3765. if (Result.isInvalid())
  3766. return ExprError();
  3767. // Check the expression as an initializer for the parameter.
  3768. InitializedEntity Entity
  3769. = InitializedEntity::InitializeParameter(Context, Param);
  3770. InitializationKind Kind
  3771. = InitializationKind::CreateCopy(Param->getLocation(),
  3772. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3773. Expr *ResultE = Result.getAs<Expr>();
  3774. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3775. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3776. if (Result.isInvalid())
  3777. return ExprError();
  3778. Expr *Arg = Result.getAs<Expr>();
  3779. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3780. // Build the default argument expression.
  3781. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3782. }
  3783. // If the default expression creates temporaries, we need to
  3784. // push them to the current stack of expression temporaries so they'll
  3785. // be properly destroyed.
  3786. // FIXME: We should really be rebuilding the default argument with new
  3787. // bound temporaries; see the comment in PR5810.
  3788. // We don't need to do that with block decls, though, because
  3789. // blocks in default argument expression can never capture anything.
  3790. if (isa<ExprWithCleanups>(Param->getInit())) {
  3791. // Set the "needs cleanups" bit regardless of whether there are
  3792. // any explicit objects.
  3793. ExprNeedsCleanups = true;
  3794. // Append all the objects to the cleanup list. Right now, this
  3795. // should always be a no-op, because blocks in default argument
  3796. // expressions should never be able to capture anything.
  3797. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3798. "default argument expression has capturing blocks?");
  3799. }
  3800. // We already type-checked the argument, so we know it works.
  3801. // Just mark all of the declarations in this potentially-evaluated expression
  3802. // as being "referenced".
  3803. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3804. /*SkipLocalVariables=*/true);
  3805. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3806. }
  3807. Sema::VariadicCallType
  3808. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3809. Expr *Fn) {
  3810. if (Proto && Proto->isVariadic()) {
  3811. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3812. return VariadicConstructor;
  3813. else if (Fn && Fn->getType()->isBlockPointerType())
  3814. return VariadicBlock;
  3815. else if (FDecl) {
  3816. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3817. if (Method->isInstance())
  3818. return VariadicMethod;
  3819. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3820. return VariadicMethod;
  3821. return VariadicFunction;
  3822. }
  3823. return VariadicDoesNotApply;
  3824. }
  3825. namespace {
  3826. class FunctionCallCCC : public FunctionCallFilterCCC {
  3827. public:
  3828. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3829. unsigned NumArgs, MemberExpr *ME)
  3830. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3831. FunctionName(FuncName) {}
  3832. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3833. if (!candidate.getCorrectionSpecifier() ||
  3834. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3835. return false;
  3836. }
  3837. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3838. }
  3839. private:
  3840. const IdentifierInfo *const FunctionName;
  3841. };
  3842. }
  3843. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3844. FunctionDecl *FDecl,
  3845. ArrayRef<Expr *> Args) {
  3846. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3847. DeclarationName FuncName = FDecl->getDeclName();
  3848. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3849. if (TypoCorrection Corrected = S.CorrectTypo(
  3850. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3851. S.getScopeForContext(S.CurContext), nullptr,
  3852. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3853. Args.size(), ME),
  3854. Sema::CTK_ErrorRecovery)) {
  3855. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3856. if (Corrected.isOverloaded()) {
  3857. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3858. OverloadCandidateSet::iterator Best;
  3859. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3860. CDEnd = Corrected.end();
  3861. CD != CDEnd; ++CD) {
  3862. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3863. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3864. OCS);
  3865. }
  3866. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3867. case OR_Success:
  3868. ND = Best->Function;
  3869. Corrected.setCorrectionDecl(ND);
  3870. break;
  3871. default:
  3872. break;
  3873. }
  3874. }
  3875. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3876. return Corrected;
  3877. }
  3878. }
  3879. }
  3880. return TypoCorrection();
  3881. }
  3882. /// ConvertArgumentsForCall - Converts the arguments specified in
  3883. /// Args/NumArgs to the parameter types of the function FDecl with
  3884. /// function prototype Proto. Call is the call expression itself, and
  3885. /// Fn is the function expression. For a C++ member function, this
  3886. /// routine does not attempt to convert the object argument. Returns
  3887. /// true if the call is ill-formed.
  3888. bool
  3889. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3890. FunctionDecl *FDecl,
  3891. const FunctionProtoType *Proto,
  3892. ArrayRef<Expr *> Args,
  3893. SourceLocation RParenLoc,
  3894. bool IsExecConfig) {
  3895. // Bail out early if calling a builtin with custom typechecking.
  3896. if (FDecl)
  3897. if (unsigned ID = FDecl->getBuiltinID())
  3898. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3899. return false;
  3900. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3901. // assignment, to the types of the corresponding parameter, ...
  3902. unsigned NumParams = Proto->getNumParams();
  3903. bool Invalid = false;
  3904. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3905. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3906. ? 1 /* block */
  3907. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3908. : 0 /* function */);
  3909. // If too few arguments are available (and we don't have default
  3910. // arguments for the remaining parameters), don't make the call.
  3911. if (Args.size() < NumParams) {
  3912. if (Args.size() < MinArgs) {
  3913. TypoCorrection TC;
  3914. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3915. unsigned diag_id =
  3916. MinArgs == NumParams && !Proto->isVariadic()
  3917. ? diag::err_typecheck_call_too_few_args_suggest
  3918. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3919. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3920. << static_cast<unsigned>(Args.size())
  3921. << TC.getCorrectionRange());
  3922. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3923. Diag(RParenLoc,
  3924. MinArgs == NumParams && !Proto->isVariadic()
  3925. ? diag::err_typecheck_call_too_few_args_one
  3926. : diag::err_typecheck_call_too_few_args_at_least_one)
  3927. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3928. else
  3929. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3930. ? diag::err_typecheck_call_too_few_args
  3931. : diag::err_typecheck_call_too_few_args_at_least)
  3932. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3933. << Fn->getSourceRange();
  3934. // Emit the location of the prototype.
  3935. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3936. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3937. << FDecl;
  3938. return true;
  3939. }
  3940. Call->setNumArgs(Context, NumParams);
  3941. }
  3942. // If too many are passed and not variadic, error on the extras and drop
  3943. // them.
  3944. if (Args.size() > NumParams) {
  3945. if (!Proto->isVariadic()) {
  3946. TypoCorrection TC;
  3947. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3948. unsigned diag_id =
  3949. MinArgs == NumParams && !Proto->isVariadic()
  3950. ? diag::err_typecheck_call_too_many_args_suggest
  3951. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  3952. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  3953. << static_cast<unsigned>(Args.size())
  3954. << TC.getCorrectionRange());
  3955. } else if (NumParams == 1 && FDecl &&
  3956. FDecl->getParamDecl(0)->getDeclName())
  3957. Diag(Args[NumParams]->getLocStart(),
  3958. MinArgs == NumParams
  3959. ? diag::err_typecheck_call_too_many_args_one
  3960. : diag::err_typecheck_call_too_many_args_at_most_one)
  3961. << FnKind << FDecl->getParamDecl(0)
  3962. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  3963. << SourceRange(Args[NumParams]->getLocStart(),
  3964. Args.back()->getLocEnd());
  3965. else
  3966. Diag(Args[NumParams]->getLocStart(),
  3967. MinArgs == NumParams
  3968. ? diag::err_typecheck_call_too_many_args
  3969. : diag::err_typecheck_call_too_many_args_at_most)
  3970. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  3971. << Fn->getSourceRange()
  3972. << SourceRange(Args[NumParams]->getLocStart(),
  3973. Args.back()->getLocEnd());
  3974. // Emit the location of the prototype.
  3975. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3976. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3977. << FDecl;
  3978. // This deletes the extra arguments.
  3979. Call->setNumArgs(Context, NumParams);
  3980. return true;
  3981. }
  3982. }
  3983. SmallVector<Expr *, 8> AllArgs;
  3984. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  3985. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  3986. Proto, 0, Args, AllArgs, CallType);
  3987. if (Invalid)
  3988. return true;
  3989. unsigned TotalNumArgs = AllArgs.size();
  3990. for (unsigned i = 0; i < TotalNumArgs; ++i)
  3991. Call->setArg(i, AllArgs[i]);
  3992. return false;
  3993. }
  3994. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  3995. const FunctionProtoType *Proto,
  3996. unsigned FirstParam, ArrayRef<Expr *> Args,
  3997. SmallVectorImpl<Expr *> &AllArgs,
  3998. VariadicCallType CallType, bool AllowExplicit,
  3999. bool IsListInitialization) {
  4000. unsigned NumParams = Proto->getNumParams();
  4001. bool Invalid = false;
  4002. unsigned ArgIx = 0;
  4003. // Continue to check argument types (even if we have too few/many args).
  4004. for (unsigned i = FirstParam; i < NumParams; i++) {
  4005. QualType ProtoArgType = Proto->getParamType(i);
  4006. Expr *Arg;
  4007. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4008. if (ArgIx < Args.size()) {
  4009. Arg = Args[ArgIx++];
  4010. if (RequireCompleteType(Arg->getLocStart(),
  4011. ProtoArgType,
  4012. diag::err_call_incomplete_argument, Arg))
  4013. return true;
  4014. // Strip the unbridged-cast placeholder expression off, if applicable.
  4015. bool CFAudited = false;
  4016. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4017. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4018. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4019. Arg = stripARCUnbridgedCast(Arg);
  4020. else if (getLangOpts().ObjCAutoRefCount &&
  4021. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4022. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4023. CFAudited = true;
  4024. InitializedEntity Entity =
  4025. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4026. ProtoArgType)
  4027. : InitializedEntity::InitializeParameter(
  4028. Context, ProtoArgType, Proto->isParamConsumed(i));
  4029. // Remember that parameter belongs to a CF audited API.
  4030. if (CFAudited)
  4031. Entity.setParameterCFAudited();
  4032. ExprResult ArgE = PerformCopyInitialization(
  4033. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4034. if (ArgE.isInvalid())
  4035. return true;
  4036. Arg = ArgE.getAs<Expr>();
  4037. } else {
  4038. assert(Param && "can't use default arguments without a known callee");
  4039. ExprResult ArgExpr =
  4040. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4041. if (ArgExpr.isInvalid())
  4042. return true;
  4043. Arg = ArgExpr.getAs<Expr>();
  4044. }
  4045. // Check for array bounds violations for each argument to the call. This
  4046. // check only triggers warnings when the argument isn't a more complex Expr
  4047. // with its own checking, such as a BinaryOperator.
  4048. CheckArrayAccess(Arg);
  4049. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4050. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4051. AllArgs.push_back(Arg);
  4052. }
  4053. // If this is a variadic call, handle args passed through "...".
  4054. if (CallType != VariadicDoesNotApply) {
  4055. // Assume that extern "C" functions with variadic arguments that
  4056. // return __unknown_anytype aren't *really* variadic.
  4057. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4058. FDecl->isExternC()) {
  4059. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4060. QualType paramType; // ignored
  4061. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  4062. Invalid |= arg.isInvalid();
  4063. AllArgs.push_back(arg.get());
  4064. }
  4065. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4066. } else {
  4067. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4068. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  4069. FDecl);
  4070. Invalid |= Arg.isInvalid();
  4071. AllArgs.push_back(Arg.get());
  4072. }
  4073. }
  4074. // Check for array bounds violations.
  4075. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  4076. CheckArrayAccess(Args[i]);
  4077. }
  4078. return Invalid;
  4079. }
  4080. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4081. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4082. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4083. TL = DTL.getOriginalLoc();
  4084. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4085. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4086. << ATL.getLocalSourceRange();
  4087. }
  4088. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4089. /// array parameter, check that it is non-null, and that if it is formed by
  4090. /// array-to-pointer decay, the underlying array is sufficiently large.
  4091. ///
  4092. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4093. /// array type derivation, then for each call to the function, the value of the
  4094. /// corresponding actual argument shall provide access to the first element of
  4095. /// an array with at least as many elements as specified by the size expression.
  4096. void
  4097. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4098. ParmVarDecl *Param,
  4099. const Expr *ArgExpr) {
  4100. // Static array parameters are not supported in C++.
  4101. if (!Param || getLangOpts().CPlusPlus)
  4102. return;
  4103. QualType OrigTy = Param->getOriginalType();
  4104. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4105. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4106. return;
  4107. if (ArgExpr->isNullPointerConstant(Context,
  4108. Expr::NPC_NeverValueDependent)) {
  4109. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4110. DiagnoseCalleeStaticArrayParam(*this, Param);
  4111. return;
  4112. }
  4113. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4114. if (!CAT)
  4115. return;
  4116. const ConstantArrayType *ArgCAT =
  4117. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4118. if (!ArgCAT)
  4119. return;
  4120. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4121. Diag(CallLoc, diag::warn_static_array_too_small)
  4122. << ArgExpr->getSourceRange()
  4123. << (unsigned) ArgCAT->getSize().getZExtValue()
  4124. << (unsigned) CAT->getSize().getZExtValue();
  4125. DiagnoseCalleeStaticArrayParam(*this, Param);
  4126. }
  4127. }
  4128. /// Given a function expression of unknown-any type, try to rebuild it
  4129. /// to have a function type.
  4130. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4131. /// Is the given type a placeholder that we need to lower out
  4132. /// immediately during argument processing?
  4133. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4134. // Placeholders are never sugared.
  4135. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4136. if (!placeholder) return false;
  4137. switch (placeholder->getKind()) {
  4138. // Ignore all the non-placeholder types.
  4139. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4140. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4141. #include "clang/AST/BuiltinTypes.def"
  4142. return false;
  4143. // We cannot lower out overload sets; they might validly be resolved
  4144. // by the call machinery.
  4145. case BuiltinType::Overload:
  4146. return false;
  4147. // Unbridged casts in ARC can be handled in some call positions and
  4148. // should be left in place.
  4149. case BuiltinType::ARCUnbridgedCast:
  4150. return false;
  4151. // Pseudo-objects should be converted as soon as possible.
  4152. case BuiltinType::PseudoObject:
  4153. return true;
  4154. // The debugger mode could theoretically but currently does not try
  4155. // to resolve unknown-typed arguments based on known parameter types.
  4156. case BuiltinType::UnknownAny:
  4157. return true;
  4158. // These are always invalid as call arguments and should be reported.
  4159. case BuiltinType::BoundMember:
  4160. case BuiltinType::BuiltinFn:
  4161. case BuiltinType::OMPArraySection:
  4162. return true;
  4163. }
  4164. llvm_unreachable("bad builtin type kind");
  4165. }
  4166. /// Check an argument list for placeholders that we won't try to
  4167. /// handle later.
  4168. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4169. // Apply this processing to all the arguments at once instead of
  4170. // dying at the first failure.
  4171. bool hasInvalid = false;
  4172. for (size_t i = 0, e = args.size(); i != e; i++) {
  4173. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4174. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4175. if (result.isInvalid()) hasInvalid = true;
  4176. else args[i] = result.get();
  4177. } else if (hasInvalid) {
  4178. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4179. }
  4180. }
  4181. return hasInvalid;
  4182. }
  4183. /// If a builtin function has a pointer argument with no explicit address
  4184. /// space, than it should be able to accept a pointer to any address
  4185. /// space as input. In order to do this, we need to replace the
  4186. /// standard builtin declaration with one that uses the same address space
  4187. /// as the call.
  4188. ///
  4189. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4190. /// it does not contain any pointer arguments without
  4191. /// an address space qualifer. Otherwise the rewritten
  4192. /// FunctionDecl is returned.
  4193. /// TODO: Handle pointer return types.
  4194. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4195. const FunctionDecl *FDecl,
  4196. MultiExprArg ArgExprs) {
  4197. QualType DeclType = FDecl->getType();
  4198. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4199. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4200. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4201. return nullptr;
  4202. bool NeedsNewDecl = false;
  4203. unsigned i = 0;
  4204. SmallVector<QualType, 8> OverloadParams;
  4205. for (QualType ParamType : FT->param_types()) {
  4206. // Convert array arguments to pointer to simplify type lookup.
  4207. Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
  4208. QualType ArgType = Arg->getType();
  4209. if (!ParamType->isPointerType() ||
  4210. ParamType.getQualifiers().hasAddressSpace() ||
  4211. !ArgType->isPointerType() ||
  4212. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4213. OverloadParams.push_back(ParamType);
  4214. continue;
  4215. }
  4216. NeedsNewDecl = true;
  4217. unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
  4218. QualType PointeeType = ParamType->getPointeeType();
  4219. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4220. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4221. }
  4222. if (!NeedsNewDecl)
  4223. return nullptr;
  4224. FunctionProtoType::ExtProtoInfo EPI;
  4225. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4226. OverloadParams, EPI);
  4227. DeclContext *Parent = Context.getTranslationUnitDecl();
  4228. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4229. FDecl->getLocation(),
  4230. FDecl->getLocation(),
  4231. FDecl->getIdentifier(),
  4232. OverloadTy,
  4233. /*TInfo=*/nullptr,
  4234. SC_Extern, false,
  4235. /*hasPrototype=*/true);
  4236. SmallVector<ParmVarDecl*, 16> Params;
  4237. FT = cast<FunctionProtoType>(OverloadTy);
  4238. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4239. QualType ParamType = FT->getParamType(i);
  4240. ParmVarDecl *Parm =
  4241. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4242. SourceLocation(), nullptr, ParamType,
  4243. /*TInfo=*/nullptr, SC_None, nullptr);
  4244. Parm->setScopeInfo(0, i);
  4245. Params.push_back(Parm);
  4246. }
  4247. OverloadDecl->setParams(Params);
  4248. return OverloadDecl;
  4249. }
  4250. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4251. /// This provides the location of the left/right parens and a list of comma
  4252. /// locations.
  4253. ExprResult
  4254. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  4255. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4256. Expr *ExecConfig, bool IsExecConfig) {
  4257. // Since this might be a postfix expression, get rid of ParenListExprs.
  4258. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  4259. if (Result.isInvalid()) return ExprError();
  4260. Fn = Result.get();
  4261. if (checkArgsForPlaceholders(*this, ArgExprs))
  4262. return ExprError();
  4263. if (getLangOpts().CPlusPlus) {
  4264. // If this is a pseudo-destructor expression, build the call immediately.
  4265. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4266. if (!ArgExprs.empty()) {
  4267. // Pseudo-destructor calls should not have any arguments.
  4268. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4269. << FixItHint::CreateRemoval(
  4270. SourceRange(ArgExprs.front()->getLocStart(),
  4271. ArgExprs.back()->getLocEnd()));
  4272. }
  4273. return new (Context)
  4274. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4275. }
  4276. if (Fn->getType() == Context.PseudoObjectTy) {
  4277. ExprResult result = CheckPlaceholderExpr(Fn);
  4278. if (result.isInvalid()) return ExprError();
  4279. Fn = result.get();
  4280. }
  4281. // Determine whether this is a dependent call inside a C++ template,
  4282. // in which case we won't do any semantic analysis now.
  4283. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4284. // Fn.
  4285. bool Dependent = false;
  4286. if (Fn->isTypeDependent())
  4287. Dependent = true;
  4288. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4289. Dependent = true;
  4290. if (Dependent) {
  4291. if (ExecConfig) {
  4292. return new (Context) CUDAKernelCallExpr(
  4293. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4294. Context.DependentTy, VK_RValue, RParenLoc);
  4295. } else {
  4296. return new (Context) CallExpr(
  4297. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4298. }
  4299. }
  4300. // Determine whether this is a call to an object (C++ [over.call.object]).
  4301. if (Fn->getType()->isRecordType())
  4302. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4303. RParenLoc);
  4304. if (Fn->getType() == Context.UnknownAnyTy) {
  4305. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4306. if (result.isInvalid()) return ExprError();
  4307. Fn = result.get();
  4308. }
  4309. if (Fn->getType() == Context.BoundMemberTy) {
  4310. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4311. }
  4312. }
  4313. // Check for overloaded calls. This can happen even in C due to extensions.
  4314. if (Fn->getType() == Context.OverloadTy) {
  4315. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4316. // We aren't supposed to apply this logic for if there's an '&' involved.
  4317. if (!find.HasFormOfMemberPointer) {
  4318. OverloadExpr *ovl = find.Expression;
  4319. if (isa<UnresolvedLookupExpr>(ovl)) {
  4320. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4321. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4322. RParenLoc, ExecConfig);
  4323. } else {
  4324. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4325. RParenLoc);
  4326. }
  4327. }
  4328. }
  4329. // If we're directly calling a function, get the appropriate declaration.
  4330. if (Fn->getType() == Context.UnknownAnyTy) {
  4331. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4332. if (result.isInvalid()) return ExprError();
  4333. Fn = result.get();
  4334. }
  4335. Expr *NakedFn = Fn->IgnoreParens();
  4336. NamedDecl *NDecl = nullptr;
  4337. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4338. if (UnOp->getOpcode() == UO_AddrOf)
  4339. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4340. if (isa<DeclRefExpr>(NakedFn)) {
  4341. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4342. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4343. if (FDecl && FDecl->getBuiltinID()) {
  4344. // Rewrite the function decl for this builtin by replacing paramaters
  4345. // with no explicit address space with the address space of the arguments
  4346. // in ArgExprs.
  4347. if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4348. NDecl = FDecl;
  4349. Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
  4350. SourceLocation(), FDecl, false,
  4351. SourceLocation(), FDecl->getType(),
  4352. Fn->getValueKind(), FDecl);
  4353. }
  4354. }
  4355. } else if (isa<MemberExpr>(NakedFn))
  4356. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4357. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4358. if (FD->hasAttr<EnableIfAttr>()) {
  4359. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4360. Diag(Fn->getLocStart(),
  4361. isa<CXXMethodDecl>(FD) ?
  4362. diag::err_ovl_no_viable_member_function_in_call :
  4363. diag::err_ovl_no_viable_function_in_call)
  4364. << FD << FD->getSourceRange();
  4365. Diag(FD->getLocation(),
  4366. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4367. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4368. }
  4369. }
  4370. }
  4371. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4372. ExecConfig, IsExecConfig);
  4373. }
  4374. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4375. ///
  4376. /// __builtin_astype( value, dst type )
  4377. ///
  4378. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4379. SourceLocation BuiltinLoc,
  4380. SourceLocation RParenLoc) {
  4381. ExprValueKind VK = VK_RValue;
  4382. ExprObjectKind OK = OK_Ordinary;
  4383. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4384. QualType SrcTy = E->getType();
  4385. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4386. return ExprError(Diag(BuiltinLoc,
  4387. diag::err_invalid_astype_of_different_size)
  4388. << DstTy
  4389. << SrcTy
  4390. << E->getSourceRange());
  4391. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4392. }
  4393. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4394. /// provided arguments.
  4395. ///
  4396. /// __builtin_convertvector( value, dst type )
  4397. ///
  4398. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4399. SourceLocation BuiltinLoc,
  4400. SourceLocation RParenLoc) {
  4401. TypeSourceInfo *TInfo;
  4402. GetTypeFromParser(ParsedDestTy, &TInfo);
  4403. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4404. }
  4405. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4406. /// i.e. an expression not of \p OverloadTy. The expression should
  4407. /// unary-convert to an expression of function-pointer or
  4408. /// block-pointer type.
  4409. ///
  4410. /// \param NDecl the declaration being called, if available
  4411. ExprResult
  4412. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4413. SourceLocation LParenLoc,
  4414. ArrayRef<Expr *> Args,
  4415. SourceLocation RParenLoc,
  4416. Expr *Config, bool IsExecConfig) {
  4417. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4418. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4419. // Promote the function operand.
  4420. // We special-case function promotion here because we only allow promoting
  4421. // builtin functions to function pointers in the callee of a call.
  4422. ExprResult Result;
  4423. if (BuiltinID &&
  4424. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4425. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4426. CK_BuiltinFnToFnPtr).get();
  4427. } else {
  4428. Result = CallExprUnaryConversions(Fn);
  4429. }
  4430. if (Result.isInvalid())
  4431. return ExprError();
  4432. Fn = Result.get();
  4433. // Make the call expr early, before semantic checks. This guarantees cleanup
  4434. // of arguments and function on error.
  4435. CallExpr *TheCall;
  4436. if (Config)
  4437. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4438. cast<CallExpr>(Config), Args,
  4439. Context.BoolTy, VK_RValue,
  4440. RParenLoc);
  4441. else
  4442. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4443. VK_RValue, RParenLoc);
  4444. if (!getLangOpts().CPlusPlus) {
  4445. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4446. // function calls as their argument checking don't necessarily handle
  4447. // dependent types properly, so make sure any TypoExprs have been
  4448. // dealt with.
  4449. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4450. if (!Result.isUsable()) return ExprError();
  4451. TheCall = dyn_cast<CallExpr>(Result.get());
  4452. if (!TheCall) return Result;
  4453. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  4454. }
  4455. // Bail out early if calling a builtin with custom typechecking.
  4456. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4457. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4458. retry:
  4459. const FunctionType *FuncT;
  4460. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4461. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4462. // have type pointer to function".
  4463. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4464. if (!FuncT)
  4465. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4466. << Fn->getType() << Fn->getSourceRange());
  4467. } else if (const BlockPointerType *BPT =
  4468. Fn->getType()->getAs<BlockPointerType>()) {
  4469. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4470. } else {
  4471. // Handle calls to expressions of unknown-any type.
  4472. if (Fn->getType() == Context.UnknownAnyTy) {
  4473. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4474. if (rewrite.isInvalid()) return ExprError();
  4475. Fn = rewrite.get();
  4476. TheCall->setCallee(Fn);
  4477. goto retry;
  4478. }
  4479. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4480. << Fn->getType() << Fn->getSourceRange());
  4481. }
  4482. if (getLangOpts().CUDA) {
  4483. if (Config) {
  4484. // CUDA: Kernel calls must be to global functions
  4485. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4486. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4487. << FDecl->getName() << Fn->getSourceRange());
  4488. // CUDA: Kernel function must have 'void' return type
  4489. if (!FuncT->getReturnType()->isVoidType())
  4490. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4491. << Fn->getType() << Fn->getSourceRange());
  4492. } else {
  4493. // CUDA: Calls to global functions must be configured
  4494. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4495. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4496. << FDecl->getName() << Fn->getSourceRange());
  4497. }
  4498. }
  4499. // Check for a valid return type
  4500. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4501. FDecl))
  4502. return ExprError();
  4503. // We know the result type of the call, set it.
  4504. TheCall->setType(FuncT->getCallResultType(Context));
  4505. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4506. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4507. if (Proto) {
  4508. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4509. IsExecConfig))
  4510. return ExprError();
  4511. } else {
  4512. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4513. if (FDecl) {
  4514. // Check if we have too few/too many template arguments, based
  4515. // on our knowledge of the function definition.
  4516. const FunctionDecl *Def = nullptr;
  4517. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4518. Proto = Def->getType()->getAs<FunctionProtoType>();
  4519. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4520. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4521. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4522. }
  4523. // If the function we're calling isn't a function prototype, but we have
  4524. // a function prototype from a prior declaratiom, use that prototype.
  4525. if (!FDecl->hasPrototype())
  4526. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4527. }
  4528. // Promote the arguments (C99 6.5.2.2p6).
  4529. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4530. Expr *Arg = Args[i];
  4531. if (Proto && i < Proto->getNumParams()) {
  4532. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4533. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4534. ExprResult ArgE =
  4535. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4536. if (ArgE.isInvalid())
  4537. return true;
  4538. Arg = ArgE.getAs<Expr>();
  4539. } else {
  4540. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4541. if (ArgE.isInvalid())
  4542. return true;
  4543. Arg = ArgE.getAs<Expr>();
  4544. }
  4545. if (RequireCompleteType(Arg->getLocStart(),
  4546. Arg->getType(),
  4547. diag::err_call_incomplete_argument, Arg))
  4548. return ExprError();
  4549. TheCall->setArg(i, Arg);
  4550. }
  4551. }
  4552. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4553. if (!Method->isStatic())
  4554. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4555. << Fn->getSourceRange());
  4556. // Check for sentinels
  4557. if (NDecl)
  4558. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4559. // Do special checking on direct calls to functions.
  4560. if (FDecl) {
  4561. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4562. return ExprError();
  4563. if (BuiltinID)
  4564. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4565. } else if (NDecl) {
  4566. if (CheckPointerCall(NDecl, TheCall, Proto))
  4567. return ExprError();
  4568. } else {
  4569. if (CheckOtherCall(TheCall, Proto))
  4570. return ExprError();
  4571. }
  4572. return MaybeBindToTemporary(TheCall);
  4573. }
  4574. ExprResult
  4575. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4576. SourceLocation RParenLoc, Expr *InitExpr) {
  4577. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4578. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  4579. TypeSourceInfo *TInfo;
  4580. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4581. if (!TInfo)
  4582. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4583. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4584. }
  4585. ExprResult
  4586. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4587. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4588. QualType literalType = TInfo->getType();
  4589. if (literalType->isArrayType()) {
  4590. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4591. diag::err_illegal_decl_array_incomplete_type,
  4592. SourceRange(LParenLoc,
  4593. LiteralExpr->getSourceRange().getEnd())))
  4594. return ExprError();
  4595. if (literalType->isVariableArrayType())
  4596. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4597. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4598. } else if (!literalType->isDependentType() &&
  4599. RequireCompleteType(LParenLoc, literalType,
  4600. diag::err_typecheck_decl_incomplete_type,
  4601. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4602. return ExprError();
  4603. InitializedEntity Entity
  4604. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4605. InitializationKind Kind
  4606. = InitializationKind::CreateCStyleCast(LParenLoc,
  4607. SourceRange(LParenLoc, RParenLoc),
  4608. /*InitList=*/true);
  4609. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4610. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4611. &literalType);
  4612. if (Result.isInvalid())
  4613. return ExprError();
  4614. LiteralExpr = Result.get();
  4615. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4616. if (isFileScope &&
  4617. !LiteralExpr->isTypeDependent() &&
  4618. !LiteralExpr->isValueDependent() &&
  4619. !literalType->isDependentType()) { // 6.5.2.5p3
  4620. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4621. return ExprError();
  4622. }
  4623. // In C, compound literals are l-values for some reason.
  4624. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4625. return MaybeBindToTemporary(
  4626. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4627. VK, LiteralExpr, isFileScope));
  4628. }
  4629. ExprResult
  4630. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4631. SourceLocation RBraceLoc) {
  4632. // Immediately handle non-overload placeholders. Overloads can be
  4633. // resolved contextually, but everything else here can't.
  4634. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4635. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4636. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4637. // Ignore failures; dropping the entire initializer list because
  4638. // of one failure would be terrible for indexing/etc.
  4639. if (result.isInvalid()) continue;
  4640. InitArgList[I] = result.get();
  4641. }
  4642. }
  4643. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4644. // CheckInitializer() - it requires knowledge of the object being intialized.
  4645. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4646. RBraceLoc);
  4647. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4648. return E;
  4649. }
  4650. /// Do an explicit extend of the given block pointer if we're in ARC.
  4651. void Sema::maybeExtendBlockObject(ExprResult &E) {
  4652. assert(E.get()->getType()->isBlockPointerType());
  4653. assert(E.get()->isRValue());
  4654. // Only do this in an r-value context.
  4655. if (!getLangOpts().ObjCAutoRefCount) return;
  4656. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  4657. CK_ARCExtendBlockObject, E.get(),
  4658. /*base path*/ nullptr, VK_RValue);
  4659. ExprNeedsCleanups = true;
  4660. }
  4661. /// Prepare a conversion of the given expression to an ObjC object
  4662. /// pointer type.
  4663. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4664. QualType type = E.get()->getType();
  4665. if (type->isObjCObjectPointerType()) {
  4666. return CK_BitCast;
  4667. } else if (type->isBlockPointerType()) {
  4668. maybeExtendBlockObject(E);
  4669. return CK_BlockPointerToObjCPointerCast;
  4670. } else {
  4671. assert(type->isPointerType());
  4672. return CK_CPointerToObjCPointerCast;
  4673. }
  4674. }
  4675. /// Prepares for a scalar cast, performing all the necessary stages
  4676. /// except the final cast and returning the kind required.
  4677. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4678. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4679. // Also, callers should have filtered out the invalid cases with
  4680. // pointers. Everything else should be possible.
  4681. QualType SrcTy = Src.get()->getType();
  4682. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4683. return CK_NoOp;
  4684. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4685. case Type::STK_MemberPointer:
  4686. llvm_unreachable("member pointer type in C");
  4687. case Type::STK_CPointer:
  4688. case Type::STK_BlockPointer:
  4689. case Type::STK_ObjCObjectPointer:
  4690. switch (DestTy->getScalarTypeKind()) {
  4691. case Type::STK_CPointer: {
  4692. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4693. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4694. if (SrcAS != DestAS)
  4695. return CK_AddressSpaceConversion;
  4696. return CK_BitCast;
  4697. }
  4698. case Type::STK_BlockPointer:
  4699. return (SrcKind == Type::STK_BlockPointer
  4700. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4701. case Type::STK_ObjCObjectPointer:
  4702. if (SrcKind == Type::STK_ObjCObjectPointer)
  4703. return CK_BitCast;
  4704. if (SrcKind == Type::STK_CPointer)
  4705. return CK_CPointerToObjCPointerCast;
  4706. maybeExtendBlockObject(Src);
  4707. return CK_BlockPointerToObjCPointerCast;
  4708. case Type::STK_Bool:
  4709. return CK_PointerToBoolean;
  4710. case Type::STK_Integral:
  4711. return CK_PointerToIntegral;
  4712. case Type::STK_Floating:
  4713. case Type::STK_FloatingComplex:
  4714. case Type::STK_IntegralComplex:
  4715. case Type::STK_MemberPointer:
  4716. llvm_unreachable("illegal cast from pointer");
  4717. }
  4718. llvm_unreachable("Should have returned before this");
  4719. case Type::STK_Bool: // casting from bool is like casting from an integer
  4720. case Type::STK_Integral:
  4721. switch (DestTy->getScalarTypeKind()) {
  4722. case Type::STK_CPointer:
  4723. case Type::STK_ObjCObjectPointer:
  4724. case Type::STK_BlockPointer:
  4725. if (Src.get()->isNullPointerConstant(Context,
  4726. Expr::NPC_ValueDependentIsNull))
  4727. return CK_NullToPointer;
  4728. return CK_IntegralToPointer;
  4729. case Type::STK_Bool:
  4730. return CK_IntegralToBoolean;
  4731. case Type::STK_Integral:
  4732. return CK_IntegralCast;
  4733. case Type::STK_Floating:
  4734. return CK_IntegralToFloating;
  4735. case Type::STK_IntegralComplex:
  4736. Src = ImpCastExprToType(Src.get(),
  4737. DestTy->castAs<ComplexType>()->getElementType(),
  4738. CK_IntegralCast);
  4739. return CK_IntegralRealToComplex;
  4740. case Type::STK_FloatingComplex:
  4741. Src = ImpCastExprToType(Src.get(),
  4742. DestTy->castAs<ComplexType>()->getElementType(),
  4743. CK_IntegralToFloating);
  4744. return CK_FloatingRealToComplex;
  4745. case Type::STK_MemberPointer:
  4746. llvm_unreachable("member pointer type in C");
  4747. }
  4748. llvm_unreachable("Should have returned before this");
  4749. case Type::STK_Floating:
  4750. switch (DestTy->getScalarTypeKind()) {
  4751. case Type::STK_Floating:
  4752. return CK_FloatingCast;
  4753. case Type::STK_Bool:
  4754. return CK_FloatingToBoolean;
  4755. case Type::STK_Integral:
  4756. return CK_FloatingToIntegral;
  4757. case Type::STK_FloatingComplex:
  4758. Src = ImpCastExprToType(Src.get(),
  4759. DestTy->castAs<ComplexType>()->getElementType(),
  4760. CK_FloatingCast);
  4761. return CK_FloatingRealToComplex;
  4762. case Type::STK_IntegralComplex:
  4763. Src = ImpCastExprToType(Src.get(),
  4764. DestTy->castAs<ComplexType>()->getElementType(),
  4765. CK_FloatingToIntegral);
  4766. return CK_IntegralRealToComplex;
  4767. case Type::STK_CPointer:
  4768. case Type::STK_ObjCObjectPointer:
  4769. case Type::STK_BlockPointer:
  4770. llvm_unreachable("valid float->pointer cast?");
  4771. case Type::STK_MemberPointer:
  4772. llvm_unreachable("member pointer type in C");
  4773. }
  4774. llvm_unreachable("Should have returned before this");
  4775. case Type::STK_FloatingComplex:
  4776. switch (DestTy->getScalarTypeKind()) {
  4777. case Type::STK_FloatingComplex:
  4778. return CK_FloatingComplexCast;
  4779. case Type::STK_IntegralComplex:
  4780. return CK_FloatingComplexToIntegralComplex;
  4781. case Type::STK_Floating: {
  4782. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4783. if (Context.hasSameType(ET, DestTy))
  4784. return CK_FloatingComplexToReal;
  4785. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4786. return CK_FloatingCast;
  4787. }
  4788. case Type::STK_Bool:
  4789. return CK_FloatingComplexToBoolean;
  4790. case Type::STK_Integral:
  4791. Src = ImpCastExprToType(Src.get(),
  4792. SrcTy->castAs<ComplexType>()->getElementType(),
  4793. CK_FloatingComplexToReal);
  4794. return CK_FloatingToIntegral;
  4795. case Type::STK_CPointer:
  4796. case Type::STK_ObjCObjectPointer:
  4797. case Type::STK_BlockPointer:
  4798. llvm_unreachable("valid complex float->pointer cast?");
  4799. case Type::STK_MemberPointer:
  4800. llvm_unreachable("member pointer type in C");
  4801. }
  4802. llvm_unreachable("Should have returned before this");
  4803. case Type::STK_IntegralComplex:
  4804. switch (DestTy->getScalarTypeKind()) {
  4805. case Type::STK_FloatingComplex:
  4806. return CK_IntegralComplexToFloatingComplex;
  4807. case Type::STK_IntegralComplex:
  4808. return CK_IntegralComplexCast;
  4809. case Type::STK_Integral: {
  4810. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4811. if (Context.hasSameType(ET, DestTy))
  4812. return CK_IntegralComplexToReal;
  4813. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4814. return CK_IntegralCast;
  4815. }
  4816. case Type::STK_Bool:
  4817. return CK_IntegralComplexToBoolean;
  4818. case Type::STK_Floating:
  4819. Src = ImpCastExprToType(Src.get(),
  4820. SrcTy->castAs<ComplexType>()->getElementType(),
  4821. CK_IntegralComplexToReal);
  4822. return CK_IntegralToFloating;
  4823. case Type::STK_CPointer:
  4824. case Type::STK_ObjCObjectPointer:
  4825. case Type::STK_BlockPointer:
  4826. llvm_unreachable("valid complex int->pointer cast?");
  4827. case Type::STK_MemberPointer:
  4828. llvm_unreachable("member pointer type in C");
  4829. }
  4830. llvm_unreachable("Should have returned before this");
  4831. }
  4832. llvm_unreachable("Unhandled scalar cast");
  4833. }
  4834. static bool breakDownVectorType(QualType type, uint64_t &len,
  4835. QualType &eltType) {
  4836. // Vectors are simple.
  4837. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4838. len = vecType->getNumElements();
  4839. eltType = vecType->getElementType();
  4840. assert(eltType->isScalarType());
  4841. return true;
  4842. }
  4843. // We allow lax conversion to and from non-vector types, but only if
  4844. // they're real types (i.e. non-complex, non-pointer scalar types).
  4845. if (!type->isRealType()) return false;
  4846. len = 1;
  4847. eltType = type;
  4848. return true;
  4849. }
  4850. /// Are the two types lax-compatible vector types? That is, given
  4851. /// that one of them is a vector, do they have equal storage sizes,
  4852. /// where the storage size is the number of elements times the element
  4853. /// size?
  4854. ///
  4855. /// This will also return false if either of the types is neither a
  4856. /// vector nor a real type.
  4857. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  4858. assert(destTy->isVectorType() || srcTy->isVectorType());
  4859. // Disallow lax conversions between scalars and ExtVectors (these
  4860. // conversions are allowed for other vector types because common headers
  4861. // depend on them). Most scalar OP ExtVector cases are handled by the
  4862. // splat path anyway, which does what we want (convert, not bitcast).
  4863. // What this rules out for ExtVectors is crazy things like char4*float.
  4864. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  4865. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  4866. uint64_t srcLen, destLen;
  4867. QualType srcEltTy, destEltTy;
  4868. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  4869. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  4870. // ASTContext::getTypeSize will return the size rounded up to a
  4871. // power of 2, so instead of using that, we need to use the raw
  4872. // element size multiplied by the element count.
  4873. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  4874. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  4875. return (srcLen * srcEltSize == destLen * destEltSize);
  4876. }
  4877. /// Is this a legal conversion between two types, one of which is
  4878. /// known to be a vector type?
  4879. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4880. assert(destTy->isVectorType() || srcTy->isVectorType());
  4881. if (!Context.getLangOpts().LaxVectorConversions)
  4882. return false;
  4883. return areLaxCompatibleVectorTypes(srcTy, destTy);
  4884. }
  4885. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4886. CastKind &Kind) {
  4887. assert(VectorTy->isVectorType() && "Not a vector type!");
  4888. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  4889. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  4890. return Diag(R.getBegin(),
  4891. Ty->isVectorType() ?
  4892. diag::err_invalid_conversion_between_vectors :
  4893. diag::err_invalid_conversion_between_vector_and_integer)
  4894. << VectorTy << Ty << R;
  4895. } else
  4896. return Diag(R.getBegin(),
  4897. diag::err_invalid_conversion_between_vector_and_scalar)
  4898. << VectorTy << Ty << R;
  4899. Kind = CK_BitCast;
  4900. return false;
  4901. }
  4902. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4903. Expr *CastExpr, CastKind &Kind) {
  4904. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4905. QualType SrcTy = CastExpr->getType();
  4906. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4907. // an ExtVectorType.
  4908. // In OpenCL, casts between vectors of different types are not allowed.
  4909. // (See OpenCL 6.2).
  4910. if (SrcTy->isVectorType()) {
  4911. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
  4912. || (getLangOpts().OpenCL &&
  4913. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4914. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4915. << DestTy << SrcTy << R;
  4916. return ExprError();
  4917. }
  4918. Kind = CK_BitCast;
  4919. return CastExpr;
  4920. }
  4921. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4922. // conversion will take place first from scalar to elt type, and then
  4923. // splat from elt type to vector.
  4924. if (SrcTy->isPointerType())
  4925. return Diag(R.getBegin(),
  4926. diag::err_invalid_conversion_between_vector_and_scalar)
  4927. << DestTy << SrcTy << R;
  4928. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4929. ExprResult CastExprRes = CastExpr;
  4930. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4931. if (CastExprRes.isInvalid())
  4932. return ExprError();
  4933. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4934. Kind = CK_VectorSplat;
  4935. return CastExpr;
  4936. }
  4937. ExprResult
  4938. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4939. Declarator &D, ParsedType &Ty,
  4940. SourceLocation RParenLoc, Expr *CastExpr) {
  4941. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4942. "ActOnCastExpr(): missing type or expr");
  4943. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4944. if (D.isInvalidType())
  4945. return ExprError();
  4946. if (getLangOpts().CPlusPlus) {
  4947. // Check that there are no default arguments (C++ only).
  4948. CheckExtraCXXDefaultArguments(D);
  4949. } else {
  4950. // Make sure any TypoExprs have been dealt with.
  4951. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4952. if (!Res.isUsable())
  4953. return ExprError();
  4954. CastExpr = Res.get();
  4955. }
  4956. checkUnusedDeclAttributes(D);
  4957. QualType castType = castTInfo->getType();
  4958. Ty = CreateParsedType(castType, castTInfo);
  4959. bool isVectorLiteral = false;
  4960. // Check for an altivec or OpenCL literal,
  4961. // i.e. all the elements are integer constants.
  4962. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  4963. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  4964. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  4965. && castType->isVectorType() && (PE || PLE)) {
  4966. if (PLE && PLE->getNumExprs() == 0) {
  4967. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  4968. return ExprError();
  4969. }
  4970. if (PE || PLE->getNumExprs() == 1) {
  4971. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  4972. if (!E->getType()->isVectorType())
  4973. isVectorLiteral = true;
  4974. }
  4975. else
  4976. isVectorLiteral = true;
  4977. }
  4978. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  4979. // then handle it as such.
  4980. if (isVectorLiteral)
  4981. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  4982. // If the Expr being casted is a ParenListExpr, handle it specially.
  4983. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  4984. // sequence of BinOp comma operators.
  4985. if (isa<ParenListExpr>(CastExpr)) {
  4986. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  4987. if (Result.isInvalid()) return ExprError();
  4988. CastExpr = Result.get();
  4989. }
  4990. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  4991. !getSourceManager().isInSystemMacro(LParenLoc))
  4992. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  4993. CheckTollFreeBridgeCast(castType, CastExpr);
  4994. CheckObjCBridgeRelatedCast(castType, CastExpr);
  4995. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  4996. }
  4997. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  4998. SourceLocation RParenLoc, Expr *E,
  4999. TypeSourceInfo *TInfo) {
  5000. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5001. "Expected paren or paren list expression");
  5002. Expr **exprs;
  5003. unsigned numExprs;
  5004. Expr *subExpr;
  5005. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5006. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5007. LiteralLParenLoc = PE->getLParenLoc();
  5008. LiteralRParenLoc = PE->getRParenLoc();
  5009. exprs = PE->getExprs();
  5010. numExprs = PE->getNumExprs();
  5011. } else { // isa<ParenExpr> by assertion at function entrance
  5012. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5013. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5014. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5015. exprs = &subExpr;
  5016. numExprs = 1;
  5017. }
  5018. QualType Ty = TInfo->getType();
  5019. assert(Ty->isVectorType() && "Expected vector type");
  5020. SmallVector<Expr *, 8> initExprs;
  5021. const VectorType *VTy = Ty->getAs<VectorType>();
  5022. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5023. // '(...)' form of vector initialization in AltiVec: the number of
  5024. // initializers must be one or must match the size of the vector.
  5025. // If a single value is specified in the initializer then it will be
  5026. // replicated to all the components of the vector
  5027. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5028. // The number of initializers must be one or must match the size of the
  5029. // vector. If a single value is specified in the initializer then it will
  5030. // be replicated to all the components of the vector
  5031. if (numExprs == 1) {
  5032. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5033. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5034. if (Literal.isInvalid())
  5035. return ExprError();
  5036. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5037. PrepareScalarCast(Literal, ElemTy));
  5038. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5039. }
  5040. else if (numExprs < numElems) {
  5041. Diag(E->getExprLoc(),
  5042. diag::err_incorrect_number_of_vector_initializers);
  5043. return ExprError();
  5044. }
  5045. else
  5046. initExprs.append(exprs, exprs + numExprs);
  5047. }
  5048. else {
  5049. // For OpenCL, when the number of initializers is a single value,
  5050. // it will be replicated to all components of the vector.
  5051. if (getLangOpts().OpenCL &&
  5052. VTy->getVectorKind() == VectorType::GenericVector &&
  5053. numExprs == 1) {
  5054. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5055. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5056. if (Literal.isInvalid())
  5057. return ExprError();
  5058. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5059. PrepareScalarCast(Literal, ElemTy));
  5060. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5061. }
  5062. initExprs.append(exprs, exprs + numExprs);
  5063. }
  5064. // FIXME: This means that pretty-printing the final AST will produce curly
  5065. // braces instead of the original commas.
  5066. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5067. initExprs, LiteralRParenLoc);
  5068. initE->setType(Ty);
  5069. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5070. }
  5071. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5072. /// the ParenListExpr into a sequence of comma binary operators.
  5073. ExprResult
  5074. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5075. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5076. if (!E)
  5077. return OrigExpr;
  5078. ExprResult Result(E->getExpr(0));
  5079. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5080. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5081. E->getExpr(i));
  5082. if (Result.isInvalid()) return ExprError();
  5083. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5084. }
  5085. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5086. SourceLocation R,
  5087. MultiExprArg Val) {
  5088. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5089. return expr;
  5090. }
  5091. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  5092. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5093. /// emitted.
  5094. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5095. SourceLocation QuestionLoc) {
  5096. Expr *NullExpr = LHSExpr;
  5097. Expr *NonPointerExpr = RHSExpr;
  5098. Expr::NullPointerConstantKind NullKind =
  5099. NullExpr->isNullPointerConstant(Context,
  5100. Expr::NPC_ValueDependentIsNotNull);
  5101. if (NullKind == Expr::NPCK_NotNull) {
  5102. NullExpr = RHSExpr;
  5103. NonPointerExpr = LHSExpr;
  5104. NullKind =
  5105. NullExpr->isNullPointerConstant(Context,
  5106. Expr::NPC_ValueDependentIsNotNull);
  5107. }
  5108. if (NullKind == Expr::NPCK_NotNull)
  5109. return false;
  5110. if (NullKind == Expr::NPCK_ZeroExpression)
  5111. return false;
  5112. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5113. // In this case, check to make sure that we got here from a "NULL"
  5114. // string in the source code.
  5115. NullExpr = NullExpr->IgnoreParenImpCasts();
  5116. SourceLocation loc = NullExpr->getExprLoc();
  5117. if (!findMacroSpelling(loc, "NULL"))
  5118. return false;
  5119. }
  5120. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5121. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5122. << NonPointerExpr->getType() << DiagType
  5123. << NonPointerExpr->getSourceRange();
  5124. return true;
  5125. }
  5126. /// \brief Return false if the condition expression is valid, true otherwise.
  5127. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5128. QualType CondTy = Cond->getType();
  5129. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5130. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5131. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5132. << CondTy << Cond->getSourceRange();
  5133. return true;
  5134. }
  5135. // C99 6.5.15p2
  5136. if (CondTy->isScalarType()) return false;
  5137. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5138. << CondTy << Cond->getSourceRange();
  5139. return true;
  5140. }
  5141. /// \brief Handle when one or both operands are void type.
  5142. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5143. ExprResult &RHS) {
  5144. Expr *LHSExpr = LHS.get();
  5145. Expr *RHSExpr = RHS.get();
  5146. if (!LHSExpr->getType()->isVoidType())
  5147. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5148. << RHSExpr->getSourceRange();
  5149. if (!RHSExpr->getType()->isVoidType())
  5150. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5151. << LHSExpr->getSourceRange();
  5152. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5153. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5154. return S.Context.VoidTy;
  5155. }
  5156. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5157. /// true otherwise.
  5158. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5159. QualType PointerTy) {
  5160. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5161. !NullExpr.get()->isNullPointerConstant(S.Context,
  5162. Expr::NPC_ValueDependentIsNull))
  5163. return true;
  5164. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5165. return false;
  5166. }
  5167. /// \brief Checks compatibility between two pointers and return the resulting
  5168. /// type.
  5169. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5170. ExprResult &RHS,
  5171. SourceLocation Loc) {
  5172. QualType LHSTy = LHS.get()->getType();
  5173. QualType RHSTy = RHS.get()->getType();
  5174. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5175. // Two identical pointers types are always compatible.
  5176. return LHSTy;
  5177. }
  5178. QualType lhptee, rhptee;
  5179. // Get the pointee types.
  5180. bool IsBlockPointer = false;
  5181. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5182. lhptee = LHSBTy->getPointeeType();
  5183. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5184. IsBlockPointer = true;
  5185. } else {
  5186. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5187. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5188. }
  5189. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5190. // differently qualified versions of compatible types, the result type is
  5191. // a pointer to an appropriately qualified version of the composite
  5192. // type.
  5193. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5194. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5195. // be incompatible with address space 3: they may live on different devices or
  5196. // anything.
  5197. Qualifiers lhQual = lhptee.getQualifiers();
  5198. Qualifiers rhQual = rhptee.getQualifiers();
  5199. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5200. lhQual.removeCVRQualifiers();
  5201. rhQual.removeCVRQualifiers();
  5202. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5203. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5204. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5205. if (CompositeTy.isNull()) {
  5206. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5207. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5208. << RHS.get()->getSourceRange();
  5209. // In this situation, we assume void* type. No especially good
  5210. // reason, but this is what gcc does, and we do have to pick
  5211. // to get a consistent AST.
  5212. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  5213. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5214. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5215. return incompatTy;
  5216. }
  5217. // The pointer types are compatible.
  5218. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  5219. if (IsBlockPointer)
  5220. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5221. else
  5222. ResultTy = S.Context.getPointerType(ResultTy);
  5223. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  5224. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  5225. return ResultTy;
  5226. }
  5227. /// \brief Return the resulting type when the operands are both block pointers.
  5228. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5229. ExprResult &LHS,
  5230. ExprResult &RHS,
  5231. SourceLocation Loc) {
  5232. QualType LHSTy = LHS.get()->getType();
  5233. QualType RHSTy = RHS.get()->getType();
  5234. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5235. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5236. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5237. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5238. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5239. return destType;
  5240. }
  5241. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5242. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5243. << RHS.get()->getSourceRange();
  5244. return QualType();
  5245. }
  5246. // We have 2 block pointer types.
  5247. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5248. }
  5249. /// \brief Return the resulting type when the operands are both pointers.
  5250. static QualType
  5251. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5252. ExprResult &RHS,
  5253. SourceLocation Loc) {
  5254. // get the pointer types
  5255. QualType LHSTy = LHS.get()->getType();
  5256. QualType RHSTy = RHS.get()->getType();
  5257. // get the "pointed to" types
  5258. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5259. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5260. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5261. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5262. // Figure out necessary qualifiers (C99 6.5.15p6)
  5263. QualType destPointee
  5264. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5265. QualType destType = S.Context.getPointerType(destPointee);
  5266. // Add qualifiers if necessary.
  5267. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5268. // Promote to void*.
  5269. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5270. return destType;
  5271. }
  5272. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5273. QualType destPointee
  5274. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5275. QualType destType = S.Context.getPointerType(destPointee);
  5276. // Add qualifiers if necessary.
  5277. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5278. // Promote to void*.
  5279. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5280. return destType;
  5281. }
  5282. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5283. }
  5284. /// \brief Return false if the first expression is not an integer and the second
  5285. /// expression is not a pointer, true otherwise.
  5286. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5287. Expr* PointerExpr, SourceLocation Loc,
  5288. bool IsIntFirstExpr) {
  5289. if (!PointerExpr->getType()->isPointerType() ||
  5290. !Int.get()->getType()->isIntegerType())
  5291. return false;
  5292. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5293. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5294. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5295. << Expr1->getType() << Expr2->getType()
  5296. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5297. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5298. CK_IntegralToPointer);
  5299. return true;
  5300. }
  5301. /// \brief Simple conversion between integer and floating point types.
  5302. ///
  5303. /// Used when handling the OpenCL conditional operator where the
  5304. /// condition is a vector while the other operands are scalar.
  5305. ///
  5306. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5307. /// types are either integer or floating type. Between the two
  5308. /// operands, the type with the higher rank is defined as the "result
  5309. /// type". The other operand needs to be promoted to the same type. No
  5310. /// other type promotion is allowed. We cannot use
  5311. /// UsualArithmeticConversions() for this purpose, since it always
  5312. /// promotes promotable types.
  5313. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5314. ExprResult &RHS,
  5315. SourceLocation QuestionLoc) {
  5316. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5317. if (LHS.isInvalid())
  5318. return QualType();
  5319. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5320. if (RHS.isInvalid())
  5321. return QualType();
  5322. // For conversion purposes, we ignore any qualifiers.
  5323. // For example, "const float" and "float" are equivalent.
  5324. QualType LHSType =
  5325. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5326. QualType RHSType =
  5327. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5328. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5329. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5330. << LHSType << LHS.get()->getSourceRange();
  5331. return QualType();
  5332. }
  5333. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5334. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5335. << RHSType << RHS.get()->getSourceRange();
  5336. return QualType();
  5337. }
  5338. // If both types are identical, no conversion is needed.
  5339. if (LHSType == RHSType)
  5340. return LHSType;
  5341. // Now handle "real" floating types (i.e. float, double, long double).
  5342. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5343. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5344. /*IsCompAssign = */ false);
  5345. // Finally, we have two differing integer types.
  5346. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5347. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5348. }
  5349. /// \brief Convert scalar operands to a vector that matches the
  5350. /// condition in length.
  5351. ///
  5352. /// Used when handling the OpenCL conditional operator where the
  5353. /// condition is a vector while the other operands are scalar.
  5354. ///
  5355. /// We first compute the "result type" for the scalar operands
  5356. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5357. /// into a vector of that type where the length matches the condition
  5358. /// vector type. s6.11.6 requires that the element types of the result
  5359. /// and the condition must have the same number of bits.
  5360. static QualType
  5361. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5362. QualType CondTy, SourceLocation QuestionLoc) {
  5363. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5364. if (ResTy.isNull()) return QualType();
  5365. const VectorType *CV = CondTy->getAs<VectorType>();
  5366. assert(CV);
  5367. // Determine the vector result type
  5368. unsigned NumElements = CV->getNumElements();
  5369. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5370. // Ensure that all types have the same number of bits
  5371. if (S.Context.getTypeSize(CV->getElementType())
  5372. != S.Context.getTypeSize(ResTy)) {
  5373. // Since VectorTy is created internally, it does not pretty print
  5374. // with an OpenCL name. Instead, we just print a description.
  5375. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5376. SmallString<64> Str;
  5377. llvm::raw_svector_ostream OS(Str);
  5378. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5379. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5380. << CondTy << OS.str();
  5381. return QualType();
  5382. }
  5383. // Convert operands to the vector result type
  5384. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5385. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5386. return VectorTy;
  5387. }
  5388. /// \brief Return false if this is a valid OpenCL condition vector
  5389. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5390. SourceLocation QuestionLoc) {
  5391. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5392. // integral type.
  5393. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5394. assert(CondTy);
  5395. QualType EleTy = CondTy->getElementType();
  5396. if (EleTy->isIntegerType()) return false;
  5397. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5398. << Cond->getType() << Cond->getSourceRange();
  5399. return true;
  5400. }
  5401. /// \brief Return false if the vector condition type and the vector
  5402. /// result type are compatible.
  5403. ///
  5404. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5405. /// number of elements, and their element types have the same number
  5406. /// of bits.
  5407. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5408. SourceLocation QuestionLoc) {
  5409. const VectorType *CV = CondTy->getAs<VectorType>();
  5410. const VectorType *RV = VecResTy->getAs<VectorType>();
  5411. assert(CV && RV);
  5412. if (CV->getNumElements() != RV->getNumElements()) {
  5413. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5414. << CondTy << VecResTy;
  5415. return true;
  5416. }
  5417. QualType CVE = CV->getElementType();
  5418. QualType RVE = RV->getElementType();
  5419. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5420. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5421. << CondTy << VecResTy;
  5422. return true;
  5423. }
  5424. return false;
  5425. }
  5426. /// \brief Return the resulting type for the conditional operator in
  5427. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5428. /// s6.3.i) when the condition is a vector type.
  5429. static QualType
  5430. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5431. ExprResult &LHS, ExprResult &RHS,
  5432. SourceLocation QuestionLoc) {
  5433. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5434. if (Cond.isInvalid())
  5435. return QualType();
  5436. QualType CondTy = Cond.get()->getType();
  5437. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5438. return QualType();
  5439. // If either operand is a vector then find the vector type of the
  5440. // result as specified in OpenCL v1.1 s6.3.i.
  5441. if (LHS.get()->getType()->isVectorType() ||
  5442. RHS.get()->getType()->isVectorType()) {
  5443. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5444. /*isCompAssign*/false,
  5445. /*AllowBothBool*/true,
  5446. /*AllowBoolConversions*/false);
  5447. if (VecResTy.isNull()) return QualType();
  5448. // The result type must match the condition type as specified in
  5449. // OpenCL v1.1 s6.11.6.
  5450. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5451. return QualType();
  5452. return VecResTy;
  5453. }
  5454. // Both operands are scalar.
  5455. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5456. }
  5457. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5458. /// In that case, LHS = cond.
  5459. /// C99 6.5.15
  5460. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5461. ExprResult &RHS, ExprValueKind &VK,
  5462. ExprObjectKind &OK,
  5463. SourceLocation QuestionLoc) {
  5464. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5465. if (!LHSResult.isUsable()) return QualType();
  5466. LHS = LHSResult;
  5467. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5468. if (!RHSResult.isUsable()) return QualType();
  5469. RHS = RHSResult;
  5470. // C++ is sufficiently different to merit its own checker.
  5471. if (getLangOpts().CPlusPlus)
  5472. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5473. VK = VK_RValue;
  5474. OK = OK_Ordinary;
  5475. // The OpenCL operator with a vector condition is sufficiently
  5476. // different to merit its own checker.
  5477. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5478. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5479. // First, check the condition.
  5480. Cond = UsualUnaryConversions(Cond.get());
  5481. if (Cond.isInvalid())
  5482. return QualType();
  5483. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5484. return QualType();
  5485. // Now check the two expressions.
  5486. if (LHS.get()->getType()->isVectorType() ||
  5487. RHS.get()->getType()->isVectorType())
  5488. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5489. /*AllowBothBool*/true,
  5490. /*AllowBoolConversions*/false);
  5491. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5492. if (LHS.isInvalid() || RHS.isInvalid())
  5493. return QualType();
  5494. QualType LHSTy = LHS.get()->getType();
  5495. QualType RHSTy = RHS.get()->getType();
  5496. // If both operands have arithmetic type, do the usual arithmetic conversions
  5497. // to find a common type: C99 6.5.15p3,5.
  5498. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5499. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5500. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5501. return ResTy;
  5502. }
  5503. // If both operands are the same structure or union type, the result is that
  5504. // type.
  5505. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5506. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5507. if (LHSRT->getDecl() == RHSRT->getDecl())
  5508. // "If both the operands have structure or union type, the result has
  5509. // that type." This implies that CV qualifiers are dropped.
  5510. return LHSTy.getUnqualifiedType();
  5511. // FIXME: Type of conditional expression must be complete in C mode.
  5512. }
  5513. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5514. // The following || allows only one side to be void (a GCC-ism).
  5515. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5516. return checkConditionalVoidType(*this, LHS, RHS);
  5517. }
  5518. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5519. // the type of the other operand."
  5520. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5521. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5522. // All objective-c pointer type analysis is done here.
  5523. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5524. QuestionLoc);
  5525. if (LHS.isInvalid() || RHS.isInvalid())
  5526. return QualType();
  5527. if (!compositeType.isNull())
  5528. return compositeType;
  5529. // Handle block pointer types.
  5530. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5531. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5532. QuestionLoc);
  5533. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5534. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5535. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5536. QuestionLoc);
  5537. // GCC compatibility: soften pointer/integer mismatch. Note that
  5538. // null pointers have been filtered out by this point.
  5539. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5540. /*isIntFirstExpr=*/true))
  5541. return RHSTy;
  5542. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5543. /*isIntFirstExpr=*/false))
  5544. return LHSTy;
  5545. // Emit a better diagnostic if one of the expressions is a null pointer
  5546. // constant and the other is not a pointer type. In this case, the user most
  5547. // likely forgot to take the address of the other expression.
  5548. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5549. return QualType();
  5550. // Otherwise, the operands are not compatible.
  5551. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5552. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5553. << RHS.get()->getSourceRange();
  5554. return QualType();
  5555. }
  5556. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5557. /// two objective-c pointer types of the two input expressions.
  5558. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5559. SourceLocation QuestionLoc) {
  5560. QualType LHSTy = LHS.get()->getType();
  5561. QualType RHSTy = RHS.get()->getType();
  5562. // Handle things like Class and struct objc_class*. Here we case the result
  5563. // to the pseudo-builtin, because that will be implicitly cast back to the
  5564. // redefinition type if an attempt is made to access its fields.
  5565. if (LHSTy->isObjCClassType() &&
  5566. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5567. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5568. return LHSTy;
  5569. }
  5570. if (RHSTy->isObjCClassType() &&
  5571. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5572. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5573. return RHSTy;
  5574. }
  5575. // And the same for struct objc_object* / id
  5576. if (LHSTy->isObjCIdType() &&
  5577. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5578. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5579. return LHSTy;
  5580. }
  5581. if (RHSTy->isObjCIdType() &&
  5582. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5583. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5584. return RHSTy;
  5585. }
  5586. // And the same for struct objc_selector* / SEL
  5587. if (Context.isObjCSelType(LHSTy) &&
  5588. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5589. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5590. return LHSTy;
  5591. }
  5592. if (Context.isObjCSelType(RHSTy) &&
  5593. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5594. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5595. return RHSTy;
  5596. }
  5597. // Check constraints for Objective-C object pointers types.
  5598. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5599. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5600. // Two identical object pointer types are always compatible.
  5601. return LHSTy;
  5602. }
  5603. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5604. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5605. QualType compositeType = LHSTy;
  5606. // If both operands are interfaces and either operand can be
  5607. // assigned to the other, use that type as the composite
  5608. // type. This allows
  5609. // xxx ? (A*) a : (B*) b
  5610. // where B is a subclass of A.
  5611. //
  5612. // Additionally, as for assignment, if either type is 'id'
  5613. // allow silent coercion. Finally, if the types are
  5614. // incompatible then make sure to use 'id' as the composite
  5615. // type so the result is acceptable for sending messages to.
  5616. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5617. // It could return the composite type.
  5618. if (!(compositeType =
  5619. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  5620. // Nothing more to do.
  5621. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5622. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5623. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5624. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5625. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5626. RHSTy->isObjCQualifiedIdType()) &&
  5627. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5628. // Need to handle "id<xx>" explicitly.
  5629. // GCC allows qualified id and any Objective-C type to devolve to
  5630. // id. Currently localizing to here until clear this should be
  5631. // part of ObjCQualifiedIdTypesAreCompatible.
  5632. compositeType = Context.getObjCIdType();
  5633. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5634. compositeType = Context.getObjCIdType();
  5635. } else {
  5636. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5637. << LHSTy << RHSTy
  5638. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5639. QualType incompatTy = Context.getObjCIdType();
  5640. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5641. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5642. return incompatTy;
  5643. }
  5644. // The object pointer types are compatible.
  5645. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5646. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5647. return compositeType;
  5648. }
  5649. // Check Objective-C object pointer types and 'void *'
  5650. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5651. if (getLangOpts().ObjCAutoRefCount) {
  5652. // ARC forbids the implicit conversion of object pointers to 'void *',
  5653. // so these types are not compatible.
  5654. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5655. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5656. LHS = RHS = true;
  5657. return QualType();
  5658. }
  5659. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5660. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5661. QualType destPointee
  5662. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5663. QualType destType = Context.getPointerType(destPointee);
  5664. // Add qualifiers if necessary.
  5665. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5666. // Promote to void*.
  5667. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5668. return destType;
  5669. }
  5670. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5671. if (getLangOpts().ObjCAutoRefCount) {
  5672. // ARC forbids the implicit conversion of object pointers to 'void *',
  5673. // so these types are not compatible.
  5674. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5675. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5676. LHS = RHS = true;
  5677. return QualType();
  5678. }
  5679. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5680. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5681. QualType destPointee
  5682. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5683. QualType destType = Context.getPointerType(destPointee);
  5684. // Add qualifiers if necessary.
  5685. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5686. // Promote to void*.
  5687. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5688. return destType;
  5689. }
  5690. return QualType();
  5691. }
  5692. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5693. /// ParenRange in parentheses.
  5694. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5695. const PartialDiagnostic &Note,
  5696. SourceRange ParenRange) {
  5697. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  5698. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5699. EndLoc.isValid()) {
  5700. Self.Diag(Loc, Note)
  5701. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5702. << FixItHint::CreateInsertion(EndLoc, ")");
  5703. } else {
  5704. // We can't display the parentheses, so just show the bare note.
  5705. Self.Diag(Loc, Note) << ParenRange;
  5706. }
  5707. }
  5708. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5709. return Opc >= BO_Mul && Opc <= BO_Shr;
  5710. }
  5711. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5712. /// expression, either using a built-in or overloaded operator,
  5713. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5714. /// expression.
  5715. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5716. Expr **RHSExprs) {
  5717. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5718. E = E->IgnoreImpCasts();
  5719. E = E->IgnoreConversionOperator();
  5720. E = E->IgnoreImpCasts();
  5721. // Built-in binary operator.
  5722. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5723. if (IsArithmeticOp(OP->getOpcode())) {
  5724. *Opcode = OP->getOpcode();
  5725. *RHSExprs = OP->getRHS();
  5726. return true;
  5727. }
  5728. }
  5729. // Overloaded operator.
  5730. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5731. if (Call->getNumArgs() != 2)
  5732. return false;
  5733. // Make sure this is really a binary operator that is safe to pass into
  5734. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5735. OverloadedOperatorKind OO = Call->getOperator();
  5736. if (OO < OO_Plus || OO > OO_Arrow ||
  5737. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5738. return false;
  5739. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5740. if (IsArithmeticOp(OpKind)) {
  5741. *Opcode = OpKind;
  5742. *RHSExprs = Call->getArg(1);
  5743. return true;
  5744. }
  5745. }
  5746. return false;
  5747. }
  5748. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5749. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5750. }
  5751. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5752. /// or is a logical expression such as (x==y) which has int type, but is
  5753. /// commonly interpreted as boolean.
  5754. static bool ExprLooksBoolean(Expr *E) {
  5755. E = E->IgnoreParenImpCasts();
  5756. if (E->getType()->isBooleanType())
  5757. return true;
  5758. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5759. return IsLogicOp(OP->getOpcode());
  5760. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5761. return OP->getOpcode() == UO_LNot;
  5762. if (E->getType()->isPointerType())
  5763. return true;
  5764. return false;
  5765. }
  5766. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5767. /// and binary operator are mixed in a way that suggests the programmer assumed
  5768. /// the conditional operator has higher precedence, for example:
  5769. /// "int x = a + someBinaryCondition ? 1 : 2".
  5770. static void DiagnoseConditionalPrecedence(Sema &Self,
  5771. SourceLocation OpLoc,
  5772. Expr *Condition,
  5773. Expr *LHSExpr,
  5774. Expr *RHSExpr) {
  5775. BinaryOperatorKind CondOpcode;
  5776. Expr *CondRHS;
  5777. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5778. return;
  5779. if (!ExprLooksBoolean(CondRHS))
  5780. return;
  5781. // The condition is an arithmetic binary expression, with a right-
  5782. // hand side that looks boolean, so warn.
  5783. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5784. << Condition->getSourceRange()
  5785. << BinaryOperator::getOpcodeStr(CondOpcode);
  5786. SuggestParentheses(Self, OpLoc,
  5787. Self.PDiag(diag::note_precedence_silence)
  5788. << BinaryOperator::getOpcodeStr(CondOpcode),
  5789. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5790. SuggestParentheses(Self, OpLoc,
  5791. Self.PDiag(diag::note_precedence_conditional_first),
  5792. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5793. }
  5794. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5795. /// in the case of a the GNU conditional expr extension.
  5796. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5797. SourceLocation ColonLoc,
  5798. Expr *CondExpr, Expr *LHSExpr,
  5799. Expr *RHSExpr) {
  5800. if (!getLangOpts().CPlusPlus) {
  5801. // C cannot handle TypoExpr nodes in the condition because it
  5802. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5803. // been dealt with before checking the operands.
  5804. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5805. if (!CondResult.isUsable()) return ExprError();
  5806. CondExpr = CondResult.get();
  5807. }
  5808. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5809. // was the condition.
  5810. OpaqueValueExpr *opaqueValue = nullptr;
  5811. Expr *commonExpr = nullptr;
  5812. if (!LHSExpr) {
  5813. commonExpr = CondExpr;
  5814. // Lower out placeholder types first. This is important so that we don't
  5815. // try to capture a placeholder. This happens in few cases in C++; such
  5816. // as Objective-C++'s dictionary subscripting syntax.
  5817. if (commonExpr->hasPlaceholderType()) {
  5818. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5819. if (!result.isUsable()) return ExprError();
  5820. commonExpr = result.get();
  5821. }
  5822. // We usually want to apply unary conversions *before* saving, except
  5823. // in the special case of a C++ l-value conditional.
  5824. if (!(getLangOpts().CPlusPlus
  5825. && !commonExpr->isTypeDependent()
  5826. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5827. && commonExpr->isGLValue()
  5828. && commonExpr->isOrdinaryOrBitFieldObject()
  5829. && RHSExpr->isOrdinaryOrBitFieldObject()
  5830. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5831. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5832. if (commonRes.isInvalid())
  5833. return ExprError();
  5834. commonExpr = commonRes.get();
  5835. }
  5836. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5837. commonExpr->getType(),
  5838. commonExpr->getValueKind(),
  5839. commonExpr->getObjectKind(),
  5840. commonExpr);
  5841. LHSExpr = CondExpr = opaqueValue;
  5842. }
  5843. ExprValueKind VK = VK_RValue;
  5844. ExprObjectKind OK = OK_Ordinary;
  5845. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5846. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5847. VK, OK, QuestionLoc);
  5848. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5849. RHS.isInvalid())
  5850. return ExprError();
  5851. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5852. RHS.get());
  5853. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  5854. if (!commonExpr)
  5855. return new (Context)
  5856. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5857. RHS.get(), result, VK, OK);
  5858. return new (Context) BinaryConditionalOperator(
  5859. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5860. ColonLoc, result, VK, OK);
  5861. }
  5862. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5863. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5864. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5865. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5866. // FIXME: add a couple examples in this comment.
  5867. static Sema::AssignConvertType
  5868. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5869. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5870. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5871. // get the "pointed to" type (ignoring qualifiers at the top level)
  5872. const Type *lhptee, *rhptee;
  5873. Qualifiers lhq, rhq;
  5874. std::tie(lhptee, lhq) =
  5875. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5876. std::tie(rhptee, rhq) =
  5877. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5878. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5879. // C99 6.5.16.1p1: This following citation is common to constraints
  5880. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5881. // qualifiers of the type *pointed to* by the right;
  5882. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5883. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5884. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5885. // Ignore lifetime for further calculation.
  5886. lhq.removeObjCLifetime();
  5887. rhq.removeObjCLifetime();
  5888. }
  5889. if (!lhq.compatiblyIncludes(rhq)) {
  5890. // Treat address-space mismatches as fatal. TODO: address subspaces
  5891. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5892. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5893. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5894. // and from void*.
  5895. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5896. .compatiblyIncludes(
  5897. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5898. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5899. ; // keep old
  5900. // Treat lifetime mismatches as fatal.
  5901. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5902. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5903. // For GCC compatibility, other qualifier mismatches are treated
  5904. // as still compatible in C.
  5905. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5906. }
  5907. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5908. // incomplete type and the other is a pointer to a qualified or unqualified
  5909. // version of void...
  5910. if (lhptee->isVoidType()) {
  5911. if (rhptee->isIncompleteOrObjectType())
  5912. return ConvTy;
  5913. // As an extension, we allow cast to/from void* to function pointer.
  5914. assert(rhptee->isFunctionType());
  5915. return Sema::FunctionVoidPointer;
  5916. }
  5917. if (rhptee->isVoidType()) {
  5918. if (lhptee->isIncompleteOrObjectType())
  5919. return ConvTy;
  5920. // As an extension, we allow cast to/from void* to function pointer.
  5921. assert(lhptee->isFunctionType());
  5922. return Sema::FunctionVoidPointer;
  5923. }
  5924. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5925. // unqualified versions of compatible types, ...
  5926. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5927. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5928. // Check if the pointee types are compatible ignoring the sign.
  5929. // We explicitly check for char so that we catch "char" vs
  5930. // "unsigned char" on systems where "char" is unsigned.
  5931. if (lhptee->isCharType())
  5932. ltrans = S.Context.UnsignedCharTy;
  5933. else if (lhptee->hasSignedIntegerRepresentation())
  5934. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5935. if (rhptee->isCharType())
  5936. rtrans = S.Context.UnsignedCharTy;
  5937. else if (rhptee->hasSignedIntegerRepresentation())
  5938. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5939. if (ltrans == rtrans) {
  5940. // Types are compatible ignoring the sign. Qualifier incompatibility
  5941. // takes priority over sign incompatibility because the sign
  5942. // warning can be disabled.
  5943. if (ConvTy != Sema::Compatible)
  5944. return ConvTy;
  5945. return Sema::IncompatiblePointerSign;
  5946. }
  5947. // If we are a multi-level pointer, it's possible that our issue is simply
  5948. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5949. // the eventual target type is the same and the pointers have the same
  5950. // level of indirection, this must be the issue.
  5951. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5952. do {
  5953. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  5954. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  5955. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  5956. if (lhptee == rhptee)
  5957. return Sema::IncompatibleNestedPointerQualifiers;
  5958. }
  5959. // General pointer incompatibility takes priority over qualifiers.
  5960. return Sema::IncompatiblePointer;
  5961. }
  5962. if (!S.getLangOpts().CPlusPlus &&
  5963. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  5964. return Sema::IncompatiblePointer;
  5965. return ConvTy;
  5966. }
  5967. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  5968. /// block pointer types are compatible or whether a block and normal pointer
  5969. /// are compatible. It is more restrict than comparing two function pointer
  5970. // types.
  5971. static Sema::AssignConvertType
  5972. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  5973. QualType RHSType) {
  5974. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5975. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5976. QualType lhptee, rhptee;
  5977. // get the "pointed to" type (ignoring qualifiers at the top level)
  5978. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  5979. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  5980. // In C++, the types have to match exactly.
  5981. if (S.getLangOpts().CPlusPlus)
  5982. return Sema::IncompatibleBlockPointer;
  5983. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5984. // For blocks we enforce that qualifiers are identical.
  5985. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  5986. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5987. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  5988. return Sema::IncompatibleBlockPointer;
  5989. return ConvTy;
  5990. }
  5991. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  5992. /// for assignment compatibility.
  5993. static Sema::AssignConvertType
  5994. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  5995. QualType RHSType) {
  5996. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  5997. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  5998. if (LHSType->isObjCBuiltinType()) {
  5999. // Class is not compatible with ObjC object pointers.
  6000. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6001. !RHSType->isObjCQualifiedClassType())
  6002. return Sema::IncompatiblePointer;
  6003. return Sema::Compatible;
  6004. }
  6005. if (RHSType->isObjCBuiltinType()) {
  6006. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6007. !LHSType->isObjCQualifiedClassType())
  6008. return Sema::IncompatiblePointer;
  6009. return Sema::Compatible;
  6010. }
  6011. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6012. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6013. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6014. // make an exception for id<P>
  6015. !LHSType->isObjCQualifiedIdType())
  6016. return Sema::CompatiblePointerDiscardsQualifiers;
  6017. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6018. return Sema::Compatible;
  6019. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6020. return Sema::IncompatibleObjCQualifiedId;
  6021. return Sema::IncompatiblePointer;
  6022. }
  6023. Sema::AssignConvertType
  6024. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6025. QualType LHSType, QualType RHSType) {
  6026. // Fake up an opaque expression. We don't actually care about what
  6027. // cast operations are required, so if CheckAssignmentConstraints
  6028. // adds casts to this they'll be wasted, but fortunately that doesn't
  6029. // usually happen on valid code.
  6030. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6031. ExprResult RHSPtr = &RHSExpr;
  6032. CastKind K = CK_Invalid;
  6033. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  6034. }
  6035. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6036. /// has code to accommodate several GCC extensions when type checking
  6037. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6038. ///
  6039. /// int a, *pint;
  6040. /// short *pshort;
  6041. /// struct foo *pfoo;
  6042. ///
  6043. /// pint = pshort; // warning: assignment from incompatible pointer type
  6044. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6045. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6046. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6047. ///
  6048. /// As a result, the code for dealing with pointers is more complex than the
  6049. /// C99 spec dictates.
  6050. ///
  6051. /// Sets 'Kind' for any result kind except Incompatible.
  6052. Sema::AssignConvertType
  6053. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6054. CastKind &Kind, bool ConvertRHS) {
  6055. QualType RHSType = RHS.get()->getType();
  6056. QualType OrigLHSType = LHSType;
  6057. // Get canonical types. We're not formatting these types, just comparing
  6058. // them.
  6059. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6060. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6061. // Common case: no conversion required.
  6062. if (LHSType == RHSType) {
  6063. Kind = CK_NoOp;
  6064. return Compatible;
  6065. }
  6066. // If we have an atomic type, try a non-atomic assignment, then just add an
  6067. // atomic qualification step.
  6068. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6069. Sema::AssignConvertType result =
  6070. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6071. if (result != Compatible)
  6072. return result;
  6073. if (Kind != CK_NoOp && ConvertRHS)
  6074. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6075. Kind = CK_NonAtomicToAtomic;
  6076. return Compatible;
  6077. }
  6078. // If the left-hand side is a reference type, then we are in a
  6079. // (rare!) case where we've allowed the use of references in C,
  6080. // e.g., as a parameter type in a built-in function. In this case,
  6081. // just make sure that the type referenced is compatible with the
  6082. // right-hand side type. The caller is responsible for adjusting
  6083. // LHSType so that the resulting expression does not have reference
  6084. // type.
  6085. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6086. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6087. Kind = CK_LValueBitCast;
  6088. return Compatible;
  6089. }
  6090. return Incompatible;
  6091. }
  6092. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6093. // to the same ExtVector type.
  6094. if (LHSType->isExtVectorType()) {
  6095. if (RHSType->isExtVectorType())
  6096. return Incompatible;
  6097. if (RHSType->isArithmeticType()) {
  6098. // CK_VectorSplat does T -> vector T, so first cast to the
  6099. // element type.
  6100. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  6101. if (elType != RHSType && ConvertRHS) {
  6102. Kind = PrepareScalarCast(RHS, elType);
  6103. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  6104. }
  6105. Kind = CK_VectorSplat;
  6106. return Compatible;
  6107. }
  6108. }
  6109. // Conversions to or from vector type.
  6110. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6111. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6112. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6113. // vector type and vice versa
  6114. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6115. Kind = CK_BitCast;
  6116. return Compatible;
  6117. }
  6118. // If we are allowing lax vector conversions, and LHS and RHS are both
  6119. // vectors, the total size only needs to be the same. This is a bitcast;
  6120. // no bits are changed but the result type is different.
  6121. if (isLaxVectorConversion(RHSType, LHSType)) {
  6122. Kind = CK_BitCast;
  6123. return IncompatibleVectors;
  6124. }
  6125. }
  6126. return Incompatible;
  6127. }
  6128. // Arithmetic conversions.
  6129. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6130. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6131. if (ConvertRHS)
  6132. Kind = PrepareScalarCast(RHS, LHSType);
  6133. return Compatible;
  6134. }
  6135. // Conversions to normal pointers.
  6136. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6137. // U* -> T*
  6138. if (isa<PointerType>(RHSType)) {
  6139. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6140. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6141. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6142. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6143. }
  6144. // int -> T*
  6145. if (RHSType->isIntegerType()) {
  6146. Kind = CK_IntegralToPointer; // FIXME: null?
  6147. return IntToPointer;
  6148. }
  6149. // C pointers are not compatible with ObjC object pointers,
  6150. // with two exceptions:
  6151. if (isa<ObjCObjectPointerType>(RHSType)) {
  6152. // - conversions to void*
  6153. if (LHSPointer->getPointeeType()->isVoidType()) {
  6154. Kind = CK_BitCast;
  6155. return Compatible;
  6156. }
  6157. // - conversions from 'Class' to the redefinition type
  6158. if (RHSType->isObjCClassType() &&
  6159. Context.hasSameType(LHSType,
  6160. Context.getObjCClassRedefinitionType())) {
  6161. Kind = CK_BitCast;
  6162. return Compatible;
  6163. }
  6164. Kind = CK_BitCast;
  6165. return IncompatiblePointer;
  6166. }
  6167. // U^ -> void*
  6168. if (RHSType->getAs<BlockPointerType>()) {
  6169. if (LHSPointer->getPointeeType()->isVoidType()) {
  6170. Kind = CK_BitCast;
  6171. return Compatible;
  6172. }
  6173. }
  6174. return Incompatible;
  6175. }
  6176. // Conversions to block pointers.
  6177. if (isa<BlockPointerType>(LHSType)) {
  6178. // U^ -> T^
  6179. if (RHSType->isBlockPointerType()) {
  6180. Kind = CK_BitCast;
  6181. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6182. }
  6183. // int or null -> T^
  6184. if (RHSType->isIntegerType()) {
  6185. Kind = CK_IntegralToPointer; // FIXME: null
  6186. return IntToBlockPointer;
  6187. }
  6188. // id -> T^
  6189. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6190. Kind = CK_AnyPointerToBlockPointerCast;
  6191. return Compatible;
  6192. }
  6193. // void* -> T^
  6194. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6195. if (RHSPT->getPointeeType()->isVoidType()) {
  6196. Kind = CK_AnyPointerToBlockPointerCast;
  6197. return Compatible;
  6198. }
  6199. return Incompatible;
  6200. }
  6201. // Conversions to Objective-C pointers.
  6202. if (isa<ObjCObjectPointerType>(LHSType)) {
  6203. // A* -> B*
  6204. if (RHSType->isObjCObjectPointerType()) {
  6205. Kind = CK_BitCast;
  6206. Sema::AssignConvertType result =
  6207. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6208. if (getLangOpts().ObjCAutoRefCount &&
  6209. result == Compatible &&
  6210. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6211. result = IncompatibleObjCWeakRef;
  6212. return result;
  6213. }
  6214. // int or null -> A*
  6215. if (RHSType->isIntegerType()) {
  6216. Kind = CK_IntegralToPointer; // FIXME: null
  6217. return IntToPointer;
  6218. }
  6219. // In general, C pointers are not compatible with ObjC object pointers,
  6220. // with two exceptions:
  6221. if (isa<PointerType>(RHSType)) {
  6222. Kind = CK_CPointerToObjCPointerCast;
  6223. // - conversions from 'void*'
  6224. if (RHSType->isVoidPointerType()) {
  6225. return Compatible;
  6226. }
  6227. // - conversions to 'Class' from its redefinition type
  6228. if (LHSType->isObjCClassType() &&
  6229. Context.hasSameType(RHSType,
  6230. Context.getObjCClassRedefinitionType())) {
  6231. return Compatible;
  6232. }
  6233. return IncompatiblePointer;
  6234. }
  6235. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6236. if (RHSType->isBlockPointerType() &&
  6237. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6238. if (ConvertRHS)
  6239. maybeExtendBlockObject(RHS);
  6240. Kind = CK_BlockPointerToObjCPointerCast;
  6241. return Compatible;
  6242. }
  6243. return Incompatible;
  6244. }
  6245. // Conversions from pointers that are not covered by the above.
  6246. if (isa<PointerType>(RHSType)) {
  6247. // T* -> _Bool
  6248. if (LHSType == Context.BoolTy) {
  6249. Kind = CK_PointerToBoolean;
  6250. return Compatible;
  6251. }
  6252. // T* -> int
  6253. if (LHSType->isIntegerType()) {
  6254. Kind = CK_PointerToIntegral;
  6255. return PointerToInt;
  6256. }
  6257. return Incompatible;
  6258. }
  6259. // Conversions from Objective-C pointers that are not covered by the above.
  6260. if (isa<ObjCObjectPointerType>(RHSType)) {
  6261. // T* -> _Bool
  6262. if (LHSType == Context.BoolTy) {
  6263. Kind = CK_PointerToBoolean;
  6264. return Compatible;
  6265. }
  6266. // T* -> int
  6267. if (LHSType->isIntegerType()) {
  6268. Kind = CK_PointerToIntegral;
  6269. return PointerToInt;
  6270. }
  6271. return Incompatible;
  6272. }
  6273. // struct A -> struct B
  6274. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6275. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6276. Kind = CK_NoOp;
  6277. return Compatible;
  6278. }
  6279. }
  6280. return Incompatible;
  6281. }
  6282. /// \brief Constructs a transparent union from an expression that is
  6283. /// used to initialize the transparent union.
  6284. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6285. ExprResult &EResult, QualType UnionType,
  6286. FieldDecl *Field) {
  6287. // Build an initializer list that designates the appropriate member
  6288. // of the transparent union.
  6289. Expr *E = EResult.get();
  6290. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6291. E, SourceLocation());
  6292. Initializer->setType(UnionType);
  6293. Initializer->setInitializedFieldInUnion(Field);
  6294. // Build a compound literal constructing a value of the transparent
  6295. // union type from this initializer list.
  6296. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6297. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6298. VK_RValue, Initializer, false);
  6299. }
  6300. Sema::AssignConvertType
  6301. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6302. ExprResult &RHS) {
  6303. QualType RHSType = RHS.get()->getType();
  6304. // If the ArgType is a Union type, we want to handle a potential
  6305. // transparent_union GCC extension.
  6306. const RecordType *UT = ArgType->getAsUnionType();
  6307. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6308. return Incompatible;
  6309. // The field to initialize within the transparent union.
  6310. RecordDecl *UD = UT->getDecl();
  6311. FieldDecl *InitField = nullptr;
  6312. // It's compatible if the expression matches any of the fields.
  6313. for (auto *it : UD->fields()) {
  6314. if (it->getType()->isPointerType()) {
  6315. // If the transparent union contains a pointer type, we allow:
  6316. // 1) void pointer
  6317. // 2) null pointer constant
  6318. if (RHSType->isPointerType())
  6319. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6320. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6321. InitField = it;
  6322. break;
  6323. }
  6324. if (RHS.get()->isNullPointerConstant(Context,
  6325. Expr::NPC_ValueDependentIsNull)) {
  6326. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6327. CK_NullToPointer);
  6328. InitField = it;
  6329. break;
  6330. }
  6331. }
  6332. CastKind Kind = CK_Invalid;
  6333. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6334. == Compatible) {
  6335. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6336. InitField = it;
  6337. break;
  6338. }
  6339. }
  6340. if (!InitField)
  6341. return Incompatible;
  6342. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6343. return Compatible;
  6344. }
  6345. Sema::AssignConvertType
  6346. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  6347. bool Diagnose,
  6348. bool DiagnoseCFAudited,
  6349. bool ConvertRHS) {
  6350. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  6351. // we can't avoid *all* modifications at the moment, so we need some somewhere
  6352. // to put the updated value.
  6353. ExprResult LocalRHS = CallerRHS;
  6354. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  6355. if (getLangOpts().CPlusPlus) {
  6356. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6357. // C++ 5.17p3: If the left operand is not of class type, the
  6358. // expression is implicitly converted (C++ 4) to the
  6359. // cv-unqualified type of the left operand.
  6360. ExprResult Res;
  6361. if (Diagnose) {
  6362. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6363. AA_Assigning);
  6364. } else {
  6365. ImplicitConversionSequence ICS =
  6366. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6367. /*SuppressUserConversions=*/false,
  6368. /*AllowExplicit=*/false,
  6369. /*InOverloadResolution=*/false,
  6370. /*CStyle=*/false,
  6371. /*AllowObjCWritebackConversion=*/false);
  6372. if (ICS.isFailure())
  6373. return Incompatible;
  6374. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6375. ICS, AA_Assigning);
  6376. }
  6377. if (Res.isInvalid())
  6378. return Incompatible;
  6379. Sema::AssignConvertType result = Compatible;
  6380. if (getLangOpts().ObjCAutoRefCount &&
  6381. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6382. RHS.get()->getType()))
  6383. result = IncompatibleObjCWeakRef;
  6384. RHS = Res;
  6385. return result;
  6386. }
  6387. // FIXME: Currently, we fall through and treat C++ classes like C
  6388. // structures.
  6389. // FIXME: We also fall through for atomics; not sure what should
  6390. // happen there, though.
  6391. } else if (RHS.get()->getType() == Context.OverloadTy) {
  6392. // As a set of extensions to C, we support overloading on functions. These
  6393. // functions need to be resolved here.
  6394. DeclAccessPair DAP;
  6395. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  6396. RHS.get(), LHSType, /*Complain=*/false, DAP))
  6397. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  6398. else
  6399. return Incompatible;
  6400. }
  6401. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6402. // a null pointer constant.
  6403. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6404. LHSType->isBlockPointerType()) &&
  6405. RHS.get()->isNullPointerConstant(Context,
  6406. Expr::NPC_ValueDependentIsNull)) {
  6407. CastKind Kind;
  6408. CXXCastPath Path;
  6409. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6410. if (ConvertRHS)
  6411. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6412. return Compatible;
  6413. }
  6414. // This check seems unnatural, however it is necessary to ensure the proper
  6415. // conversion of functions/arrays. If the conversion were done for all
  6416. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6417. // expressions that suppress this implicit conversion (&, sizeof).
  6418. //
  6419. // Suppress this for references: C++ 8.5.3p5.
  6420. if (!LHSType->isReferenceType()) {
  6421. // FIXME: We potentially allocate here even if ConvertRHS is false.
  6422. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  6423. if (RHS.isInvalid())
  6424. return Incompatible;
  6425. }
  6426. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6427. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6428. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6429. if (PDecl && !PDecl->hasDefinition()) {
  6430. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6431. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6432. }
  6433. }
  6434. CastKind Kind = CK_Invalid;
  6435. Sema::AssignConvertType result =
  6436. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  6437. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6438. // type of the assignment expression.
  6439. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6440. // so that we can use references in built-in functions even in C.
  6441. // The getNonReferenceType() call makes sure that the resulting expression
  6442. // does not have reference type.
  6443. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6444. QualType Ty = LHSType.getNonLValueExprType(Context);
  6445. Expr *E = RHS.get();
  6446. if (getLangOpts().ObjCAutoRefCount)
  6447. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6448. DiagnoseCFAudited);
  6449. if (getLangOpts().ObjC1 &&
  6450. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6451. LHSType, E->getType(), E) ||
  6452. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6453. RHS = E;
  6454. return Compatible;
  6455. }
  6456. if (ConvertRHS)
  6457. RHS = ImpCastExprToType(E, Ty, Kind);
  6458. }
  6459. return result;
  6460. }
  6461. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6462. ExprResult &RHS) {
  6463. Diag(Loc, diag::err_typecheck_invalid_operands)
  6464. << LHS.get()->getType() << RHS.get()->getType()
  6465. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6466. return QualType();
  6467. }
  6468. /// Try to convert a value of non-vector type to a vector type by converting
  6469. /// the type to the element type of the vector and then performing a splat.
  6470. /// If the language is OpenCL, we only use conversions that promote scalar
  6471. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6472. /// for float->int.
  6473. ///
  6474. /// \param scalar - if non-null, actually perform the conversions
  6475. /// \return true if the operation fails (but without diagnosing the failure)
  6476. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6477. QualType scalarTy,
  6478. QualType vectorEltTy,
  6479. QualType vectorTy) {
  6480. // The conversion to apply to the scalar before splatting it,
  6481. // if necessary.
  6482. CastKind scalarCast = CK_Invalid;
  6483. if (vectorEltTy->isIntegralType(S.Context)) {
  6484. if (!scalarTy->isIntegralType(S.Context))
  6485. return true;
  6486. if (S.getLangOpts().OpenCL &&
  6487. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6488. return true;
  6489. scalarCast = CK_IntegralCast;
  6490. } else if (vectorEltTy->isRealFloatingType()) {
  6491. if (scalarTy->isRealFloatingType()) {
  6492. if (S.getLangOpts().OpenCL &&
  6493. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6494. return true;
  6495. scalarCast = CK_FloatingCast;
  6496. }
  6497. else if (scalarTy->isIntegralType(S.Context))
  6498. scalarCast = CK_IntegralToFloating;
  6499. else
  6500. return true;
  6501. } else {
  6502. return true;
  6503. }
  6504. // Adjust scalar if desired.
  6505. if (scalar) {
  6506. if (scalarCast != CK_Invalid)
  6507. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6508. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6509. }
  6510. return false;
  6511. }
  6512. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6513. SourceLocation Loc, bool IsCompAssign,
  6514. bool AllowBothBool,
  6515. bool AllowBoolConversions) {
  6516. if (!IsCompAssign) {
  6517. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6518. if (LHS.isInvalid())
  6519. return QualType();
  6520. }
  6521. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6522. if (RHS.isInvalid())
  6523. return QualType();
  6524. // For conversion purposes, we ignore any qualifiers.
  6525. // For example, "const float" and "float" are equivalent.
  6526. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6527. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6528. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6529. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6530. assert(LHSVecType || RHSVecType);
  6531. // AltiVec-style "vector bool op vector bool" combinations are allowed
  6532. // for some operators but not others.
  6533. if (!AllowBothBool &&
  6534. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6535. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  6536. return InvalidOperands(Loc, LHS, RHS);
  6537. // If the vector types are identical, return.
  6538. if (Context.hasSameType(LHSType, RHSType))
  6539. return LHSType;
  6540. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6541. if (LHSVecType && RHSVecType &&
  6542. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6543. if (isa<ExtVectorType>(LHSVecType)) {
  6544. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6545. return LHSType;
  6546. }
  6547. if (!IsCompAssign)
  6548. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6549. return RHSType;
  6550. }
  6551. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  6552. // can be mixed, with the result being the non-bool type. The non-bool
  6553. // operand must have integer element type.
  6554. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  6555. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  6556. (Context.getTypeSize(LHSVecType->getElementType()) ==
  6557. Context.getTypeSize(RHSVecType->getElementType()))) {
  6558. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6559. LHSVecType->getElementType()->isIntegerType() &&
  6560. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  6561. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6562. return LHSType;
  6563. }
  6564. if (!IsCompAssign &&
  6565. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6566. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6567. RHSVecType->getElementType()->isIntegerType()) {
  6568. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6569. return RHSType;
  6570. }
  6571. }
  6572. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6573. // the vector element type and splat.
  6574. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6575. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6576. LHSVecType->getElementType(), LHSType))
  6577. return LHSType;
  6578. }
  6579. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6580. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6581. LHSType, RHSVecType->getElementType(),
  6582. RHSType))
  6583. return RHSType;
  6584. }
  6585. // If we're allowing lax vector conversions, only the total (data) size
  6586. // needs to be the same.
  6587. // FIXME: Should we really be allowing this?
  6588. // FIXME: We really just pick the LHS type arbitrarily?
  6589. if (isLaxVectorConversion(RHSType, LHSType)) {
  6590. QualType resultType = LHSType;
  6591. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6592. return resultType;
  6593. }
  6594. // Okay, the expression is invalid.
  6595. // If there's a non-vector, non-real operand, diagnose that.
  6596. if ((!RHSVecType && !RHSType->isRealType()) ||
  6597. (!LHSVecType && !LHSType->isRealType())) {
  6598. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6599. << LHSType << RHSType
  6600. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6601. return QualType();
  6602. }
  6603. // OpenCL V1.1 6.2.6.p1:
  6604. // If the operands are of more than one vector type, then an error shall
  6605. // occur. Implicit conversions between vector types are not permitted, per
  6606. // section 6.2.1.
  6607. if (getLangOpts().OpenCL &&
  6608. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  6609. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6610. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  6611. << RHSType;
  6612. return QualType();
  6613. }
  6614. // Otherwise, use the generic diagnostic.
  6615. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6616. << LHSType << RHSType
  6617. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6618. return QualType();
  6619. }
  6620. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6621. // expression. These are mainly cases where the null pointer is used as an
  6622. // integer instead of a pointer.
  6623. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6624. SourceLocation Loc, bool IsCompare) {
  6625. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6626. // but we use a bit of a hack here for speed; this is a relatively
  6627. // hot path, and isNullPointerConstant is slow.
  6628. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6629. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6630. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6631. // Avoid analyzing cases where the result will either be invalid (and
  6632. // diagnosed as such) or entirely valid and not something to warn about.
  6633. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6634. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6635. return;
  6636. // Comparison operations would not make sense with a null pointer no matter
  6637. // what the other expression is.
  6638. if (!IsCompare) {
  6639. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6640. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6641. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6642. return;
  6643. }
  6644. // The rest of the operations only make sense with a null pointer
  6645. // if the other expression is a pointer.
  6646. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6647. NonNullType->canDecayToPointerType())
  6648. return;
  6649. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6650. << LHSNull /* LHS is NULL */ << NonNullType
  6651. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6652. }
  6653. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  6654. ExprResult &RHS,
  6655. SourceLocation Loc, bool IsDiv) {
  6656. // Check for division/remainder by zero.
  6657. llvm::APSInt RHSValue;
  6658. if (!RHS.get()->isValueDependent() &&
  6659. RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
  6660. S.DiagRuntimeBehavior(Loc, RHS.get(),
  6661. S.PDiag(diag::warn_remainder_division_by_zero)
  6662. << IsDiv << RHS.get()->getSourceRange());
  6663. }
  6664. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6665. SourceLocation Loc,
  6666. bool IsCompAssign, bool IsDiv) {
  6667. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6668. if (LHS.get()->getType()->isVectorType() ||
  6669. RHS.get()->getType()->isVectorType())
  6670. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6671. /*AllowBothBool*/getLangOpts().AltiVec,
  6672. /*AllowBoolConversions*/false);
  6673. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6674. if (LHS.isInvalid() || RHS.isInvalid())
  6675. return QualType();
  6676. if (compType.isNull() || !compType->isArithmeticType())
  6677. return InvalidOperands(Loc, LHS, RHS);
  6678. if (IsDiv)
  6679. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  6680. return compType;
  6681. }
  6682. QualType Sema::CheckRemainderOperands(
  6683. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6684. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6685. if (LHS.get()->getType()->isVectorType() ||
  6686. RHS.get()->getType()->isVectorType()) {
  6687. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6688. RHS.get()->getType()->hasIntegerRepresentation())
  6689. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6690. /*AllowBothBool*/getLangOpts().AltiVec,
  6691. /*AllowBoolConversions*/false);
  6692. return InvalidOperands(Loc, LHS, RHS);
  6693. }
  6694. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6695. if (LHS.isInvalid() || RHS.isInvalid())
  6696. return QualType();
  6697. if (compType.isNull() || !compType->isIntegerType())
  6698. return InvalidOperands(Loc, LHS, RHS);
  6699. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  6700. return compType;
  6701. }
  6702. /// \brief Diagnose invalid arithmetic on two void pointers.
  6703. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6704. Expr *LHSExpr, Expr *RHSExpr) {
  6705. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6706. ? diag::err_typecheck_pointer_arith_void_type
  6707. : diag::ext_gnu_void_ptr)
  6708. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6709. << RHSExpr->getSourceRange();
  6710. }
  6711. /// \brief Diagnose invalid arithmetic on a void pointer.
  6712. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6713. Expr *Pointer) {
  6714. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6715. ? diag::err_typecheck_pointer_arith_void_type
  6716. : diag::ext_gnu_void_ptr)
  6717. << 0 /* one pointer */ << Pointer->getSourceRange();
  6718. }
  6719. /// \brief Diagnose invalid arithmetic on two function pointers.
  6720. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6721. Expr *LHS, Expr *RHS) {
  6722. assert(LHS->getType()->isAnyPointerType());
  6723. assert(RHS->getType()->isAnyPointerType());
  6724. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6725. ? diag::err_typecheck_pointer_arith_function_type
  6726. : diag::ext_gnu_ptr_func_arith)
  6727. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6728. // We only show the second type if it differs from the first.
  6729. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6730. RHS->getType())
  6731. << RHS->getType()->getPointeeType()
  6732. << LHS->getSourceRange() << RHS->getSourceRange();
  6733. }
  6734. /// \brief Diagnose invalid arithmetic on a function pointer.
  6735. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6736. Expr *Pointer) {
  6737. assert(Pointer->getType()->isAnyPointerType());
  6738. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6739. ? diag::err_typecheck_pointer_arith_function_type
  6740. : diag::ext_gnu_ptr_func_arith)
  6741. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6742. << 0 /* one pointer, so only one type */
  6743. << Pointer->getSourceRange();
  6744. }
  6745. /// \brief Emit error if Operand is incomplete pointer type
  6746. ///
  6747. /// \returns True if pointer has incomplete type
  6748. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6749. Expr *Operand) {
  6750. QualType ResType = Operand->getType();
  6751. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6752. ResType = ResAtomicType->getValueType();
  6753. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6754. QualType PointeeTy = ResType->getPointeeType();
  6755. return S.RequireCompleteType(Loc, PointeeTy,
  6756. diag::err_typecheck_arithmetic_incomplete_type,
  6757. PointeeTy, Operand->getSourceRange());
  6758. }
  6759. /// \brief Check the validity of an arithmetic pointer operand.
  6760. ///
  6761. /// If the operand has pointer type, this code will check for pointer types
  6762. /// which are invalid in arithmetic operations. These will be diagnosed
  6763. /// appropriately, including whether or not the use is supported as an
  6764. /// extension.
  6765. ///
  6766. /// \returns True when the operand is valid to use (even if as an extension).
  6767. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6768. Expr *Operand) {
  6769. QualType ResType = Operand->getType();
  6770. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6771. ResType = ResAtomicType->getValueType();
  6772. if (!ResType->isAnyPointerType()) return true;
  6773. QualType PointeeTy = ResType->getPointeeType();
  6774. if (PointeeTy->isVoidType()) {
  6775. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6776. return !S.getLangOpts().CPlusPlus;
  6777. }
  6778. if (PointeeTy->isFunctionType()) {
  6779. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6780. return !S.getLangOpts().CPlusPlus;
  6781. }
  6782. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6783. return true;
  6784. }
  6785. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6786. /// operands.
  6787. ///
  6788. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6789. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6790. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6791. /// are (potentially problematic) pointers.
  6792. ///
  6793. /// \returns True when the operand is valid to use (even if as an extension).
  6794. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6795. Expr *LHSExpr, Expr *RHSExpr) {
  6796. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6797. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6798. if (!isLHSPointer && !isRHSPointer) return true;
  6799. QualType LHSPointeeTy, RHSPointeeTy;
  6800. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6801. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6802. // if both are pointers check if operation is valid wrt address spaces
  6803. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  6804. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6805. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6806. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6807. S.Diag(Loc,
  6808. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6809. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6810. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6811. return false;
  6812. }
  6813. }
  6814. // Check for arithmetic on pointers to incomplete types.
  6815. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6816. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6817. if (isLHSVoidPtr || isRHSVoidPtr) {
  6818. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6819. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6820. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6821. return !S.getLangOpts().CPlusPlus;
  6822. }
  6823. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6824. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6825. if (isLHSFuncPtr || isRHSFuncPtr) {
  6826. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6827. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6828. RHSExpr);
  6829. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6830. return !S.getLangOpts().CPlusPlus;
  6831. }
  6832. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6833. return false;
  6834. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6835. return false;
  6836. return true;
  6837. }
  6838. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6839. /// literal.
  6840. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6841. Expr *LHSExpr, Expr *RHSExpr) {
  6842. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6843. Expr* IndexExpr = RHSExpr;
  6844. if (!StrExpr) {
  6845. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6846. IndexExpr = LHSExpr;
  6847. }
  6848. bool IsStringPlusInt = StrExpr &&
  6849. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6850. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6851. return;
  6852. llvm::APSInt index;
  6853. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6854. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6855. if (index.isNonNegative() &&
  6856. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6857. index.isUnsigned()))
  6858. return;
  6859. }
  6860. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6861. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6862. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6863. // Only print a fixit for "str" + int, not for int + "str".
  6864. if (IndexExpr == RHSExpr) {
  6865. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
  6866. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6867. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6868. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6869. << FixItHint::CreateInsertion(EndLoc, "]");
  6870. } else
  6871. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6872. }
  6873. /// \brief Emit a warning when adding a char literal to a string.
  6874. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6875. Expr *LHSExpr, Expr *RHSExpr) {
  6876. const Expr *StringRefExpr = LHSExpr;
  6877. const CharacterLiteral *CharExpr =
  6878. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6879. if (!CharExpr) {
  6880. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6881. StringRefExpr = RHSExpr;
  6882. }
  6883. if (!CharExpr || !StringRefExpr)
  6884. return;
  6885. const QualType StringType = StringRefExpr->getType();
  6886. // Return if not a PointerType.
  6887. if (!StringType->isAnyPointerType())
  6888. return;
  6889. // Return if not a CharacterType.
  6890. if (!StringType->getPointeeType()->isAnyCharacterType())
  6891. return;
  6892. ASTContext &Ctx = Self.getASTContext();
  6893. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6894. const QualType CharType = CharExpr->getType();
  6895. if (!CharType->isAnyCharacterType() &&
  6896. CharType->isIntegerType() &&
  6897. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6898. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6899. << DiagRange << Ctx.CharTy;
  6900. } else {
  6901. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6902. << DiagRange << CharExpr->getType();
  6903. }
  6904. // Only print a fixit for str + char, not for char + str.
  6905. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6906. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
  6907. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6908. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6909. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6910. << FixItHint::CreateInsertion(EndLoc, "]");
  6911. } else {
  6912. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6913. }
  6914. }
  6915. /// \brief Emit error when two pointers are incompatible.
  6916. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6917. Expr *LHSExpr, Expr *RHSExpr) {
  6918. assert(LHSExpr->getType()->isAnyPointerType());
  6919. assert(RHSExpr->getType()->isAnyPointerType());
  6920. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6921. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6922. << RHSExpr->getSourceRange();
  6923. }
  6924. // C99 6.5.6
  6925. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  6926. SourceLocation Loc, BinaryOperatorKind Opc,
  6927. QualType* CompLHSTy) {
  6928. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6929. if (LHS.get()->getType()->isVectorType() ||
  6930. RHS.get()->getType()->isVectorType()) {
  6931. QualType compType = CheckVectorOperands(
  6932. LHS, RHS, Loc, CompLHSTy,
  6933. /*AllowBothBool*/getLangOpts().AltiVec,
  6934. /*AllowBoolConversions*/getLangOpts().ZVector);
  6935. if (CompLHSTy) *CompLHSTy = compType;
  6936. return compType;
  6937. }
  6938. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6939. if (LHS.isInvalid() || RHS.isInvalid())
  6940. return QualType();
  6941. // Diagnose "string literal" '+' int and string '+' "char literal".
  6942. if (Opc == BO_Add) {
  6943. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6944. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6945. }
  6946. // handle the common case first (both operands are arithmetic).
  6947. if (!compType.isNull() && compType->isArithmeticType()) {
  6948. if (CompLHSTy) *CompLHSTy = compType;
  6949. return compType;
  6950. }
  6951. // Type-checking. Ultimately the pointer's going to be in PExp;
  6952. // note that we bias towards the LHS being the pointer.
  6953. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6954. bool isObjCPointer;
  6955. if (PExp->getType()->isPointerType()) {
  6956. isObjCPointer = false;
  6957. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6958. isObjCPointer = true;
  6959. } else {
  6960. std::swap(PExp, IExp);
  6961. if (PExp->getType()->isPointerType()) {
  6962. isObjCPointer = false;
  6963. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6964. isObjCPointer = true;
  6965. } else {
  6966. return InvalidOperands(Loc, LHS, RHS);
  6967. }
  6968. }
  6969. assert(PExp->getType()->isAnyPointerType());
  6970. if (!IExp->getType()->isIntegerType())
  6971. return InvalidOperands(Loc, LHS, RHS);
  6972. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6973. return QualType();
  6974. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6975. return QualType();
  6976. // Check array bounds for pointer arithemtic
  6977. CheckArrayAccess(PExp, IExp);
  6978. if (CompLHSTy) {
  6979. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  6980. if (LHSTy.isNull()) {
  6981. LHSTy = LHS.get()->getType();
  6982. if (LHSTy->isPromotableIntegerType())
  6983. LHSTy = Context.getPromotedIntegerType(LHSTy);
  6984. }
  6985. *CompLHSTy = LHSTy;
  6986. }
  6987. return PExp->getType();
  6988. }
  6989. // C99 6.5.6
  6990. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  6991. SourceLocation Loc,
  6992. QualType* CompLHSTy) {
  6993. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6994. if (LHS.get()->getType()->isVectorType() ||
  6995. RHS.get()->getType()->isVectorType()) {
  6996. QualType compType = CheckVectorOperands(
  6997. LHS, RHS, Loc, CompLHSTy,
  6998. /*AllowBothBool*/getLangOpts().AltiVec,
  6999. /*AllowBoolConversions*/getLangOpts().ZVector);
  7000. if (CompLHSTy) *CompLHSTy = compType;
  7001. return compType;
  7002. }
  7003. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7004. if (LHS.isInvalid() || RHS.isInvalid())
  7005. return QualType();
  7006. // Enforce type constraints: C99 6.5.6p3.
  7007. // Handle the common case first (both operands are arithmetic).
  7008. if (!compType.isNull() && compType->isArithmeticType()) {
  7009. if (CompLHSTy) *CompLHSTy = compType;
  7010. return compType;
  7011. }
  7012. // Either ptr - int or ptr - ptr.
  7013. if (LHS.get()->getType()->isAnyPointerType()) {
  7014. QualType lpointee = LHS.get()->getType()->getPointeeType();
  7015. // Diagnose bad cases where we step over interface counts.
  7016. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  7017. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  7018. return QualType();
  7019. // The result type of a pointer-int computation is the pointer type.
  7020. if (RHS.get()->getType()->isIntegerType()) {
  7021. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  7022. return QualType();
  7023. // Check array bounds for pointer arithemtic
  7024. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  7025. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  7026. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7027. return LHS.get()->getType();
  7028. }
  7029. // Handle pointer-pointer subtractions.
  7030. if (const PointerType *RHSPTy
  7031. = RHS.get()->getType()->getAs<PointerType>()) {
  7032. QualType rpointee = RHSPTy->getPointeeType();
  7033. if (getLangOpts().CPlusPlus) {
  7034. // Pointee types must be the same: C++ [expr.add]
  7035. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  7036. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7037. }
  7038. } else {
  7039. // Pointee types must be compatible C99 6.5.6p3
  7040. if (!Context.typesAreCompatible(
  7041. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  7042. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  7043. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7044. return QualType();
  7045. }
  7046. }
  7047. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  7048. LHS.get(), RHS.get()))
  7049. return QualType();
  7050. // The pointee type may have zero size. As an extension, a structure or
  7051. // union may have zero size or an array may have zero length. In this
  7052. // case subtraction does not make sense.
  7053. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7054. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7055. if (ElementSize.isZero()) {
  7056. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7057. << rpointee.getUnqualifiedType()
  7058. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7059. }
  7060. }
  7061. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7062. return Context.getPointerDiffType();
  7063. }
  7064. }
  7065. return InvalidOperands(Loc, LHS, RHS);
  7066. }
  7067. static bool isScopedEnumerationType(QualType T) {
  7068. if (const EnumType *ET = T->getAs<EnumType>())
  7069. return ET->getDecl()->isScoped();
  7070. return false;
  7071. }
  7072. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  7073. SourceLocation Loc, BinaryOperatorKind Opc,
  7074. QualType LHSType) {
  7075. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  7076. // so skip remaining warnings as we don't want to modify values within Sema.
  7077. if (S.getLangOpts().OpenCL)
  7078. return;
  7079. llvm::APSInt Right;
  7080. // Check right/shifter operand
  7081. if (RHS.get()->isValueDependent() ||
  7082. !RHS.get()->EvaluateAsInt(Right, S.Context))
  7083. return;
  7084. if (Right.isNegative()) {
  7085. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7086. S.PDiag(diag::warn_shift_negative)
  7087. << RHS.get()->getSourceRange());
  7088. return;
  7089. }
  7090. llvm::APInt LeftBits(Right.getBitWidth(),
  7091. S.Context.getTypeSize(LHS.get()->getType()));
  7092. if (Right.uge(LeftBits)) {
  7093. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7094. S.PDiag(diag::warn_shift_gt_typewidth)
  7095. << RHS.get()->getSourceRange());
  7096. return;
  7097. }
  7098. if (Opc != BO_Shl)
  7099. return;
  7100. // When left shifting an ICE which is signed, we can check for overflow which
  7101. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  7102. // integers have defined behavior modulo one more than the maximum value
  7103. // representable in the result type, so never warn for those.
  7104. llvm::APSInt Left;
  7105. if (LHS.get()->isValueDependent() ||
  7106. LHSType->hasUnsignedIntegerRepresentation() ||
  7107. !LHS.get()->EvaluateAsInt(Left, S.Context))
  7108. return;
  7109. // If LHS does not have a signed type and non-negative value
  7110. // then, the behavior is undefined. Warn about it.
  7111. if (Left.isNegative()) {
  7112. S.DiagRuntimeBehavior(Loc, LHS.get(),
  7113. S.PDiag(diag::warn_shift_lhs_negative)
  7114. << LHS.get()->getSourceRange());
  7115. return;
  7116. }
  7117. llvm::APInt ResultBits =
  7118. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  7119. if (LeftBits.uge(ResultBits))
  7120. return;
  7121. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  7122. Result = Result.shl(Right);
  7123. // Print the bit representation of the signed integer as an unsigned
  7124. // hexadecimal number.
  7125. SmallString<40> HexResult;
  7126. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  7127. // If we are only missing a sign bit, this is less likely to result in actual
  7128. // bugs -- if the result is cast back to an unsigned type, it will have the
  7129. // expected value. Thus we place this behind a different warning that can be
  7130. // turned off separately if needed.
  7131. if (LeftBits == ResultBits - 1) {
  7132. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  7133. << HexResult << LHSType
  7134. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7135. return;
  7136. }
  7137. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  7138. << HexResult.str() << Result.getMinSignedBits() << LHSType
  7139. << Left.getBitWidth() << LHS.get()->getSourceRange()
  7140. << RHS.get()->getSourceRange();
  7141. }
  7142. /// \brief Return the resulting type when an OpenCL vector is shifted
  7143. /// by a scalar or vector shift amount.
  7144. static QualType checkOpenCLVectorShift(Sema &S,
  7145. ExprResult &LHS, ExprResult &RHS,
  7146. SourceLocation Loc, bool IsCompAssign) {
  7147. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  7148. if (!LHS.get()->getType()->isVectorType()) {
  7149. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  7150. << RHS.get()->getType() << LHS.get()->getType()
  7151. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7152. return QualType();
  7153. }
  7154. if (!IsCompAssign) {
  7155. LHS = S.UsualUnaryConversions(LHS.get());
  7156. if (LHS.isInvalid()) return QualType();
  7157. }
  7158. RHS = S.UsualUnaryConversions(RHS.get());
  7159. if (RHS.isInvalid()) return QualType();
  7160. QualType LHSType = LHS.get()->getType();
  7161. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  7162. QualType LHSEleType = LHSVecTy->getElementType();
  7163. // Note that RHS might not be a vector.
  7164. QualType RHSType = RHS.get()->getType();
  7165. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  7166. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  7167. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  7168. if (!LHSEleType->isIntegerType()) {
  7169. S.Diag(Loc, diag::err_typecheck_expect_int)
  7170. << LHS.get()->getType() << LHS.get()->getSourceRange();
  7171. return QualType();
  7172. }
  7173. if (!RHSEleType->isIntegerType()) {
  7174. S.Diag(Loc, diag::err_typecheck_expect_int)
  7175. << RHS.get()->getType() << RHS.get()->getSourceRange();
  7176. return QualType();
  7177. }
  7178. if (RHSVecTy) {
  7179. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  7180. // are applied component-wise. So if RHS is a vector, then ensure
  7181. // that the number of elements is the same as LHS...
  7182. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  7183. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  7184. << LHS.get()->getType() << RHS.get()->getType()
  7185. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7186. return QualType();
  7187. }
  7188. } else {
  7189. // ...else expand RHS to match the number of elements in LHS.
  7190. QualType VecTy =
  7191. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  7192. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  7193. }
  7194. return LHSType;
  7195. }
  7196. // C99 6.5.7
  7197. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  7198. SourceLocation Loc, BinaryOperatorKind Opc,
  7199. bool IsCompAssign) {
  7200. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7201. // Vector shifts promote their scalar inputs to vector type.
  7202. if (LHS.get()->getType()->isVectorType() ||
  7203. RHS.get()->getType()->isVectorType()) {
  7204. if (LangOpts.OpenCL)
  7205. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7206. if (LangOpts.ZVector) {
  7207. // The shift operators for the z vector extensions work basically
  7208. // like OpenCL shifts, except that neither the LHS nor the RHS is
  7209. // allowed to be a "vector bool".
  7210. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  7211. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7212. return InvalidOperands(Loc, LHS, RHS);
  7213. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  7214. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7215. return InvalidOperands(Loc, LHS, RHS);
  7216. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7217. }
  7218. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7219. /*AllowBothBool*/true,
  7220. /*AllowBoolConversions*/false);
  7221. }
  7222. // Shifts don't perform usual arithmetic conversions, they just do integer
  7223. // promotions on each operand. C99 6.5.7p3
  7224. // For the LHS, do usual unary conversions, but then reset them away
  7225. // if this is a compound assignment.
  7226. ExprResult OldLHS = LHS;
  7227. LHS = UsualUnaryConversions(LHS.get());
  7228. if (LHS.isInvalid())
  7229. return QualType();
  7230. QualType LHSType = LHS.get()->getType();
  7231. if (IsCompAssign) LHS = OldLHS;
  7232. // The RHS is simpler.
  7233. RHS = UsualUnaryConversions(RHS.get());
  7234. if (RHS.isInvalid())
  7235. return QualType();
  7236. QualType RHSType = RHS.get()->getType();
  7237. // C99 6.5.7p2: Each of the operands shall have integer type.
  7238. if (!LHSType->hasIntegerRepresentation() ||
  7239. !RHSType->hasIntegerRepresentation())
  7240. return InvalidOperands(Loc, LHS, RHS);
  7241. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  7242. // hasIntegerRepresentation() above instead of this.
  7243. if (isScopedEnumerationType(LHSType) ||
  7244. isScopedEnumerationType(RHSType)) {
  7245. return InvalidOperands(Loc, LHS, RHS);
  7246. }
  7247. // Sanity-check shift operands
  7248. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  7249. // "The type of the result is that of the promoted left operand."
  7250. return LHSType;
  7251. }
  7252. static bool IsWithinTemplateSpecialization(Decl *D) {
  7253. if (DeclContext *DC = D->getDeclContext()) {
  7254. if (isa<ClassTemplateSpecializationDecl>(DC))
  7255. return true;
  7256. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  7257. return FD->isFunctionTemplateSpecialization();
  7258. }
  7259. return false;
  7260. }
  7261. /// If two different enums are compared, raise a warning.
  7262. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  7263. Expr *RHS) {
  7264. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  7265. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  7266. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  7267. if (!LHSEnumType)
  7268. return;
  7269. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  7270. if (!RHSEnumType)
  7271. return;
  7272. // Ignore anonymous enums.
  7273. if (!LHSEnumType->getDecl()->getIdentifier())
  7274. return;
  7275. if (!RHSEnumType->getDecl()->getIdentifier())
  7276. return;
  7277. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  7278. return;
  7279. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  7280. << LHSStrippedType << RHSStrippedType
  7281. << LHS->getSourceRange() << RHS->getSourceRange();
  7282. }
  7283. /// \brief Diagnose bad pointer comparisons.
  7284. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  7285. ExprResult &LHS, ExprResult &RHS,
  7286. bool IsError) {
  7287. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  7288. : diag::ext_typecheck_comparison_of_distinct_pointers)
  7289. << LHS.get()->getType() << RHS.get()->getType()
  7290. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7291. }
  7292. /// \brief Returns false if the pointers are converted to a composite type,
  7293. /// true otherwise.
  7294. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  7295. ExprResult &LHS, ExprResult &RHS) {
  7296. // C++ [expr.rel]p2:
  7297. // [...] Pointer conversions (4.10) and qualification
  7298. // conversions (4.4) are performed on pointer operands (or on
  7299. // a pointer operand and a null pointer constant) to bring
  7300. // them to their composite pointer type. [...]
  7301. //
  7302. // C++ [expr.eq]p1 uses the same notion for (in)equality
  7303. // comparisons of pointers.
  7304. // C++ [expr.eq]p2:
  7305. // In addition, pointers to members can be compared, or a pointer to
  7306. // member and a null pointer constant. Pointer to member conversions
  7307. // (4.11) and qualification conversions (4.4) are performed to bring
  7308. // them to a common type. If one operand is a null pointer constant,
  7309. // the common type is the type of the other operand. Otherwise, the
  7310. // common type is a pointer to member type similar (4.4) to the type
  7311. // of one of the operands, with a cv-qualification signature (4.4)
  7312. // that is the union of the cv-qualification signatures of the operand
  7313. // types.
  7314. QualType LHSType = LHS.get()->getType();
  7315. QualType RHSType = RHS.get()->getType();
  7316. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  7317. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  7318. bool NonStandardCompositeType = false;
  7319. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  7320. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  7321. if (T.isNull()) {
  7322. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  7323. return true;
  7324. }
  7325. if (NonStandardCompositeType)
  7326. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  7327. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  7328. << RHS.get()->getSourceRange();
  7329. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  7330. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  7331. return false;
  7332. }
  7333. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  7334. ExprResult &LHS,
  7335. ExprResult &RHS,
  7336. bool IsError) {
  7337. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  7338. : diag::ext_typecheck_comparison_of_fptr_to_void)
  7339. << LHS.get()->getType() << RHS.get()->getType()
  7340. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7341. }
  7342. static bool isObjCObjectLiteral(ExprResult &E) {
  7343. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  7344. case Stmt::ObjCArrayLiteralClass:
  7345. case Stmt::ObjCDictionaryLiteralClass:
  7346. case Stmt::ObjCStringLiteralClass:
  7347. case Stmt::ObjCBoxedExprClass:
  7348. return true;
  7349. default:
  7350. // Note that ObjCBoolLiteral is NOT an object literal!
  7351. return false;
  7352. }
  7353. }
  7354. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  7355. const ObjCObjectPointerType *Type =
  7356. LHS->getType()->getAs<ObjCObjectPointerType>();
  7357. // If this is not actually an Objective-C object, bail out.
  7358. if (!Type)
  7359. return false;
  7360. // Get the LHS object's interface type.
  7361. QualType InterfaceType = Type->getPointeeType();
  7362. // If the RHS isn't an Objective-C object, bail out.
  7363. if (!RHS->getType()->isObjCObjectPointerType())
  7364. return false;
  7365. // Try to find the -isEqual: method.
  7366. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  7367. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  7368. InterfaceType,
  7369. /*instance=*/true);
  7370. if (!Method) {
  7371. if (Type->isObjCIdType()) {
  7372. // For 'id', just check the global pool.
  7373. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7374. /*receiverId=*/true);
  7375. } else {
  7376. // Check protocols.
  7377. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7378. /*instance=*/true);
  7379. }
  7380. }
  7381. if (!Method)
  7382. return false;
  7383. QualType T = Method->parameters()[0]->getType();
  7384. if (!T->isObjCObjectPointerType())
  7385. return false;
  7386. QualType R = Method->getReturnType();
  7387. if (!R->isScalarType())
  7388. return false;
  7389. return true;
  7390. }
  7391. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7392. FromE = FromE->IgnoreParenImpCasts();
  7393. switch (FromE->getStmtClass()) {
  7394. default:
  7395. break;
  7396. case Stmt::ObjCStringLiteralClass:
  7397. // "string literal"
  7398. return LK_String;
  7399. case Stmt::ObjCArrayLiteralClass:
  7400. // "array literal"
  7401. return LK_Array;
  7402. case Stmt::ObjCDictionaryLiteralClass:
  7403. // "dictionary literal"
  7404. return LK_Dictionary;
  7405. case Stmt::BlockExprClass:
  7406. return LK_Block;
  7407. case Stmt::ObjCBoxedExprClass: {
  7408. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7409. switch (Inner->getStmtClass()) {
  7410. case Stmt::IntegerLiteralClass:
  7411. case Stmt::FloatingLiteralClass:
  7412. case Stmt::CharacterLiteralClass:
  7413. case Stmt::ObjCBoolLiteralExprClass:
  7414. case Stmt::CXXBoolLiteralExprClass:
  7415. // "numeric literal"
  7416. return LK_Numeric;
  7417. case Stmt::ImplicitCastExprClass: {
  7418. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7419. // Boolean literals can be represented by implicit casts.
  7420. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7421. return LK_Numeric;
  7422. break;
  7423. }
  7424. default:
  7425. break;
  7426. }
  7427. return LK_Boxed;
  7428. }
  7429. }
  7430. return LK_None;
  7431. }
  7432. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7433. ExprResult &LHS, ExprResult &RHS,
  7434. BinaryOperator::Opcode Opc){
  7435. Expr *Literal;
  7436. Expr *Other;
  7437. if (isObjCObjectLiteral(LHS)) {
  7438. Literal = LHS.get();
  7439. Other = RHS.get();
  7440. } else {
  7441. Literal = RHS.get();
  7442. Other = LHS.get();
  7443. }
  7444. // Don't warn on comparisons against nil.
  7445. Other = Other->IgnoreParenCasts();
  7446. if (Other->isNullPointerConstant(S.getASTContext(),
  7447. Expr::NPC_ValueDependentIsNotNull))
  7448. return;
  7449. // This should be kept in sync with warn_objc_literal_comparison.
  7450. // LK_String should always be after the other literals, since it has its own
  7451. // warning flag.
  7452. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7453. assert(LiteralKind != Sema::LK_Block);
  7454. if (LiteralKind == Sema::LK_None) {
  7455. llvm_unreachable("Unknown Objective-C object literal kind");
  7456. }
  7457. if (LiteralKind == Sema::LK_String)
  7458. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7459. << Literal->getSourceRange();
  7460. else
  7461. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7462. << LiteralKind << Literal->getSourceRange();
  7463. if (BinaryOperator::isEqualityOp(Opc) &&
  7464. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7465. SourceLocation Start = LHS.get()->getLocStart();
  7466. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
  7467. CharSourceRange OpRange =
  7468. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  7469. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7470. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7471. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7472. << FixItHint::CreateInsertion(End, "]");
  7473. }
  7474. }
  7475. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7476. ExprResult &RHS,
  7477. SourceLocation Loc,
  7478. BinaryOperatorKind Opc) {
  7479. // Check that left hand side is !something.
  7480. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7481. if (!UO || UO->getOpcode() != UO_LNot) return;
  7482. // Only check if the right hand side is non-bool arithmetic type.
  7483. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  7484. // Make sure that the something in !something is not bool.
  7485. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7486. if (SubExpr->isKnownToHaveBooleanValue()) return;
  7487. // Emit warning.
  7488. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7489. << Loc;
  7490. // First note suggest !(x < y)
  7491. SourceLocation FirstOpen = SubExpr->getLocStart();
  7492. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7493. FirstClose = S.getLocForEndOfToken(FirstClose);
  7494. if (FirstClose.isInvalid())
  7495. FirstOpen = SourceLocation();
  7496. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7497. << FixItHint::CreateInsertion(FirstOpen, "(")
  7498. << FixItHint::CreateInsertion(FirstClose, ")");
  7499. // Second note suggests (!x) < y
  7500. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7501. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7502. SecondClose = S.getLocForEndOfToken(SecondClose);
  7503. if (SecondClose.isInvalid())
  7504. SecondOpen = SourceLocation();
  7505. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7506. << FixItHint::CreateInsertion(SecondOpen, "(")
  7507. << FixItHint::CreateInsertion(SecondClose, ")");
  7508. }
  7509. // Get the decl for a simple expression: a reference to a variable,
  7510. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7511. static ValueDecl *getCompareDecl(Expr *E) {
  7512. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7513. return DR->getDecl();
  7514. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7515. if (Ivar->isFreeIvar())
  7516. return Ivar->getDecl();
  7517. }
  7518. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7519. if (Mem->isImplicitAccess())
  7520. return Mem->getMemberDecl();
  7521. }
  7522. return nullptr;
  7523. }
  7524. // C99 6.5.8, C++ [expr.rel]
  7525. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7526. SourceLocation Loc, BinaryOperatorKind Opc,
  7527. bool IsRelational) {
  7528. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7529. // Handle vector comparisons separately.
  7530. if (LHS.get()->getType()->isVectorType() ||
  7531. RHS.get()->getType()->isVectorType())
  7532. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7533. QualType LHSType = LHS.get()->getType();
  7534. QualType RHSType = RHS.get()->getType();
  7535. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7536. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7537. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7538. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
  7539. if (!LHSType->hasFloatingRepresentation() &&
  7540. !(LHSType->isBlockPointerType() && IsRelational) &&
  7541. !LHS.get()->getLocStart().isMacroID() &&
  7542. !RHS.get()->getLocStart().isMacroID() &&
  7543. ActiveTemplateInstantiations.empty()) {
  7544. // For non-floating point types, check for self-comparisons of the form
  7545. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7546. // often indicate logic errors in the program.
  7547. //
  7548. // NOTE: Don't warn about comparison expressions resulting from macro
  7549. // expansion. Also don't warn about comparisons which are only self
  7550. // comparisons within a template specialization. The warnings should catch
  7551. // obvious cases in the definition of the template anyways. The idea is to
  7552. // warn when the typed comparison operator will always evaluate to the same
  7553. // result.
  7554. ValueDecl *DL = getCompareDecl(LHSStripped);
  7555. ValueDecl *DR = getCompareDecl(RHSStripped);
  7556. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7557. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7558. << 0 // self-
  7559. << (Opc == BO_EQ
  7560. || Opc == BO_LE
  7561. || Opc == BO_GE));
  7562. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7563. !DL->getType()->isReferenceType() &&
  7564. !DR->getType()->isReferenceType()) {
  7565. // what is it always going to eval to?
  7566. char always_evals_to;
  7567. switch(Opc) {
  7568. case BO_EQ: // e.g. array1 == array2
  7569. always_evals_to = 0; // false
  7570. break;
  7571. case BO_NE: // e.g. array1 != array2
  7572. always_evals_to = 1; // true
  7573. break;
  7574. default:
  7575. // best we can say is 'a constant'
  7576. always_evals_to = 2; // e.g. array1 <= array2
  7577. break;
  7578. }
  7579. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7580. << 1 // array
  7581. << always_evals_to);
  7582. }
  7583. if (isa<CastExpr>(LHSStripped))
  7584. LHSStripped = LHSStripped->IgnoreParenCasts();
  7585. if (isa<CastExpr>(RHSStripped))
  7586. RHSStripped = RHSStripped->IgnoreParenCasts();
  7587. // Warn about comparisons against a string constant (unless the other
  7588. // operand is null), the user probably wants strcmp.
  7589. Expr *literalString = nullptr;
  7590. Expr *literalStringStripped = nullptr;
  7591. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7592. !RHSStripped->isNullPointerConstant(Context,
  7593. Expr::NPC_ValueDependentIsNull)) {
  7594. literalString = LHS.get();
  7595. literalStringStripped = LHSStripped;
  7596. } else if ((isa<StringLiteral>(RHSStripped) ||
  7597. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7598. !LHSStripped->isNullPointerConstant(Context,
  7599. Expr::NPC_ValueDependentIsNull)) {
  7600. literalString = RHS.get();
  7601. literalStringStripped = RHSStripped;
  7602. }
  7603. if (literalString) {
  7604. DiagRuntimeBehavior(Loc, nullptr,
  7605. PDiag(diag::warn_stringcompare)
  7606. << isa<ObjCEncodeExpr>(literalStringStripped)
  7607. << literalString->getSourceRange());
  7608. }
  7609. }
  7610. // C99 6.5.8p3 / C99 6.5.9p4
  7611. UsualArithmeticConversions(LHS, RHS);
  7612. if (LHS.isInvalid() || RHS.isInvalid())
  7613. return QualType();
  7614. LHSType = LHS.get()->getType();
  7615. RHSType = RHS.get()->getType();
  7616. // The result of comparisons is 'bool' in C++, 'int' in C.
  7617. QualType ResultTy = Context.getLogicalOperationType();
  7618. if (IsRelational) {
  7619. if (LHSType->isRealType() && RHSType->isRealType())
  7620. return ResultTy;
  7621. } else {
  7622. // Check for comparisons of floating point operands using != and ==.
  7623. if (LHSType->hasFloatingRepresentation())
  7624. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7625. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7626. return ResultTy;
  7627. }
  7628. const Expr::NullPointerConstantKind LHSNullKind =
  7629. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7630. const Expr::NullPointerConstantKind RHSNullKind =
  7631. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7632. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7633. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7634. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7635. bool IsEquality = Opc == BO_EQ;
  7636. if (RHSIsNull)
  7637. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7638. RHS.get()->getSourceRange());
  7639. else
  7640. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7641. LHS.get()->getSourceRange());
  7642. }
  7643. // All of the following pointer-related warnings are GCC extensions, except
  7644. // when handling null pointer constants.
  7645. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7646. QualType LCanPointeeTy =
  7647. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7648. QualType RCanPointeeTy =
  7649. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7650. if (getLangOpts().CPlusPlus) {
  7651. if (LCanPointeeTy == RCanPointeeTy)
  7652. return ResultTy;
  7653. if (!IsRelational &&
  7654. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7655. // Valid unless comparison between non-null pointer and function pointer
  7656. // This is a gcc extension compatibility comparison.
  7657. // In a SFINAE context, we treat this as a hard error to maintain
  7658. // conformance with the C++ standard.
  7659. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7660. && !LHSIsNull && !RHSIsNull) {
  7661. diagnoseFunctionPointerToVoidComparison(
  7662. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7663. if (isSFINAEContext())
  7664. return QualType();
  7665. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7666. return ResultTy;
  7667. }
  7668. }
  7669. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7670. return QualType();
  7671. else
  7672. return ResultTy;
  7673. }
  7674. // C99 6.5.9p2 and C99 6.5.8p2
  7675. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7676. RCanPointeeTy.getUnqualifiedType())) {
  7677. // Valid unless a relational comparison of function pointers
  7678. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7679. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7680. << LHSType << RHSType << LHS.get()->getSourceRange()
  7681. << RHS.get()->getSourceRange();
  7682. }
  7683. } else if (!IsRelational &&
  7684. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7685. // Valid unless comparison between non-null pointer and function pointer
  7686. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7687. && !LHSIsNull && !RHSIsNull)
  7688. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7689. /*isError*/false);
  7690. } else {
  7691. // Invalid
  7692. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7693. }
  7694. if (LCanPointeeTy != RCanPointeeTy) {
  7695. // Treat NULL constant as a special case in OpenCL.
  7696. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  7697. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  7698. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7699. Diag(Loc,
  7700. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7701. << LHSType << RHSType << 0 /* comparison */
  7702. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7703. }
  7704. }
  7705. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7706. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7707. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7708. : CK_BitCast;
  7709. if (LHSIsNull && !RHSIsNull)
  7710. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7711. else
  7712. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7713. }
  7714. return ResultTy;
  7715. }
  7716. if (getLangOpts().CPlusPlus) {
  7717. // Comparison of nullptr_t with itself.
  7718. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7719. return ResultTy;
  7720. // Comparison of pointers with null pointer constants and equality
  7721. // comparisons of member pointers to null pointer constants.
  7722. if (RHSIsNull &&
  7723. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7724. (!IsRelational &&
  7725. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7726. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7727. LHSType->isMemberPointerType()
  7728. ? CK_NullToMemberPointer
  7729. : CK_NullToPointer);
  7730. return ResultTy;
  7731. }
  7732. if (LHSIsNull &&
  7733. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7734. (!IsRelational &&
  7735. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7736. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7737. RHSType->isMemberPointerType()
  7738. ? CK_NullToMemberPointer
  7739. : CK_NullToPointer);
  7740. return ResultTy;
  7741. }
  7742. // Comparison of member pointers.
  7743. if (!IsRelational &&
  7744. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7745. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7746. return QualType();
  7747. else
  7748. return ResultTy;
  7749. }
  7750. // Handle scoped enumeration types specifically, since they don't promote
  7751. // to integers.
  7752. if (LHS.get()->getType()->isEnumeralType() &&
  7753. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7754. RHS.get()->getType()))
  7755. return ResultTy;
  7756. }
  7757. // Handle block pointer types.
  7758. if (!IsRelational && LHSType->isBlockPointerType() &&
  7759. RHSType->isBlockPointerType()) {
  7760. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7761. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7762. if (!LHSIsNull && !RHSIsNull &&
  7763. !Context.typesAreCompatible(lpointee, rpointee)) {
  7764. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7765. << LHSType << RHSType << LHS.get()->getSourceRange()
  7766. << RHS.get()->getSourceRange();
  7767. }
  7768. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7769. return ResultTy;
  7770. }
  7771. // Allow block pointers to be compared with null pointer constants.
  7772. if (!IsRelational
  7773. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7774. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7775. if (!LHSIsNull && !RHSIsNull) {
  7776. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7777. ->getPointeeType()->isVoidType())
  7778. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7779. ->getPointeeType()->isVoidType())))
  7780. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7781. << LHSType << RHSType << LHS.get()->getSourceRange()
  7782. << RHS.get()->getSourceRange();
  7783. }
  7784. if (LHSIsNull && !RHSIsNull)
  7785. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7786. RHSType->isPointerType() ? CK_BitCast
  7787. : CK_AnyPointerToBlockPointerCast);
  7788. else
  7789. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7790. LHSType->isPointerType() ? CK_BitCast
  7791. : CK_AnyPointerToBlockPointerCast);
  7792. return ResultTy;
  7793. }
  7794. if (LHSType->isObjCObjectPointerType() ||
  7795. RHSType->isObjCObjectPointerType()) {
  7796. const PointerType *LPT = LHSType->getAs<PointerType>();
  7797. const PointerType *RPT = RHSType->getAs<PointerType>();
  7798. if (LPT || RPT) {
  7799. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7800. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7801. if (!LPtrToVoid && !RPtrToVoid &&
  7802. !Context.typesAreCompatible(LHSType, RHSType)) {
  7803. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7804. /*isError*/false);
  7805. }
  7806. if (LHSIsNull && !RHSIsNull) {
  7807. Expr *E = LHS.get();
  7808. if (getLangOpts().ObjCAutoRefCount)
  7809. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7810. LHS = ImpCastExprToType(E, RHSType,
  7811. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7812. }
  7813. else {
  7814. Expr *E = RHS.get();
  7815. if (getLangOpts().ObjCAutoRefCount)
  7816. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7817. Opc);
  7818. RHS = ImpCastExprToType(E, LHSType,
  7819. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7820. }
  7821. return ResultTy;
  7822. }
  7823. if (LHSType->isObjCObjectPointerType() &&
  7824. RHSType->isObjCObjectPointerType()) {
  7825. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7826. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7827. /*isError*/false);
  7828. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7829. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7830. if (LHSIsNull && !RHSIsNull)
  7831. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7832. else
  7833. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7834. return ResultTy;
  7835. }
  7836. }
  7837. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7838. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7839. unsigned DiagID = 0;
  7840. bool isError = false;
  7841. if (LangOpts.DebuggerSupport) {
  7842. // Under a debugger, allow the comparison of pointers to integers,
  7843. // since users tend to want to compare addresses.
  7844. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7845. (RHSIsNull && RHSType->isIntegerType())) {
  7846. if (IsRelational && !getLangOpts().CPlusPlus)
  7847. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7848. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7849. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7850. else if (getLangOpts().CPlusPlus) {
  7851. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7852. isError = true;
  7853. } else
  7854. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7855. if (DiagID) {
  7856. Diag(Loc, DiagID)
  7857. << LHSType << RHSType << LHS.get()->getSourceRange()
  7858. << RHS.get()->getSourceRange();
  7859. if (isError)
  7860. return QualType();
  7861. }
  7862. if (LHSType->isIntegerType())
  7863. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7864. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7865. else
  7866. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7867. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7868. return ResultTy;
  7869. }
  7870. // Handle block pointers.
  7871. if (!IsRelational && RHSIsNull
  7872. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7873. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7874. return ResultTy;
  7875. }
  7876. if (!IsRelational && LHSIsNull
  7877. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7878. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7879. return ResultTy;
  7880. }
  7881. return InvalidOperands(Loc, LHS, RHS);
  7882. }
  7883. // Return a signed type that is of identical size and number of elements.
  7884. // For floating point vectors, return an integer type of identical size
  7885. // and number of elements.
  7886. QualType Sema::GetSignedVectorType(QualType V) {
  7887. const VectorType *VTy = V->getAs<VectorType>();
  7888. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7889. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7890. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7891. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7892. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7893. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7894. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7895. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7896. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7897. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7898. "Unhandled vector element size in vector compare");
  7899. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7900. }
  7901. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7902. /// operates on extended vector types. Instead of producing an IntTy result,
  7903. /// like a scalar comparison, a vector comparison produces a vector of integer
  7904. /// types.
  7905. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7906. SourceLocation Loc,
  7907. bool IsRelational) {
  7908. // Check to make sure we're operating on vectors of the same type and width,
  7909. // Allowing one side to be a scalar of element type.
  7910. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  7911. /*AllowBothBool*/true,
  7912. /*AllowBoolConversions*/getLangOpts().ZVector);
  7913. if (vType.isNull())
  7914. return vType;
  7915. QualType LHSType = LHS.get()->getType();
  7916. // If AltiVec, the comparison results in a numeric type, i.e.
  7917. // bool for C++, int for C
  7918. if (getLangOpts().AltiVec &&
  7919. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7920. return Context.getLogicalOperationType();
  7921. // For non-floating point types, check for self-comparisons of the form
  7922. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7923. // often indicate logic errors in the program.
  7924. if (!LHSType->hasFloatingRepresentation() &&
  7925. ActiveTemplateInstantiations.empty()) {
  7926. if (DeclRefExpr* DRL
  7927. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7928. if (DeclRefExpr* DRR
  7929. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7930. if (DRL->getDecl() == DRR->getDecl())
  7931. DiagRuntimeBehavior(Loc, nullptr,
  7932. PDiag(diag::warn_comparison_always)
  7933. << 0 // self-
  7934. << 2 // "a constant"
  7935. );
  7936. }
  7937. // Check for comparisons of floating point operands using != and ==.
  7938. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7939. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7940. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7941. }
  7942. // Return a signed type for the vector.
  7943. return GetSignedVectorType(LHSType);
  7944. }
  7945. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7946. SourceLocation Loc) {
  7947. // Ensure that either both operands are of the same vector type, or
  7948. // one operand is of a vector type and the other is of its element type.
  7949. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  7950. /*AllowBothBool*/true,
  7951. /*AllowBoolConversions*/false);
  7952. if (vType.isNull())
  7953. return InvalidOperands(Loc, LHS, RHS);
  7954. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7955. vType->hasFloatingRepresentation())
  7956. return InvalidOperands(Loc, LHS, RHS);
  7957. return GetSignedVectorType(LHS.get()->getType());
  7958. }
  7959. inline QualType Sema::CheckBitwiseOperands(
  7960. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7961. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7962. if (LHS.get()->getType()->isVectorType() ||
  7963. RHS.get()->getType()->isVectorType()) {
  7964. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7965. RHS.get()->getType()->hasIntegerRepresentation())
  7966. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7967. /*AllowBothBool*/true,
  7968. /*AllowBoolConversions*/getLangOpts().ZVector);
  7969. return InvalidOperands(Loc, LHS, RHS);
  7970. }
  7971. ExprResult LHSResult = LHS, RHSResult = RHS;
  7972. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  7973. IsCompAssign);
  7974. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  7975. return QualType();
  7976. LHS = LHSResult.get();
  7977. RHS = RHSResult.get();
  7978. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  7979. return compType;
  7980. return InvalidOperands(Loc, LHS, RHS);
  7981. }
  7982. // C99 6.5.[13,14]
  7983. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7984. SourceLocation Loc,
  7985. BinaryOperatorKind Opc) {
  7986. // Check vector operands differently.
  7987. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  7988. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  7989. // Diagnose cases where the user write a logical and/or but probably meant a
  7990. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  7991. // is a constant.
  7992. if (LHS.get()->getType()->isIntegerType() &&
  7993. !LHS.get()->getType()->isBooleanType() &&
  7994. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  7995. // Don't warn in macros or template instantiations.
  7996. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  7997. // If the RHS can be constant folded, and if it constant folds to something
  7998. // that isn't 0 or 1 (which indicate a potential logical operation that
  7999. // happened to fold to true/false) then warn.
  8000. // Parens on the RHS are ignored.
  8001. llvm::APSInt Result;
  8002. if (RHS.get()->EvaluateAsInt(Result, Context))
  8003. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  8004. !RHS.get()->getExprLoc().isMacroID()) ||
  8005. (Result != 0 && Result != 1)) {
  8006. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  8007. << RHS.get()->getSourceRange()
  8008. << (Opc == BO_LAnd ? "&&" : "||");
  8009. // Suggest replacing the logical operator with the bitwise version
  8010. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  8011. << (Opc == BO_LAnd ? "&" : "|")
  8012. << FixItHint::CreateReplacement(SourceRange(
  8013. Loc, getLocForEndOfToken(Loc)),
  8014. Opc == BO_LAnd ? "&" : "|");
  8015. if (Opc == BO_LAnd)
  8016. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  8017. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  8018. << FixItHint::CreateRemoval(
  8019. SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
  8020. RHS.get()->getLocEnd()));
  8021. }
  8022. }
  8023. if (!Context.getLangOpts().CPlusPlus) {
  8024. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  8025. // not operate on the built-in scalar and vector float types.
  8026. if (Context.getLangOpts().OpenCL &&
  8027. Context.getLangOpts().OpenCLVersion < 120) {
  8028. if (LHS.get()->getType()->isFloatingType() ||
  8029. RHS.get()->getType()->isFloatingType())
  8030. return InvalidOperands(Loc, LHS, RHS);
  8031. }
  8032. LHS = UsualUnaryConversions(LHS.get());
  8033. if (LHS.isInvalid())
  8034. return QualType();
  8035. RHS = UsualUnaryConversions(RHS.get());
  8036. if (RHS.isInvalid())
  8037. return QualType();
  8038. if (!LHS.get()->getType()->isScalarType() ||
  8039. !RHS.get()->getType()->isScalarType())
  8040. return InvalidOperands(Loc, LHS, RHS);
  8041. return Context.IntTy;
  8042. }
  8043. // The following is safe because we only use this method for
  8044. // non-overloadable operands.
  8045. // C++ [expr.log.and]p1
  8046. // C++ [expr.log.or]p1
  8047. // The operands are both contextually converted to type bool.
  8048. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  8049. if (LHSRes.isInvalid())
  8050. return InvalidOperands(Loc, LHS, RHS);
  8051. LHS = LHSRes;
  8052. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  8053. if (RHSRes.isInvalid())
  8054. return InvalidOperands(Loc, LHS, RHS);
  8055. RHS = RHSRes;
  8056. // C++ [expr.log.and]p2
  8057. // C++ [expr.log.or]p2
  8058. // The result is a bool.
  8059. return Context.BoolTy;
  8060. }
  8061. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  8062. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  8063. if (!ME) return false;
  8064. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  8065. ObjCMessageExpr *Base =
  8066. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  8067. if (!Base) return false;
  8068. return Base->getMethodDecl() != nullptr;
  8069. }
  8070. /// Is the given expression (which must be 'const') a reference to a
  8071. /// variable which was originally non-const, but which has become
  8072. /// 'const' due to being captured within a block?
  8073. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  8074. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  8075. assert(E->isLValue() && E->getType().isConstQualified());
  8076. E = E->IgnoreParens();
  8077. // Must be a reference to a declaration from an enclosing scope.
  8078. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  8079. if (!DRE) return NCCK_None;
  8080. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  8081. // The declaration must be a variable which is not declared 'const'.
  8082. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  8083. if (!var) return NCCK_None;
  8084. if (var->getType().isConstQualified()) return NCCK_None;
  8085. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  8086. // Decide whether the first capture was for a block or a lambda.
  8087. DeclContext *DC = S.CurContext, *Prev = nullptr;
  8088. while (DC != var->getDeclContext()) {
  8089. Prev = DC;
  8090. DC = DC->getParent();
  8091. }
  8092. // Unless we have an init-capture, we've gone one step too far.
  8093. if (!var->isInitCapture())
  8094. DC = Prev;
  8095. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  8096. }
  8097. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  8098. Ty = Ty.getNonReferenceType();
  8099. if (IsDereference && Ty->isPointerType())
  8100. Ty = Ty->getPointeeType();
  8101. return !Ty.isConstQualified();
  8102. }
  8103. /// Emit the "read-only variable not assignable" error and print notes to give
  8104. /// more information about why the variable is not assignable, such as pointing
  8105. /// to the declaration of a const variable, showing that a method is const, or
  8106. /// that the function is returning a const reference.
  8107. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  8108. SourceLocation Loc) {
  8109. // Update err_typecheck_assign_const and note_typecheck_assign_const
  8110. // when this enum is changed.
  8111. enum {
  8112. ConstFunction,
  8113. ConstVariable,
  8114. ConstMember,
  8115. ConstMethod,
  8116. ConstUnknown, // Keep as last element
  8117. };
  8118. SourceRange ExprRange = E->getSourceRange();
  8119. // Only emit one error on the first const found. All other consts will emit
  8120. // a note to the error.
  8121. bool DiagnosticEmitted = false;
  8122. // Track if the current expression is the result of a derefence, and if the
  8123. // next checked expression is the result of a derefence.
  8124. bool IsDereference = false;
  8125. bool NextIsDereference = false;
  8126. // Loop to process MemberExpr chains.
  8127. while (true) {
  8128. IsDereference = NextIsDereference;
  8129. NextIsDereference = false;
  8130. E = E->IgnoreParenImpCasts();
  8131. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  8132. NextIsDereference = ME->isArrow();
  8133. const ValueDecl *VD = ME->getMemberDecl();
  8134. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  8135. // Mutable fields can be modified even if the class is const.
  8136. if (Field->isMutable()) {
  8137. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  8138. break;
  8139. }
  8140. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  8141. if (!DiagnosticEmitted) {
  8142. S.Diag(Loc, diag::err_typecheck_assign_const)
  8143. << ExprRange << ConstMember << false /*static*/ << Field
  8144. << Field->getType();
  8145. DiagnosticEmitted = true;
  8146. }
  8147. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8148. << ConstMember << false /*static*/ << Field << Field->getType()
  8149. << Field->getSourceRange();
  8150. }
  8151. E = ME->getBase();
  8152. continue;
  8153. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  8154. if (VDecl->getType().isConstQualified()) {
  8155. if (!DiagnosticEmitted) {
  8156. S.Diag(Loc, diag::err_typecheck_assign_const)
  8157. << ExprRange << ConstMember << true /*static*/ << VDecl
  8158. << VDecl->getType();
  8159. DiagnosticEmitted = true;
  8160. }
  8161. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8162. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  8163. << VDecl->getSourceRange();
  8164. }
  8165. // Static fields do not inherit constness from parents.
  8166. break;
  8167. }
  8168. break;
  8169. } // End MemberExpr
  8170. break;
  8171. }
  8172. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8173. // Function calls
  8174. const FunctionDecl *FD = CE->getDirectCallee();
  8175. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  8176. if (!DiagnosticEmitted) {
  8177. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8178. << ConstFunction << FD;
  8179. DiagnosticEmitted = true;
  8180. }
  8181. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  8182. diag::note_typecheck_assign_const)
  8183. << ConstFunction << FD << FD->getReturnType()
  8184. << FD->getReturnTypeSourceRange();
  8185. }
  8186. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8187. // Point to variable declaration.
  8188. if (const ValueDecl *VD = DRE->getDecl()) {
  8189. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  8190. if (!DiagnosticEmitted) {
  8191. S.Diag(Loc, diag::err_typecheck_assign_const)
  8192. << ExprRange << ConstVariable << VD << VD->getType();
  8193. DiagnosticEmitted = true;
  8194. }
  8195. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8196. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  8197. }
  8198. }
  8199. } else if (isa<CXXThisExpr>(E)) {
  8200. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  8201. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  8202. if (MD->isConst()) {
  8203. if (!DiagnosticEmitted) {
  8204. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8205. << ConstMethod << MD;
  8206. DiagnosticEmitted = true;
  8207. }
  8208. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  8209. << ConstMethod << MD << MD->getSourceRange();
  8210. }
  8211. }
  8212. }
  8213. }
  8214. if (DiagnosticEmitted)
  8215. return;
  8216. // Can't determine a more specific message, so display the generic error.
  8217. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  8218. }
  8219. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  8220. /// emit an error and return true. If so, return false.
  8221. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  8222. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  8223. SourceLocation OrigLoc = Loc;
  8224. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  8225. &Loc);
  8226. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  8227. IsLV = Expr::MLV_InvalidMessageExpression;
  8228. if (IsLV == Expr::MLV_Valid)
  8229. return false;
  8230. unsigned DiagID = 0;
  8231. bool NeedType = false;
  8232. switch (IsLV) { // C99 6.5.16p2
  8233. case Expr::MLV_ConstQualified:
  8234. // Use a specialized diagnostic when we're assigning to an object
  8235. // from an enclosing function or block.
  8236. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  8237. if (NCCK == NCCK_Block)
  8238. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  8239. else
  8240. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  8241. break;
  8242. }
  8243. // In ARC, use some specialized diagnostics for occasions where we
  8244. // infer 'const'. These are always pseudo-strong variables.
  8245. if (S.getLangOpts().ObjCAutoRefCount) {
  8246. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  8247. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  8248. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  8249. // Use the normal diagnostic if it's pseudo-__strong but the
  8250. // user actually wrote 'const'.
  8251. if (var->isARCPseudoStrong() &&
  8252. (!var->getTypeSourceInfo() ||
  8253. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  8254. // There are two pseudo-strong cases:
  8255. // - self
  8256. ObjCMethodDecl *method = S.getCurMethodDecl();
  8257. if (method && var == method->getSelfDecl())
  8258. DiagID = method->isClassMethod()
  8259. ? diag::err_typecheck_arc_assign_self_class_method
  8260. : diag::err_typecheck_arc_assign_self;
  8261. // - fast enumeration variables
  8262. else
  8263. DiagID = diag::err_typecheck_arr_assign_enumeration;
  8264. SourceRange Assign;
  8265. if (Loc != OrigLoc)
  8266. Assign = SourceRange(OrigLoc, OrigLoc);
  8267. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8268. // We need to preserve the AST regardless, so migration tool
  8269. // can do its job.
  8270. return false;
  8271. }
  8272. }
  8273. }
  8274. // If none of the special cases above are triggered, then this is a
  8275. // simple const assignment.
  8276. if (DiagID == 0) {
  8277. DiagnoseConstAssignment(S, E, Loc);
  8278. return true;
  8279. }
  8280. break;
  8281. case Expr::MLV_ConstAddrSpace:
  8282. DiagnoseConstAssignment(S, E, Loc);
  8283. return true;
  8284. case Expr::MLV_ArrayType:
  8285. case Expr::MLV_ArrayTemporary:
  8286. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  8287. NeedType = true;
  8288. break;
  8289. case Expr::MLV_NotObjectType:
  8290. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  8291. NeedType = true;
  8292. break;
  8293. case Expr::MLV_LValueCast:
  8294. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  8295. break;
  8296. case Expr::MLV_Valid:
  8297. llvm_unreachable("did not take early return for MLV_Valid");
  8298. case Expr::MLV_InvalidExpression:
  8299. case Expr::MLV_MemberFunction:
  8300. case Expr::MLV_ClassTemporary:
  8301. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  8302. break;
  8303. case Expr::MLV_IncompleteType:
  8304. case Expr::MLV_IncompleteVoidType:
  8305. return S.RequireCompleteType(Loc, E->getType(),
  8306. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  8307. case Expr::MLV_DuplicateVectorComponents:
  8308. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  8309. break;
  8310. case Expr::MLV_NoSetterProperty:
  8311. llvm_unreachable("readonly properties should be processed differently");
  8312. case Expr::MLV_InvalidMessageExpression:
  8313. DiagID = diag::error_readonly_message_assignment;
  8314. break;
  8315. case Expr::MLV_SubObjCPropertySetting:
  8316. DiagID = diag::error_no_subobject_property_setting;
  8317. break;
  8318. }
  8319. SourceRange Assign;
  8320. if (Loc != OrigLoc)
  8321. Assign = SourceRange(OrigLoc, OrigLoc);
  8322. if (NeedType)
  8323. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  8324. else
  8325. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8326. return true;
  8327. }
  8328. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  8329. SourceLocation Loc,
  8330. Sema &Sema) {
  8331. // C / C++ fields
  8332. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  8333. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  8334. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  8335. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  8336. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  8337. }
  8338. // Objective-C instance variables
  8339. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  8340. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  8341. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  8342. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  8343. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  8344. if (RL && RR && RL->getDecl() == RR->getDecl())
  8345. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  8346. }
  8347. }
  8348. // C99 6.5.16.1
  8349. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  8350. SourceLocation Loc,
  8351. QualType CompoundType) {
  8352. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  8353. // Verify that LHS is a modifiable lvalue, and emit error if not.
  8354. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  8355. return QualType();
  8356. QualType LHSType = LHSExpr->getType();
  8357. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  8358. CompoundType;
  8359. AssignConvertType ConvTy;
  8360. if (CompoundType.isNull()) {
  8361. Expr *RHSCheck = RHS.get();
  8362. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  8363. QualType LHSTy(LHSType);
  8364. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  8365. if (RHS.isInvalid())
  8366. return QualType();
  8367. // Special case of NSObject attributes on c-style pointer types.
  8368. if (ConvTy == IncompatiblePointer &&
  8369. ((Context.isObjCNSObjectType(LHSType) &&
  8370. RHSType->isObjCObjectPointerType()) ||
  8371. (Context.isObjCNSObjectType(RHSType) &&
  8372. LHSType->isObjCObjectPointerType())))
  8373. ConvTy = Compatible;
  8374. if (ConvTy == Compatible &&
  8375. LHSType->isObjCObjectType())
  8376. Diag(Loc, diag::err_objc_object_assignment)
  8377. << LHSType;
  8378. // If the RHS is a unary plus or minus, check to see if they = and + are
  8379. // right next to each other. If so, the user may have typo'd "x =+ 4"
  8380. // instead of "x += 4".
  8381. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  8382. RHSCheck = ICE->getSubExpr();
  8383. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  8384. if ((UO->getOpcode() == UO_Plus ||
  8385. UO->getOpcode() == UO_Minus) &&
  8386. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  8387. // Only if the two operators are exactly adjacent.
  8388. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  8389. // And there is a space or other character before the subexpr of the
  8390. // unary +/-. We don't want to warn on "x=-1".
  8391. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  8392. UO->getSubExpr()->getLocStart().isFileID()) {
  8393. Diag(Loc, diag::warn_not_compound_assign)
  8394. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  8395. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  8396. }
  8397. }
  8398. if (ConvTy == Compatible) {
  8399. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  8400. // Warn about retain cycles where a block captures the LHS, but
  8401. // not if the LHS is a simple variable into which the block is
  8402. // being stored...unless that variable can be captured by reference!
  8403. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  8404. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  8405. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  8406. checkRetainCycles(LHSExpr, RHS.get());
  8407. // It is safe to assign a weak reference into a strong variable.
  8408. // Although this code can still have problems:
  8409. // id x = self.weakProp;
  8410. // id y = self.weakProp;
  8411. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8412. // paths through the function. This should be revisited if
  8413. // -Wrepeated-use-of-weak is made flow-sensitive.
  8414. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8415. RHS.get()->getLocStart()))
  8416. getCurFunction()->markSafeWeakUse(RHS.get());
  8417. } else if (getLangOpts().ObjCAutoRefCount) {
  8418. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  8419. }
  8420. }
  8421. } else {
  8422. // Compound assignment "x += y"
  8423. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  8424. }
  8425. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  8426. RHS.get(), AA_Assigning))
  8427. return QualType();
  8428. CheckForNullPointerDereference(*this, LHSExpr);
  8429. // C99 6.5.16p3: The type of an assignment expression is the type of the
  8430. // left operand unless the left operand has qualified type, in which case
  8431. // it is the unqualified version of the type of the left operand.
  8432. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  8433. // is converted to the type of the assignment expression (above).
  8434. // C++ 5.17p1: the type of the assignment expression is that of its left
  8435. // operand.
  8436. return (getLangOpts().CPlusPlus
  8437. ? LHSType : LHSType.getUnqualifiedType());
  8438. }
  8439. // C99 6.5.17
  8440. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8441. SourceLocation Loc) {
  8442. LHS = S.CheckPlaceholderExpr(LHS.get());
  8443. RHS = S.CheckPlaceholderExpr(RHS.get());
  8444. if (LHS.isInvalid() || RHS.isInvalid())
  8445. return QualType();
  8446. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  8447. // operands, but not unary promotions.
  8448. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  8449. // So we treat the LHS as a ignored value, and in C++ we allow the
  8450. // containing site to determine what should be done with the RHS.
  8451. LHS = S.IgnoredValueConversions(LHS.get());
  8452. if (LHS.isInvalid())
  8453. return QualType();
  8454. S.DiagnoseUnusedExprResult(LHS.get());
  8455. if (!S.getLangOpts().CPlusPlus) {
  8456. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  8457. if (RHS.isInvalid())
  8458. return QualType();
  8459. if (!RHS.get()->getType()->isVoidType())
  8460. S.RequireCompleteType(Loc, RHS.get()->getType(),
  8461. diag::err_incomplete_type);
  8462. }
  8463. return RHS.get()->getType();
  8464. }
  8465. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  8466. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  8467. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  8468. ExprValueKind &VK,
  8469. ExprObjectKind &OK,
  8470. SourceLocation OpLoc,
  8471. bool IsInc, bool IsPrefix) {
  8472. if (Op->isTypeDependent())
  8473. return S.Context.DependentTy;
  8474. QualType ResType = Op->getType();
  8475. // Atomic types can be used for increment / decrement where the non-atomic
  8476. // versions can, so ignore the _Atomic() specifier for the purpose of
  8477. // checking.
  8478. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8479. ResType = ResAtomicType->getValueType();
  8480. assert(!ResType.isNull() && "no type for increment/decrement expression");
  8481. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  8482. // Decrement of bool is not allowed.
  8483. if (!IsInc) {
  8484. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  8485. return QualType();
  8486. }
  8487. // Increment of bool sets it to true, but is deprecated.
  8488. S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
  8489. : diag::warn_increment_bool)
  8490. << Op->getSourceRange();
  8491. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  8492. // Error on enum increments and decrements in C++ mode
  8493. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  8494. return QualType();
  8495. } else if (ResType->isRealType()) {
  8496. // OK!
  8497. } else if (ResType->isPointerType()) {
  8498. // C99 6.5.2.4p2, 6.5.6p2
  8499. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  8500. return QualType();
  8501. } else if (ResType->isObjCObjectPointerType()) {
  8502. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  8503. // Otherwise, we just need a complete type.
  8504. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  8505. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  8506. return QualType();
  8507. } else if (ResType->isAnyComplexType()) {
  8508. // C99 does not support ++/-- on complex types, we allow as an extension.
  8509. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8510. << ResType << Op->getSourceRange();
  8511. } else if (ResType->isPlaceholderType()) {
  8512. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8513. if (PR.isInvalid()) return QualType();
  8514. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8515. IsInc, IsPrefix);
  8516. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8517. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8518. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  8519. (ResType->getAs<VectorType>()->getVectorKind() !=
  8520. VectorType::AltiVecBool)) {
  8521. // The z vector extensions allow ++ and -- for non-bool vectors.
  8522. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8523. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8524. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8525. } else {
  8526. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8527. << ResType << int(IsInc) << Op->getSourceRange();
  8528. return QualType();
  8529. }
  8530. // At this point, we know we have a real, complex or pointer type.
  8531. // Now make sure the operand is a modifiable lvalue.
  8532. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8533. return QualType();
  8534. // In C++, a prefix increment is the same type as the operand. Otherwise
  8535. // (in C or with postfix), the increment is the unqualified type of the
  8536. // operand.
  8537. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8538. VK = VK_LValue;
  8539. OK = Op->getObjectKind();
  8540. return ResType;
  8541. } else {
  8542. VK = VK_RValue;
  8543. return ResType.getUnqualifiedType();
  8544. }
  8545. }
  8546. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8547. /// This routine allows us to typecheck complex/recursive expressions
  8548. /// where the declaration is needed for type checking. We only need to
  8549. /// handle cases when the expression references a function designator
  8550. /// or is an lvalue. Here are some examples:
  8551. /// - &(x) => x
  8552. /// - &*****f => f for f a function designator.
  8553. /// - &s.xx => s
  8554. /// - &s.zz[1].yy -> s, if zz is an array
  8555. /// - *(x + 1) -> x, if x is an array
  8556. /// - &"123"[2] -> 0
  8557. /// - & __real__ x -> x
  8558. static ValueDecl *getPrimaryDecl(Expr *E) {
  8559. switch (E->getStmtClass()) {
  8560. case Stmt::DeclRefExprClass:
  8561. return cast<DeclRefExpr>(E)->getDecl();
  8562. case Stmt::MemberExprClass:
  8563. // If this is an arrow operator, the address is an offset from
  8564. // the base's value, so the object the base refers to is
  8565. // irrelevant.
  8566. if (cast<MemberExpr>(E)->isArrow())
  8567. return nullptr;
  8568. // Otherwise, the expression refers to a part of the base
  8569. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8570. case Stmt::ArraySubscriptExprClass: {
  8571. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8572. // promotion of register arrays earlier.
  8573. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8574. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8575. if (ICE->getSubExpr()->getType()->isArrayType())
  8576. return getPrimaryDecl(ICE->getSubExpr());
  8577. }
  8578. return nullptr;
  8579. }
  8580. case Stmt::UnaryOperatorClass: {
  8581. UnaryOperator *UO = cast<UnaryOperator>(E);
  8582. switch(UO->getOpcode()) {
  8583. case UO_Real:
  8584. case UO_Imag:
  8585. case UO_Extension:
  8586. return getPrimaryDecl(UO->getSubExpr());
  8587. default:
  8588. return nullptr;
  8589. }
  8590. }
  8591. case Stmt::ParenExprClass:
  8592. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8593. case Stmt::ImplicitCastExprClass:
  8594. // If the result of an implicit cast is an l-value, we care about
  8595. // the sub-expression; otherwise, the result here doesn't matter.
  8596. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8597. default:
  8598. return nullptr;
  8599. }
  8600. }
  8601. namespace {
  8602. enum {
  8603. AO_Bit_Field = 0,
  8604. AO_Vector_Element = 1,
  8605. AO_Property_Expansion = 2,
  8606. AO_Register_Variable = 3,
  8607. AO_No_Error = 4
  8608. };
  8609. }
  8610. /// \brief Diagnose invalid operand for address of operations.
  8611. ///
  8612. /// \param Type The type of operand which cannot have its address taken.
  8613. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8614. Expr *E, unsigned Type) {
  8615. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8616. }
  8617. /// CheckAddressOfOperand - The operand of & must be either a function
  8618. /// designator or an lvalue designating an object. If it is an lvalue, the
  8619. /// object cannot be declared with storage class register or be a bit field.
  8620. /// Note: The usual conversions are *not* applied to the operand of the &
  8621. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8622. /// In C++, the operand might be an overloaded function name, in which case
  8623. /// we allow the '&' but retain the overloaded-function type.
  8624. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8625. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8626. if (PTy->getKind() == BuiltinType::Overload) {
  8627. Expr *E = OrigOp.get()->IgnoreParens();
  8628. if (!isa<OverloadExpr>(E)) {
  8629. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8630. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8631. << OrigOp.get()->getSourceRange();
  8632. return QualType();
  8633. }
  8634. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8635. if (isa<UnresolvedMemberExpr>(Ovl))
  8636. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8637. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8638. << OrigOp.get()->getSourceRange();
  8639. return QualType();
  8640. }
  8641. return Context.OverloadTy;
  8642. }
  8643. if (PTy->getKind() == BuiltinType::UnknownAny)
  8644. return Context.UnknownAnyTy;
  8645. if (PTy->getKind() == BuiltinType::BoundMember) {
  8646. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8647. << OrigOp.get()->getSourceRange();
  8648. return QualType();
  8649. }
  8650. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8651. if (OrigOp.isInvalid()) return QualType();
  8652. }
  8653. if (OrigOp.get()->isTypeDependent())
  8654. return Context.DependentTy;
  8655. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8656. // Make sure to ignore parentheses in subsequent checks
  8657. Expr *op = OrigOp.get()->IgnoreParens();
  8658. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8659. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8660. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8661. return QualType();
  8662. }
  8663. if (getLangOpts().C99) {
  8664. // Implement C99-only parts of addressof rules.
  8665. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8666. if (uOp->getOpcode() == UO_Deref)
  8667. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8668. // (assuming the deref expression is valid).
  8669. return uOp->getSubExpr()->getType();
  8670. }
  8671. // Technically, there should be a check for array subscript
  8672. // expressions here, but the result of one is always an lvalue anyway.
  8673. }
  8674. ValueDecl *dcl = getPrimaryDecl(op);
  8675. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  8676. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  8677. op->getLocStart()))
  8678. return QualType();
  8679. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8680. unsigned AddressOfError = AO_No_Error;
  8681. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8682. bool sfinae = (bool)isSFINAEContext();
  8683. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8684. : diag::ext_typecheck_addrof_temporary)
  8685. << op->getType() << op->getSourceRange();
  8686. if (sfinae)
  8687. return QualType();
  8688. // Materialize the temporary as an lvalue so that we can take its address.
  8689. OrigOp = op = new (Context)
  8690. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8691. } else if (isa<ObjCSelectorExpr>(op)) {
  8692. return Context.getPointerType(op->getType());
  8693. } else if (lval == Expr::LV_MemberFunction) {
  8694. // If it's an instance method, make a member pointer.
  8695. // The expression must have exactly the form &A::foo.
  8696. // If the underlying expression isn't a decl ref, give up.
  8697. if (!isa<DeclRefExpr>(op)) {
  8698. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8699. << OrigOp.get()->getSourceRange();
  8700. return QualType();
  8701. }
  8702. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8703. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8704. // The id-expression was parenthesized.
  8705. if (OrigOp.get() != DRE) {
  8706. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8707. << OrigOp.get()->getSourceRange();
  8708. // The method was named without a qualifier.
  8709. } else if (!DRE->getQualifier()) {
  8710. if (MD->getParent()->getName().empty())
  8711. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8712. << op->getSourceRange();
  8713. else {
  8714. SmallString<32> Str;
  8715. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8716. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8717. << op->getSourceRange()
  8718. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8719. }
  8720. }
  8721. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8722. if (isa<CXXDestructorDecl>(MD))
  8723. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8724. QualType MPTy = Context.getMemberPointerType(
  8725. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8726. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8727. RequireCompleteType(OpLoc, MPTy, 0);
  8728. return MPTy;
  8729. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8730. // C99 6.5.3.2p1
  8731. // The operand must be either an l-value or a function designator
  8732. if (!op->getType()->isFunctionType()) {
  8733. // Use a special diagnostic for loads from property references.
  8734. if (isa<PseudoObjectExpr>(op)) {
  8735. AddressOfError = AO_Property_Expansion;
  8736. } else {
  8737. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8738. << op->getType() << op->getSourceRange();
  8739. return QualType();
  8740. }
  8741. }
  8742. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8743. // The operand cannot be a bit-field
  8744. AddressOfError = AO_Bit_Field;
  8745. } else if (op->getObjectKind() == OK_VectorComponent) {
  8746. // The operand cannot be an element of a vector
  8747. AddressOfError = AO_Vector_Element;
  8748. } else if (dcl) { // C99 6.5.3.2p1
  8749. // We have an lvalue with a decl. Make sure the decl is not declared
  8750. // with the register storage-class specifier.
  8751. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8752. // in C++ it is not error to take address of a register
  8753. // variable (c++03 7.1.1P3)
  8754. if (vd->getStorageClass() == SC_Register &&
  8755. !getLangOpts().CPlusPlus) {
  8756. AddressOfError = AO_Register_Variable;
  8757. }
  8758. } else if (isa<MSPropertyDecl>(dcl)) {
  8759. AddressOfError = AO_Property_Expansion;
  8760. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8761. return Context.OverloadTy;
  8762. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8763. // Okay: we can take the address of a field.
  8764. // Could be a pointer to member, though, if there is an explicit
  8765. // scope qualifier for the class.
  8766. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8767. DeclContext *Ctx = dcl->getDeclContext();
  8768. if (Ctx && Ctx->isRecord()) {
  8769. if (dcl->getType()->isReferenceType()) {
  8770. Diag(OpLoc,
  8771. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8772. << dcl->getDeclName() << dcl->getType();
  8773. return QualType();
  8774. }
  8775. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8776. Ctx = Ctx->getParent();
  8777. QualType MPTy = Context.getMemberPointerType(
  8778. op->getType(),
  8779. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8780. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8781. RequireCompleteType(OpLoc, MPTy, 0);
  8782. return MPTy;
  8783. }
  8784. }
  8785. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8786. llvm_unreachable("Unknown/unexpected decl type");
  8787. }
  8788. if (AddressOfError != AO_No_Error) {
  8789. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8790. return QualType();
  8791. }
  8792. if (lval == Expr::LV_IncompleteVoidType) {
  8793. // Taking the address of a void variable is technically illegal, but we
  8794. // allow it in cases which are otherwise valid.
  8795. // Example: "extern void x; void* y = &x;".
  8796. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8797. }
  8798. // If the operand has type "type", the result has type "pointer to type".
  8799. if (op->getType()->isObjCObjectType())
  8800. return Context.getObjCObjectPointerType(op->getType());
  8801. return Context.getPointerType(op->getType());
  8802. }
  8803. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8804. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8805. if (!DRE)
  8806. return;
  8807. const Decl *D = DRE->getDecl();
  8808. if (!D)
  8809. return;
  8810. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8811. if (!Param)
  8812. return;
  8813. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8814. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8815. return;
  8816. if (FunctionScopeInfo *FD = S.getCurFunction())
  8817. if (!FD->ModifiedNonNullParams.count(Param))
  8818. FD->ModifiedNonNullParams.insert(Param);
  8819. }
  8820. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8821. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8822. SourceLocation OpLoc) {
  8823. if (Op->isTypeDependent())
  8824. return S.Context.DependentTy;
  8825. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8826. if (ConvResult.isInvalid())
  8827. return QualType();
  8828. Op = ConvResult.get();
  8829. QualType OpTy = Op->getType();
  8830. QualType Result;
  8831. if (isa<CXXReinterpretCastExpr>(Op)) {
  8832. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8833. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8834. Op->getSourceRange());
  8835. }
  8836. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8837. Result = PT->getPointeeType();
  8838. else if (const ObjCObjectPointerType *OPT =
  8839. OpTy->getAs<ObjCObjectPointerType>())
  8840. Result = OPT->getPointeeType();
  8841. else {
  8842. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8843. if (PR.isInvalid()) return QualType();
  8844. if (PR.get() != Op)
  8845. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8846. }
  8847. if (Result.isNull()) {
  8848. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8849. << OpTy << Op->getSourceRange();
  8850. return QualType();
  8851. }
  8852. // Note that per both C89 and C99, indirection is always legal, even if Result
  8853. // is an incomplete type or void. It would be possible to warn about
  8854. // dereferencing a void pointer, but it's completely well-defined, and such a
  8855. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8856. // for pointers to 'void' but is fine for any other pointer type:
  8857. //
  8858. // C++ [expr.unary.op]p1:
  8859. // [...] the expression to which [the unary * operator] is applied shall
  8860. // be a pointer to an object type, or a pointer to a function type
  8861. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8862. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8863. << OpTy << Op->getSourceRange();
  8864. // Dereferences are usually l-values...
  8865. VK = VK_LValue;
  8866. // ...except that certain expressions are never l-values in C.
  8867. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8868. VK = VK_RValue;
  8869. return Result;
  8870. }
  8871. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8872. BinaryOperatorKind Opc;
  8873. switch (Kind) {
  8874. default: llvm_unreachable("Unknown binop!");
  8875. case tok::periodstar: Opc = BO_PtrMemD; break;
  8876. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8877. case tok::star: Opc = BO_Mul; break;
  8878. case tok::slash: Opc = BO_Div; break;
  8879. case tok::percent: Opc = BO_Rem; break;
  8880. case tok::plus: Opc = BO_Add; break;
  8881. case tok::minus: Opc = BO_Sub; break;
  8882. case tok::lessless: Opc = BO_Shl; break;
  8883. case tok::greatergreater: Opc = BO_Shr; break;
  8884. case tok::lessequal: Opc = BO_LE; break;
  8885. case tok::less: Opc = BO_LT; break;
  8886. case tok::greaterequal: Opc = BO_GE; break;
  8887. case tok::greater: Opc = BO_GT; break;
  8888. case tok::exclaimequal: Opc = BO_NE; break;
  8889. case tok::equalequal: Opc = BO_EQ; break;
  8890. case tok::amp: Opc = BO_And; break;
  8891. case tok::caret: Opc = BO_Xor; break;
  8892. case tok::pipe: Opc = BO_Or; break;
  8893. case tok::ampamp: Opc = BO_LAnd; break;
  8894. case tok::pipepipe: Opc = BO_LOr; break;
  8895. case tok::equal: Opc = BO_Assign; break;
  8896. case tok::starequal: Opc = BO_MulAssign; break;
  8897. case tok::slashequal: Opc = BO_DivAssign; break;
  8898. case tok::percentequal: Opc = BO_RemAssign; break;
  8899. case tok::plusequal: Opc = BO_AddAssign; break;
  8900. case tok::minusequal: Opc = BO_SubAssign; break;
  8901. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8902. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8903. case tok::ampequal: Opc = BO_AndAssign; break;
  8904. case tok::caretequal: Opc = BO_XorAssign; break;
  8905. case tok::pipeequal: Opc = BO_OrAssign; break;
  8906. case tok::comma: Opc = BO_Comma; break;
  8907. }
  8908. return Opc;
  8909. }
  8910. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8911. tok::TokenKind Kind) {
  8912. UnaryOperatorKind Opc;
  8913. switch (Kind) {
  8914. default: llvm_unreachable("Unknown unary op!");
  8915. case tok::plusplus: Opc = UO_PreInc; break;
  8916. case tok::minusminus: Opc = UO_PreDec; break;
  8917. case tok::amp: Opc = UO_AddrOf; break;
  8918. case tok::star: Opc = UO_Deref; break;
  8919. case tok::plus: Opc = UO_Plus; break;
  8920. case tok::minus: Opc = UO_Minus; break;
  8921. case tok::tilde: Opc = UO_Not; break;
  8922. case tok::exclaim: Opc = UO_LNot; break;
  8923. case tok::kw___real: Opc = UO_Real; break;
  8924. case tok::kw___imag: Opc = UO_Imag; break;
  8925. case tok::kw___extension__: Opc = UO_Extension; break;
  8926. }
  8927. return Opc;
  8928. }
  8929. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8930. /// This warning is only emitted for builtin assignment operations. It is also
  8931. /// suppressed in the event of macro expansions.
  8932. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8933. SourceLocation OpLoc) {
  8934. if (!S.ActiveTemplateInstantiations.empty())
  8935. return;
  8936. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  8937. return;
  8938. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8939. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8940. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8941. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8942. if (!LHSDeclRef || !RHSDeclRef ||
  8943. LHSDeclRef->getLocation().isMacroID() ||
  8944. RHSDeclRef->getLocation().isMacroID())
  8945. return;
  8946. const ValueDecl *LHSDecl =
  8947. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  8948. const ValueDecl *RHSDecl =
  8949. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  8950. if (LHSDecl != RHSDecl)
  8951. return;
  8952. if (LHSDecl->getType().isVolatileQualified())
  8953. return;
  8954. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  8955. if (RefTy->getPointeeType().isVolatileQualified())
  8956. return;
  8957. S.Diag(OpLoc, diag::warn_self_assignment)
  8958. << LHSDeclRef->getType()
  8959. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8960. }
  8961. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  8962. /// is usually indicative of introspection within the Objective-C pointer.
  8963. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  8964. SourceLocation OpLoc) {
  8965. if (!S.getLangOpts().ObjC1)
  8966. return;
  8967. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  8968. const Expr *LHS = L.get();
  8969. const Expr *RHS = R.get();
  8970. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8971. ObjCPointerExpr = LHS;
  8972. OtherExpr = RHS;
  8973. }
  8974. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8975. ObjCPointerExpr = RHS;
  8976. OtherExpr = LHS;
  8977. }
  8978. // This warning is deliberately made very specific to reduce false
  8979. // positives with logic that uses '&' for hashing. This logic mainly
  8980. // looks for code trying to introspect into tagged pointers, which
  8981. // code should generally never do.
  8982. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  8983. unsigned Diag = diag::warn_objc_pointer_masking;
  8984. // Determine if we are introspecting the result of performSelectorXXX.
  8985. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  8986. // Special case messages to -performSelector and friends, which
  8987. // can return non-pointer values boxed in a pointer value.
  8988. // Some clients may wish to silence warnings in this subcase.
  8989. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  8990. Selector S = ME->getSelector();
  8991. StringRef SelArg0 = S.getNameForSlot(0);
  8992. if (SelArg0.startswith("performSelector"))
  8993. Diag = diag::warn_objc_pointer_masking_performSelector;
  8994. }
  8995. S.Diag(OpLoc, Diag)
  8996. << ObjCPointerExpr->getSourceRange();
  8997. }
  8998. }
  8999. static NamedDecl *getDeclFromExpr(Expr *E) {
  9000. if (!E)
  9001. return nullptr;
  9002. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  9003. return DRE->getDecl();
  9004. if (auto *ME = dyn_cast<MemberExpr>(E))
  9005. return ME->getMemberDecl();
  9006. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  9007. return IRE->getDecl();
  9008. return nullptr;
  9009. }
  9010. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  9011. /// operator @p Opc at location @c TokLoc. This routine only supports
  9012. /// built-in operations; ActOnBinOp handles overloaded operators.
  9013. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  9014. BinaryOperatorKind Opc,
  9015. Expr *LHSExpr, Expr *RHSExpr) {
  9016. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  9017. // The syntax only allows initializer lists on the RHS of assignment,
  9018. // so we don't need to worry about accepting invalid code for
  9019. // non-assignment operators.
  9020. // C++11 5.17p9:
  9021. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  9022. // of x = {} is x = T().
  9023. InitializationKind Kind =
  9024. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  9025. InitializedEntity Entity =
  9026. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  9027. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  9028. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  9029. if (Init.isInvalid())
  9030. return Init;
  9031. RHSExpr = Init.get();
  9032. }
  9033. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  9034. QualType ResultTy; // Result type of the binary operator.
  9035. // The following two variables are used for compound assignment operators
  9036. QualType CompLHSTy; // Type of LHS after promotions for computation
  9037. QualType CompResultTy; // Type of computation result
  9038. ExprValueKind VK = VK_RValue;
  9039. ExprObjectKind OK = OK_Ordinary;
  9040. if (!getLangOpts().CPlusPlus) {
  9041. // C cannot handle TypoExpr nodes on either side of a binop because it
  9042. // doesn't handle dependent types properly, so make sure any TypoExprs have
  9043. // been dealt with before checking the operands.
  9044. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  9045. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  9046. if (Opc != BO_Assign)
  9047. return ExprResult(E);
  9048. // Avoid correcting the RHS to the same Expr as the LHS.
  9049. Decl *D = getDeclFromExpr(E);
  9050. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  9051. });
  9052. if (!LHS.isUsable() || !RHS.isUsable())
  9053. return ExprError();
  9054. }
  9055. if (getLangOpts().OpenCL) {
  9056. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  9057. // the ATOMIC_VAR_INIT macro.
  9058. if (LHSExpr->getType()->isAtomicType() ||
  9059. RHSExpr->getType()->isAtomicType()) {
  9060. SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  9061. if (BO_Assign == Opc)
  9062. Diag(OpLoc, diag::err_atomic_init_constant) << SR;
  9063. else
  9064. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  9065. return ExprError();
  9066. }
  9067. }
  9068. switch (Opc) {
  9069. case BO_Assign:
  9070. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  9071. if (getLangOpts().CPlusPlus &&
  9072. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  9073. VK = LHS.get()->getValueKind();
  9074. OK = LHS.get()->getObjectKind();
  9075. }
  9076. if (!ResultTy.isNull()) {
  9077. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9078. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  9079. }
  9080. RecordModifiableNonNullParam(*this, LHS.get());
  9081. break;
  9082. case BO_PtrMemD:
  9083. case BO_PtrMemI:
  9084. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  9085. Opc == BO_PtrMemI);
  9086. break;
  9087. case BO_Mul:
  9088. case BO_Div:
  9089. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  9090. Opc == BO_Div);
  9091. break;
  9092. case BO_Rem:
  9093. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  9094. break;
  9095. case BO_Add:
  9096. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  9097. break;
  9098. case BO_Sub:
  9099. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  9100. break;
  9101. case BO_Shl:
  9102. case BO_Shr:
  9103. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  9104. break;
  9105. case BO_LE:
  9106. case BO_LT:
  9107. case BO_GE:
  9108. case BO_GT:
  9109. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  9110. break;
  9111. case BO_EQ:
  9112. case BO_NE:
  9113. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  9114. break;
  9115. case BO_And:
  9116. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  9117. case BO_Xor:
  9118. case BO_Or:
  9119. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  9120. break;
  9121. case BO_LAnd:
  9122. case BO_LOr:
  9123. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  9124. break;
  9125. case BO_MulAssign:
  9126. case BO_DivAssign:
  9127. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  9128. Opc == BO_DivAssign);
  9129. CompLHSTy = CompResultTy;
  9130. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9131. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9132. break;
  9133. case BO_RemAssign:
  9134. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  9135. CompLHSTy = CompResultTy;
  9136. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9137. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9138. break;
  9139. case BO_AddAssign:
  9140. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  9141. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9142. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9143. break;
  9144. case BO_SubAssign:
  9145. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  9146. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9147. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9148. break;
  9149. case BO_ShlAssign:
  9150. case BO_ShrAssign:
  9151. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  9152. CompLHSTy = CompResultTy;
  9153. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9154. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9155. break;
  9156. case BO_AndAssign:
  9157. case BO_OrAssign: // fallthrough
  9158. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9159. case BO_XorAssign:
  9160. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  9161. CompLHSTy = CompResultTy;
  9162. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9163. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9164. break;
  9165. case BO_Comma:
  9166. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  9167. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  9168. VK = RHS.get()->getValueKind();
  9169. OK = RHS.get()->getObjectKind();
  9170. }
  9171. break;
  9172. }
  9173. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  9174. return ExprError();
  9175. // Check for array bounds violations for both sides of the BinaryOperator
  9176. CheckArrayAccess(LHS.get());
  9177. CheckArrayAccess(RHS.get());
  9178. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  9179. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  9180. &Context.Idents.get("object_setClass"),
  9181. SourceLocation(), LookupOrdinaryName);
  9182. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  9183. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
  9184. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  9185. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  9186. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  9187. FixItHint::CreateInsertion(RHSLocEnd, ")");
  9188. }
  9189. else
  9190. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  9191. }
  9192. else if (const ObjCIvarRefExpr *OIRE =
  9193. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  9194. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  9195. if (CompResultTy.isNull())
  9196. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  9197. OK, OpLoc, FPFeatures.fp_contract);
  9198. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  9199. OK_ObjCProperty) {
  9200. VK = VK_LValue;
  9201. OK = LHS.get()->getObjectKind();
  9202. }
  9203. return new (Context) CompoundAssignOperator(
  9204. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  9205. OpLoc, FPFeatures.fp_contract);
  9206. }
  9207. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  9208. /// operators are mixed in a way that suggests that the programmer forgot that
  9209. /// comparison operators have higher precedence. The most typical example of
  9210. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  9211. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  9212. SourceLocation OpLoc, Expr *LHSExpr,
  9213. Expr *RHSExpr) {
  9214. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  9215. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  9216. // Check that one of the sides is a comparison operator.
  9217. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  9218. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  9219. if (!isLeftComp && !isRightComp)
  9220. return;
  9221. // Bitwise operations are sometimes used as eager logical ops.
  9222. // Don't diagnose this.
  9223. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  9224. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  9225. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  9226. return;
  9227. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  9228. OpLoc)
  9229. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  9230. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  9231. SourceRange ParensRange = isLeftComp ?
  9232. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  9233. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  9234. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  9235. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  9236. SuggestParentheses(Self, OpLoc,
  9237. Self.PDiag(diag::note_precedence_silence) << OpStr,
  9238. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  9239. SuggestParentheses(Self, OpLoc,
  9240. Self.PDiag(diag::note_precedence_bitwise_first)
  9241. << BinaryOperator::getOpcodeStr(Opc),
  9242. ParensRange);
  9243. }
  9244. /// \brief It accepts a '&' expr that is inside a '|' one.
  9245. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  9246. /// in parentheses.
  9247. static void
  9248. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  9249. BinaryOperator *Bop) {
  9250. assert(Bop->getOpcode() == BO_And);
  9251. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  9252. << Bop->getSourceRange() << OpLoc;
  9253. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9254. Self.PDiag(diag::note_precedence_silence)
  9255. << Bop->getOpcodeStr(),
  9256. Bop->getSourceRange());
  9257. }
  9258. /// \brief It accepts a '&&' expr that is inside a '||' one.
  9259. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  9260. /// in parentheses.
  9261. static void
  9262. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  9263. BinaryOperator *Bop) {
  9264. assert(Bop->getOpcode() == BO_LAnd);
  9265. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  9266. << Bop->getSourceRange() << OpLoc;
  9267. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9268. Self.PDiag(diag::note_precedence_silence)
  9269. << Bop->getOpcodeStr(),
  9270. Bop->getSourceRange());
  9271. }
  9272. /// \brief Returns true if the given expression can be evaluated as a constant
  9273. /// 'true'.
  9274. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  9275. bool Res;
  9276. return !E->isValueDependent() &&
  9277. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  9278. }
  9279. /// \brief Returns true if the given expression can be evaluated as a constant
  9280. /// 'false'.
  9281. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  9282. bool Res;
  9283. return !E->isValueDependent() &&
  9284. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  9285. }
  9286. /// \brief Look for '&&' in the left hand of a '||' expr.
  9287. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  9288. Expr *LHSExpr, Expr *RHSExpr) {
  9289. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  9290. if (Bop->getOpcode() == BO_LAnd) {
  9291. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  9292. if (EvaluatesAsFalse(S, RHSExpr))
  9293. return;
  9294. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  9295. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  9296. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9297. } else if (Bop->getOpcode() == BO_LOr) {
  9298. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  9299. // If it's "a || b && 1 || c" we didn't warn earlier for
  9300. // "a || b && 1", but warn now.
  9301. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  9302. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  9303. }
  9304. }
  9305. }
  9306. }
  9307. /// \brief Look for '&&' in the right hand of a '||' expr.
  9308. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  9309. Expr *LHSExpr, Expr *RHSExpr) {
  9310. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  9311. if (Bop->getOpcode() == BO_LAnd) {
  9312. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  9313. if (EvaluatesAsFalse(S, LHSExpr))
  9314. return;
  9315. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  9316. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  9317. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9318. }
  9319. }
  9320. }
  9321. /// \brief Look for '&' in the left or right hand of a '|' expr.
  9322. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  9323. Expr *OrArg) {
  9324. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  9325. if (Bop->getOpcode() == BO_And)
  9326. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  9327. }
  9328. }
  9329. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  9330. Expr *SubExpr, StringRef Shift) {
  9331. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  9332. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  9333. StringRef Op = Bop->getOpcodeStr();
  9334. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  9335. << Bop->getSourceRange() << OpLoc << Shift << Op;
  9336. SuggestParentheses(S, Bop->getOperatorLoc(),
  9337. S.PDiag(diag::note_precedence_silence) << Op,
  9338. Bop->getSourceRange());
  9339. }
  9340. }
  9341. }
  9342. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  9343. Expr *LHSExpr, Expr *RHSExpr) {
  9344. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  9345. if (!OCE)
  9346. return;
  9347. FunctionDecl *FD = OCE->getDirectCallee();
  9348. if (!FD || !FD->isOverloadedOperator())
  9349. return;
  9350. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  9351. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  9352. return;
  9353. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  9354. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  9355. << (Kind == OO_LessLess);
  9356. SuggestParentheses(S, OCE->getOperatorLoc(),
  9357. S.PDiag(diag::note_precedence_silence)
  9358. << (Kind == OO_LessLess ? "<<" : ">>"),
  9359. OCE->getSourceRange());
  9360. SuggestParentheses(S, OpLoc,
  9361. S.PDiag(diag::note_evaluate_comparison_first),
  9362. SourceRange(OCE->getArg(1)->getLocStart(),
  9363. RHSExpr->getLocEnd()));
  9364. }
  9365. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  9366. /// precedence.
  9367. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  9368. SourceLocation OpLoc, Expr *LHSExpr,
  9369. Expr *RHSExpr){
  9370. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  9371. if (BinaryOperator::isBitwiseOp(Opc))
  9372. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  9373. // Diagnose "arg1 & arg2 | arg3"
  9374. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9375. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  9376. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  9377. }
  9378. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  9379. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  9380. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9381. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  9382. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  9383. }
  9384. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  9385. || Opc == BO_Shr) {
  9386. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  9387. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  9388. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  9389. }
  9390. // Warn on overloaded shift operators and comparisons, such as:
  9391. // cout << 5 == 4;
  9392. if (BinaryOperator::isComparisonOp(Opc))
  9393. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  9394. }
  9395. // Binary Operators. 'Tok' is the token for the operator.
  9396. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  9397. tok::TokenKind Kind,
  9398. Expr *LHSExpr, Expr *RHSExpr) {
  9399. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  9400. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  9401. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  9402. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  9403. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  9404. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  9405. }
  9406. /// Build an overloaded binary operator expression in the given scope.
  9407. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  9408. BinaryOperatorKind Opc,
  9409. Expr *LHS, Expr *RHS) {
  9410. // Find all of the overloaded operators visible from this
  9411. // point. We perform both an operator-name lookup from the local
  9412. // scope and an argument-dependent lookup based on the types of
  9413. // the arguments.
  9414. UnresolvedSet<16> Functions;
  9415. OverloadedOperatorKind OverOp
  9416. = BinaryOperator::getOverloadedOperator(Opc);
  9417. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  9418. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  9419. RHS->getType(), Functions);
  9420. // Build the (potentially-overloaded, potentially-dependent)
  9421. // binary operation.
  9422. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  9423. }
  9424. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  9425. BinaryOperatorKind Opc,
  9426. Expr *LHSExpr, Expr *RHSExpr) {
  9427. // We want to end up calling one of checkPseudoObjectAssignment
  9428. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  9429. // both expressions are overloadable or either is type-dependent),
  9430. // or CreateBuiltinBinOp (in any other case). We also want to get
  9431. // any placeholder types out of the way.
  9432. // Handle pseudo-objects in the LHS.
  9433. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  9434. // Assignments with a pseudo-object l-value need special analysis.
  9435. if (pty->getKind() == BuiltinType::PseudoObject &&
  9436. BinaryOperator::isAssignmentOp(Opc))
  9437. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  9438. // Don't resolve overloads if the other type is overloadable.
  9439. if (pty->getKind() == BuiltinType::Overload) {
  9440. // We can't actually test that if we still have a placeholder,
  9441. // though. Fortunately, none of the exceptions we see in that
  9442. // code below are valid when the LHS is an overload set. Note
  9443. // that an overload set can be dependently-typed, but it never
  9444. // instantiates to having an overloadable type.
  9445. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9446. if (resolvedRHS.isInvalid()) return ExprError();
  9447. RHSExpr = resolvedRHS.get();
  9448. if (RHSExpr->isTypeDependent() ||
  9449. RHSExpr->getType()->isOverloadableType())
  9450. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9451. }
  9452. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  9453. if (LHS.isInvalid()) return ExprError();
  9454. LHSExpr = LHS.get();
  9455. }
  9456. // Handle pseudo-objects in the RHS.
  9457. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  9458. // An overload in the RHS can potentially be resolved by the type
  9459. // being assigned to.
  9460. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  9461. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9462. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9463. if (LHSExpr->getType()->isOverloadableType())
  9464. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9465. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9466. }
  9467. // Don't resolve overloads if the other type is overloadable.
  9468. if (pty->getKind() == BuiltinType::Overload &&
  9469. LHSExpr->getType()->isOverloadableType())
  9470. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9471. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9472. if (!resolvedRHS.isUsable()) return ExprError();
  9473. RHSExpr = resolvedRHS.get();
  9474. }
  9475. if (getLangOpts().CPlusPlus) {
  9476. // If either expression is type-dependent, always build an
  9477. // overloaded op.
  9478. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9479. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9480. // Otherwise, build an overloaded op if either expression has an
  9481. // overloadable type.
  9482. if (LHSExpr->getType()->isOverloadableType() ||
  9483. RHSExpr->getType()->isOverloadableType())
  9484. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9485. }
  9486. // Build a built-in binary operation.
  9487. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9488. }
  9489. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  9490. UnaryOperatorKind Opc,
  9491. Expr *InputExpr) {
  9492. ExprResult Input = InputExpr;
  9493. ExprValueKind VK = VK_RValue;
  9494. ExprObjectKind OK = OK_Ordinary;
  9495. QualType resultType;
  9496. if (getLangOpts().OpenCL) {
  9497. // The only legal unary operation for atomics is '&'.
  9498. if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
  9499. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9500. << InputExpr->getType()
  9501. << Input.get()->getSourceRange());
  9502. }
  9503. }
  9504. switch (Opc) {
  9505. case UO_PreInc:
  9506. case UO_PreDec:
  9507. case UO_PostInc:
  9508. case UO_PostDec:
  9509. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  9510. OpLoc,
  9511. Opc == UO_PreInc ||
  9512. Opc == UO_PostInc,
  9513. Opc == UO_PreInc ||
  9514. Opc == UO_PreDec);
  9515. break;
  9516. case UO_AddrOf:
  9517. resultType = CheckAddressOfOperand(Input, OpLoc);
  9518. RecordModifiableNonNullParam(*this, InputExpr);
  9519. break;
  9520. case UO_Deref: {
  9521. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9522. if (Input.isInvalid()) return ExprError();
  9523. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  9524. break;
  9525. }
  9526. case UO_Plus:
  9527. case UO_Minus:
  9528. Input = UsualUnaryConversions(Input.get());
  9529. if (Input.isInvalid()) return ExprError();
  9530. resultType = Input.get()->getType();
  9531. if (resultType->isDependentType())
  9532. break;
  9533. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  9534. break;
  9535. else if (resultType->isVectorType() &&
  9536. // The z vector extensions don't allow + or - with bool vectors.
  9537. (!Context.getLangOpts().ZVector ||
  9538. resultType->getAs<VectorType>()->getVectorKind() !=
  9539. VectorType::AltiVecBool))
  9540. break;
  9541. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  9542. Opc == UO_Plus &&
  9543. resultType->isPointerType())
  9544. break;
  9545. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9546. << resultType << Input.get()->getSourceRange());
  9547. case UO_Not: // bitwise complement
  9548. Input = UsualUnaryConversions(Input.get());
  9549. if (Input.isInvalid())
  9550. return ExprError();
  9551. resultType = Input.get()->getType();
  9552. if (resultType->isDependentType())
  9553. break;
  9554. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9555. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9556. // C99 does not support '~' for complex conjugation.
  9557. Diag(OpLoc, diag::ext_integer_complement_complex)
  9558. << resultType << Input.get()->getSourceRange();
  9559. else if (resultType->hasIntegerRepresentation())
  9560. break;
  9561. else if (resultType->isExtVectorType()) {
  9562. if (Context.getLangOpts().OpenCL) {
  9563. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9564. // on vector float types.
  9565. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9566. if (!T->isIntegerType())
  9567. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9568. << resultType << Input.get()->getSourceRange());
  9569. }
  9570. break;
  9571. } else {
  9572. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9573. << resultType << Input.get()->getSourceRange());
  9574. }
  9575. break;
  9576. case UO_LNot: // logical negation
  9577. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9578. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9579. if (Input.isInvalid()) return ExprError();
  9580. resultType = Input.get()->getType();
  9581. // Though we still have to promote half FP to float...
  9582. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9583. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9584. resultType = Context.FloatTy;
  9585. }
  9586. if (resultType->isDependentType())
  9587. break;
  9588. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9589. // C99 6.5.3.3p1: ok, fallthrough;
  9590. if (Context.getLangOpts().CPlusPlus) {
  9591. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9592. // operand contextually converted to bool.
  9593. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9594. ScalarTypeToBooleanCastKind(resultType));
  9595. } else if (Context.getLangOpts().OpenCL &&
  9596. Context.getLangOpts().OpenCLVersion < 120) {
  9597. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9598. // operate on scalar float types.
  9599. if (!resultType->isIntegerType())
  9600. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9601. << resultType << Input.get()->getSourceRange());
  9602. }
  9603. } else if (resultType->isExtVectorType()) {
  9604. if (Context.getLangOpts().OpenCL &&
  9605. Context.getLangOpts().OpenCLVersion < 120) {
  9606. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9607. // operate on vector float types.
  9608. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9609. if (!T->isIntegerType())
  9610. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9611. << resultType << Input.get()->getSourceRange());
  9612. }
  9613. // Vector logical not returns the signed variant of the operand type.
  9614. resultType = GetSignedVectorType(resultType);
  9615. break;
  9616. } else {
  9617. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9618. << resultType << Input.get()->getSourceRange());
  9619. }
  9620. // LNot always has type int. C99 6.5.3.3p5.
  9621. // In C++, it's bool. C++ 5.3.1p8
  9622. resultType = Context.getLogicalOperationType();
  9623. break;
  9624. case UO_Real:
  9625. case UO_Imag:
  9626. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9627. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9628. // complex l-values to ordinary l-values and all other values to r-values.
  9629. if (Input.isInvalid()) return ExprError();
  9630. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9631. if (Input.get()->getValueKind() != VK_RValue &&
  9632. Input.get()->getObjectKind() == OK_Ordinary)
  9633. VK = Input.get()->getValueKind();
  9634. } else if (!getLangOpts().CPlusPlus) {
  9635. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9636. Input = DefaultLvalueConversion(Input.get());
  9637. }
  9638. break;
  9639. case UO_Extension:
  9640. case UO_Coawait:
  9641. resultType = Input.get()->getType();
  9642. VK = Input.get()->getValueKind();
  9643. OK = Input.get()->getObjectKind();
  9644. break;
  9645. }
  9646. if (resultType.isNull() || Input.isInvalid())
  9647. return ExprError();
  9648. // Check for array bounds violations in the operand of the UnaryOperator,
  9649. // except for the '*' and '&' operators that have to be handled specially
  9650. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9651. // that are explicitly defined as valid by the standard).
  9652. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9653. CheckArrayAccess(Input.get());
  9654. return new (Context)
  9655. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9656. }
  9657. /// \brief Determine whether the given expression is a qualified member
  9658. /// access expression, of a form that could be turned into a pointer to member
  9659. /// with the address-of operator.
  9660. static bool isQualifiedMemberAccess(Expr *E) {
  9661. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9662. if (!DRE->getQualifier())
  9663. return false;
  9664. ValueDecl *VD = DRE->getDecl();
  9665. if (!VD->isCXXClassMember())
  9666. return false;
  9667. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9668. return true;
  9669. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9670. return Method->isInstance();
  9671. return false;
  9672. }
  9673. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9674. if (!ULE->getQualifier())
  9675. return false;
  9676. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9677. DEnd = ULE->decls_end();
  9678. D != DEnd; ++D) {
  9679. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9680. if (Method->isInstance())
  9681. return true;
  9682. } else {
  9683. // Overload set does not contain methods.
  9684. break;
  9685. }
  9686. }
  9687. return false;
  9688. }
  9689. return false;
  9690. }
  9691. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9692. UnaryOperatorKind Opc, Expr *Input) {
  9693. // First things first: handle placeholders so that the
  9694. // overloaded-operator check considers the right type.
  9695. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9696. // Increment and decrement of pseudo-object references.
  9697. if (pty->getKind() == BuiltinType::PseudoObject &&
  9698. UnaryOperator::isIncrementDecrementOp(Opc))
  9699. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9700. // extension is always a builtin operator.
  9701. if (Opc == UO_Extension)
  9702. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9703. // & gets special logic for several kinds of placeholder.
  9704. // The builtin code knows what to do.
  9705. if (Opc == UO_AddrOf &&
  9706. (pty->getKind() == BuiltinType::Overload ||
  9707. pty->getKind() == BuiltinType::UnknownAny ||
  9708. pty->getKind() == BuiltinType::BoundMember))
  9709. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9710. // Anything else needs to be handled now.
  9711. ExprResult Result = CheckPlaceholderExpr(Input);
  9712. if (Result.isInvalid()) return ExprError();
  9713. Input = Result.get();
  9714. }
  9715. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9716. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9717. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9718. // Find all of the overloaded operators visible from this
  9719. // point. We perform both an operator-name lookup from the local
  9720. // scope and an argument-dependent lookup based on the types of
  9721. // the arguments.
  9722. UnresolvedSet<16> Functions;
  9723. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9724. if (S && OverOp != OO_None)
  9725. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9726. Functions);
  9727. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9728. }
  9729. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9730. }
  9731. // Unary Operators. 'Tok' is the token for the operator.
  9732. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9733. tok::TokenKind Op, Expr *Input) {
  9734. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9735. }
  9736. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9737. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9738. LabelDecl *TheDecl) {
  9739. TheDecl->markUsed(Context);
  9740. // Create the AST node. The address of a label always has type 'void*'.
  9741. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9742. Context.getPointerType(Context.VoidTy));
  9743. }
  9744. /// Given the last statement in a statement-expression, check whether
  9745. /// the result is a producing expression (like a call to an
  9746. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9747. /// release out of the full-expression. Otherwise, return null.
  9748. /// Cannot fail.
  9749. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9750. // Should always be wrapped with one of these.
  9751. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9752. if (!cleanups) return nullptr;
  9753. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9754. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9755. return nullptr;
  9756. // Splice out the cast. This shouldn't modify any interesting
  9757. // features of the statement.
  9758. Expr *producer = cast->getSubExpr();
  9759. assert(producer->getType() == cast->getType());
  9760. assert(producer->getValueKind() == cast->getValueKind());
  9761. cleanups->setSubExpr(producer);
  9762. return cleanups;
  9763. }
  9764. void Sema::ActOnStartStmtExpr() {
  9765. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9766. }
  9767. void Sema::ActOnStmtExprError() {
  9768. // Note that function is also called by TreeTransform when leaving a
  9769. // StmtExpr scope without rebuilding anything.
  9770. DiscardCleanupsInEvaluationContext();
  9771. PopExpressionEvaluationContext();
  9772. }
  9773. ExprResult
  9774. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9775. SourceLocation RPLoc) { // "({..})"
  9776. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9777. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9778. if (hasAnyUnrecoverableErrorsInThisFunction())
  9779. DiscardCleanupsInEvaluationContext();
  9780. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9781. PopExpressionEvaluationContext();
  9782. // FIXME: there are a variety of strange constraints to enforce here, for
  9783. // example, it is not possible to goto into a stmt expression apparently.
  9784. // More semantic analysis is needed.
  9785. // If there are sub-stmts in the compound stmt, take the type of the last one
  9786. // as the type of the stmtexpr.
  9787. QualType Ty = Context.VoidTy;
  9788. bool StmtExprMayBindToTemp = false;
  9789. if (!Compound->body_empty()) {
  9790. Stmt *LastStmt = Compound->body_back();
  9791. LabelStmt *LastLabelStmt = nullptr;
  9792. // If LastStmt is a label, skip down through into the body.
  9793. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9794. LastLabelStmt = Label;
  9795. LastStmt = Label->getSubStmt();
  9796. }
  9797. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9798. // Do function/array conversion on the last expression, but not
  9799. // lvalue-to-rvalue. However, initialize an unqualified type.
  9800. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9801. if (LastExpr.isInvalid())
  9802. return ExprError();
  9803. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9804. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9805. // In ARC, if the final expression ends in a consume, splice
  9806. // the consume out and bind it later. In the alternate case
  9807. // (when dealing with a retainable type), the result
  9808. // initialization will create a produce. In both cases the
  9809. // result will be +1, and we'll need to balance that out with
  9810. // a bind.
  9811. if (Expr *rebuiltLastStmt
  9812. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9813. LastExpr = rebuiltLastStmt;
  9814. } else {
  9815. LastExpr = PerformCopyInitialization(
  9816. InitializedEntity::InitializeResult(LPLoc,
  9817. Ty,
  9818. false),
  9819. SourceLocation(),
  9820. LastExpr);
  9821. }
  9822. if (LastExpr.isInvalid())
  9823. return ExprError();
  9824. if (LastExpr.get() != nullptr) {
  9825. if (!LastLabelStmt)
  9826. Compound->setLastStmt(LastExpr.get());
  9827. else
  9828. LastLabelStmt->setSubStmt(LastExpr.get());
  9829. StmtExprMayBindToTemp = true;
  9830. }
  9831. }
  9832. }
  9833. }
  9834. // FIXME: Check that expression type is complete/non-abstract; statement
  9835. // expressions are not lvalues.
  9836. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9837. if (StmtExprMayBindToTemp)
  9838. return MaybeBindToTemporary(ResStmtExpr);
  9839. return ResStmtExpr;
  9840. }
  9841. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9842. TypeSourceInfo *TInfo,
  9843. ArrayRef<OffsetOfComponent> Components,
  9844. SourceLocation RParenLoc) {
  9845. QualType ArgTy = TInfo->getType();
  9846. bool Dependent = ArgTy->isDependentType();
  9847. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9848. // We must have at least one component that refers to the type, and the first
  9849. // one is known to be a field designator. Verify that the ArgTy represents
  9850. // a struct/union/class.
  9851. if (!Dependent && !ArgTy->isRecordType())
  9852. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9853. << ArgTy << TypeRange);
  9854. // Type must be complete per C99 7.17p3 because a declaring a variable
  9855. // with an incomplete type would be ill-formed.
  9856. if (!Dependent
  9857. && RequireCompleteType(BuiltinLoc, ArgTy,
  9858. diag::err_offsetof_incomplete_type, TypeRange))
  9859. return ExprError();
  9860. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9861. // GCC extension, diagnose them.
  9862. // FIXME: This diagnostic isn't actually visible because the location is in
  9863. // a system header!
  9864. if (Components.size() != 1)
  9865. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9866. << SourceRange(Components[1].LocStart, Components.back().LocEnd);
  9867. bool DidWarnAboutNonPOD = false;
  9868. QualType CurrentType = ArgTy;
  9869. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9870. SmallVector<OffsetOfNode, 4> Comps;
  9871. SmallVector<Expr*, 4> Exprs;
  9872. for (const OffsetOfComponent &OC : Components) {
  9873. if (OC.isBrackets) {
  9874. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9875. if (!CurrentType->isDependentType()) {
  9876. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9877. if(!AT)
  9878. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9879. << CurrentType);
  9880. CurrentType = AT->getElementType();
  9881. } else
  9882. CurrentType = Context.DependentTy;
  9883. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9884. if (IdxRval.isInvalid())
  9885. return ExprError();
  9886. Expr *Idx = IdxRval.get();
  9887. // The expression must be an integral expression.
  9888. // FIXME: An integral constant expression?
  9889. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9890. !Idx->getType()->isIntegerType())
  9891. return ExprError(Diag(Idx->getLocStart(),
  9892. diag::err_typecheck_subscript_not_integer)
  9893. << Idx->getSourceRange());
  9894. // Record this array index.
  9895. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9896. Exprs.push_back(Idx);
  9897. continue;
  9898. }
  9899. // Offset of a field.
  9900. if (CurrentType->isDependentType()) {
  9901. // We have the offset of a field, but we can't look into the dependent
  9902. // type. Just record the identifier of the field.
  9903. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9904. CurrentType = Context.DependentTy;
  9905. continue;
  9906. }
  9907. // We need to have a complete type to look into.
  9908. if (RequireCompleteType(OC.LocStart, CurrentType,
  9909. diag::err_offsetof_incomplete_type))
  9910. return ExprError();
  9911. // Look for the designated field.
  9912. const RecordType *RC = CurrentType->getAs<RecordType>();
  9913. if (!RC)
  9914. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9915. << CurrentType);
  9916. RecordDecl *RD = RC->getDecl();
  9917. // C++ [lib.support.types]p5:
  9918. // The macro offsetof accepts a restricted set of type arguments in this
  9919. // International Standard. type shall be a POD structure or a POD union
  9920. // (clause 9).
  9921. // C++11 [support.types]p4:
  9922. // If type is not a standard-layout class (Clause 9), the results are
  9923. // undefined.
  9924. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9925. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9926. unsigned DiagID =
  9927. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  9928. : diag::ext_offsetof_non_pod_type;
  9929. if (!IsSafe && !DidWarnAboutNonPOD &&
  9930. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  9931. PDiag(DiagID)
  9932. << SourceRange(Components[0].LocStart, OC.LocEnd)
  9933. << CurrentType))
  9934. DidWarnAboutNonPOD = true;
  9935. }
  9936. // Look for the field.
  9937. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  9938. LookupQualifiedName(R, RD);
  9939. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  9940. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  9941. if (!MemberDecl) {
  9942. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  9943. MemberDecl = IndirectMemberDecl->getAnonField();
  9944. }
  9945. if (!MemberDecl)
  9946. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  9947. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  9948. OC.LocEnd));
  9949. // C99 7.17p3:
  9950. // (If the specified member is a bit-field, the behavior is undefined.)
  9951. //
  9952. // We diagnose this as an error.
  9953. if (MemberDecl->isBitField()) {
  9954. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  9955. << MemberDecl->getDeclName()
  9956. << SourceRange(BuiltinLoc, RParenLoc);
  9957. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  9958. return ExprError();
  9959. }
  9960. RecordDecl *Parent = MemberDecl->getParent();
  9961. if (IndirectMemberDecl)
  9962. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  9963. // If the member was found in a base class, introduce OffsetOfNodes for
  9964. // the base class indirections.
  9965. CXXBasePaths Paths;
  9966. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  9967. if (Paths.getDetectedVirtual()) {
  9968. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  9969. << MemberDecl->getDeclName()
  9970. << SourceRange(BuiltinLoc, RParenLoc);
  9971. return ExprError();
  9972. }
  9973. CXXBasePath &Path = Paths.front();
  9974. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  9975. B != BEnd; ++B)
  9976. Comps.push_back(OffsetOfNode(B->Base));
  9977. }
  9978. if (IndirectMemberDecl) {
  9979. for (auto *FI : IndirectMemberDecl->chain()) {
  9980. assert(isa<FieldDecl>(FI));
  9981. Comps.push_back(OffsetOfNode(OC.LocStart,
  9982. cast<FieldDecl>(FI), OC.LocEnd));
  9983. }
  9984. } else
  9985. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  9986. CurrentType = MemberDecl->getType().getNonReferenceType();
  9987. }
  9988. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  9989. Comps, Exprs, RParenLoc);
  9990. }
  9991. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  9992. SourceLocation BuiltinLoc,
  9993. SourceLocation TypeLoc,
  9994. ParsedType ParsedArgTy,
  9995. ArrayRef<OffsetOfComponent> Components,
  9996. SourceLocation RParenLoc) {
  9997. TypeSourceInfo *ArgTInfo;
  9998. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  9999. if (ArgTy.isNull())
  10000. return ExprError();
  10001. if (!ArgTInfo)
  10002. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  10003. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  10004. }
  10005. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  10006. Expr *CondExpr,
  10007. Expr *LHSExpr, Expr *RHSExpr,
  10008. SourceLocation RPLoc) {
  10009. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  10010. ExprValueKind VK = VK_RValue;
  10011. ExprObjectKind OK = OK_Ordinary;
  10012. QualType resType;
  10013. bool ValueDependent = false;
  10014. bool CondIsTrue = false;
  10015. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  10016. resType = Context.DependentTy;
  10017. ValueDependent = true;
  10018. } else {
  10019. // The conditional expression is required to be a constant expression.
  10020. llvm::APSInt condEval(32);
  10021. ExprResult CondICE
  10022. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  10023. diag::err_typecheck_choose_expr_requires_constant, false);
  10024. if (CondICE.isInvalid())
  10025. return ExprError();
  10026. CondExpr = CondICE.get();
  10027. CondIsTrue = condEval.getZExtValue();
  10028. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  10029. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  10030. resType = ActiveExpr->getType();
  10031. ValueDependent = ActiveExpr->isValueDependent();
  10032. VK = ActiveExpr->getValueKind();
  10033. OK = ActiveExpr->getObjectKind();
  10034. }
  10035. return new (Context)
  10036. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  10037. CondIsTrue, resType->isDependentType(), ValueDependent);
  10038. }
  10039. //===----------------------------------------------------------------------===//
  10040. // Clang Extensions.
  10041. //===----------------------------------------------------------------------===//
  10042. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  10043. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  10044. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  10045. if (LangOpts.CPlusPlus) {
  10046. Decl *ManglingContextDecl;
  10047. if (MangleNumberingContext *MCtx =
  10048. getCurrentMangleNumberContext(Block->getDeclContext(),
  10049. ManglingContextDecl)) {
  10050. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  10051. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  10052. }
  10053. }
  10054. PushBlockScope(CurScope, Block);
  10055. CurContext->addDecl(Block);
  10056. if (CurScope)
  10057. PushDeclContext(CurScope, Block);
  10058. else
  10059. CurContext = Block;
  10060. getCurBlock()->HasImplicitReturnType = true;
  10061. // Enter a new evaluation context to insulate the block from any
  10062. // cleanups from the enclosing full-expression.
  10063. PushExpressionEvaluationContext(PotentiallyEvaluated);
  10064. }
  10065. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  10066. Scope *CurScope) {
  10067. assert(ParamInfo.getIdentifier() == nullptr &&
  10068. "block-id should have no identifier!");
  10069. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  10070. BlockScopeInfo *CurBlock = getCurBlock();
  10071. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  10072. QualType T = Sig->getType();
  10073. // FIXME: We should allow unexpanded parameter packs here, but that would,
  10074. // in turn, make the block expression contain unexpanded parameter packs.
  10075. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  10076. // Drop the parameters.
  10077. FunctionProtoType::ExtProtoInfo EPI;
  10078. EPI.HasTrailingReturn = false;
  10079. EPI.TypeQuals |= DeclSpec::TQ_const;
  10080. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  10081. Sig = Context.getTrivialTypeSourceInfo(T);
  10082. }
  10083. // GetTypeForDeclarator always produces a function type for a block
  10084. // literal signature. Furthermore, it is always a FunctionProtoType
  10085. // unless the function was written with a typedef.
  10086. assert(T->isFunctionType() &&
  10087. "GetTypeForDeclarator made a non-function block signature");
  10088. // Look for an explicit signature in that function type.
  10089. FunctionProtoTypeLoc ExplicitSignature;
  10090. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  10091. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  10092. // Check whether that explicit signature was synthesized by
  10093. // GetTypeForDeclarator. If so, don't save that as part of the
  10094. // written signature.
  10095. if (ExplicitSignature.getLocalRangeBegin() ==
  10096. ExplicitSignature.getLocalRangeEnd()) {
  10097. // This would be much cheaper if we stored TypeLocs instead of
  10098. // TypeSourceInfos.
  10099. TypeLoc Result = ExplicitSignature.getReturnLoc();
  10100. unsigned Size = Result.getFullDataSize();
  10101. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  10102. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  10103. ExplicitSignature = FunctionProtoTypeLoc();
  10104. }
  10105. }
  10106. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  10107. CurBlock->FunctionType = T;
  10108. const FunctionType *Fn = T->getAs<FunctionType>();
  10109. QualType RetTy = Fn->getReturnType();
  10110. bool isVariadic =
  10111. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  10112. CurBlock->TheDecl->setIsVariadic(isVariadic);
  10113. // Context.DependentTy is used as a placeholder for a missing block
  10114. // return type. TODO: what should we do with declarators like:
  10115. // ^ * { ... }
  10116. // If the answer is "apply template argument deduction"....
  10117. if (RetTy != Context.DependentTy) {
  10118. CurBlock->ReturnType = RetTy;
  10119. CurBlock->TheDecl->setBlockMissingReturnType(false);
  10120. CurBlock->HasImplicitReturnType = false;
  10121. }
  10122. // Push block parameters from the declarator if we had them.
  10123. SmallVector<ParmVarDecl*, 8> Params;
  10124. if (ExplicitSignature) {
  10125. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  10126. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  10127. if (Param->getIdentifier() == nullptr &&
  10128. !Param->isImplicit() &&
  10129. !Param->isInvalidDecl() &&
  10130. !getLangOpts().CPlusPlus)
  10131. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10132. Params.push_back(Param);
  10133. }
  10134. // Fake up parameter variables if we have a typedef, like
  10135. // ^ fntype { ... }
  10136. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  10137. for (const auto &I : Fn->param_types()) {
  10138. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  10139. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  10140. Params.push_back(Param);
  10141. }
  10142. }
  10143. // Set the parameters on the block decl.
  10144. if (!Params.empty()) {
  10145. CurBlock->TheDecl->setParams(Params);
  10146. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  10147. CurBlock->TheDecl->param_end(),
  10148. /*CheckParameterNames=*/false);
  10149. }
  10150. // Finally we can process decl attributes.
  10151. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  10152. // Put the parameter variables in scope.
  10153. for (auto AI : CurBlock->TheDecl->params()) {
  10154. AI->setOwningFunction(CurBlock->TheDecl);
  10155. // If this has an identifier, add it to the scope stack.
  10156. if (AI->getIdentifier()) {
  10157. CheckShadow(CurBlock->TheScope, AI);
  10158. PushOnScopeChains(AI, CurBlock->TheScope);
  10159. }
  10160. }
  10161. }
  10162. /// ActOnBlockError - If there is an error parsing a block, this callback
  10163. /// is invoked to pop the information about the block from the action impl.
  10164. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  10165. // Leave the expression-evaluation context.
  10166. DiscardCleanupsInEvaluationContext();
  10167. PopExpressionEvaluationContext();
  10168. // Pop off CurBlock, handle nested blocks.
  10169. PopDeclContext();
  10170. PopFunctionScopeInfo();
  10171. }
  10172. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  10173. /// literal was successfully completed. ^(int x){...}
  10174. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  10175. Stmt *Body, Scope *CurScope) {
  10176. // If blocks are disabled, emit an error.
  10177. if (!LangOpts.Blocks)
  10178. Diag(CaretLoc, diag::err_blocks_disable);
  10179. // Leave the expression-evaluation context.
  10180. if (hasAnyUnrecoverableErrorsInThisFunction())
  10181. DiscardCleanupsInEvaluationContext();
  10182. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  10183. PopExpressionEvaluationContext();
  10184. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  10185. if (BSI->HasImplicitReturnType)
  10186. deduceClosureReturnType(*BSI);
  10187. PopDeclContext();
  10188. QualType RetTy = Context.VoidTy;
  10189. if (!BSI->ReturnType.isNull())
  10190. RetTy = BSI->ReturnType;
  10191. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  10192. QualType BlockTy;
  10193. // Set the captured variables on the block.
  10194. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  10195. SmallVector<BlockDecl::Capture, 4> Captures;
  10196. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  10197. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  10198. if (Cap.isThisCapture())
  10199. continue;
  10200. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  10201. Cap.isNested(), Cap.getInitExpr());
  10202. Captures.push_back(NewCap);
  10203. }
  10204. BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  10205. // If the user wrote a function type in some form, try to use that.
  10206. if (!BSI->FunctionType.isNull()) {
  10207. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  10208. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  10209. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  10210. // Turn protoless block types into nullary block types.
  10211. if (isa<FunctionNoProtoType>(FTy)) {
  10212. FunctionProtoType::ExtProtoInfo EPI;
  10213. EPI.ExtInfo = Ext;
  10214. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10215. // Otherwise, if we don't need to change anything about the function type,
  10216. // preserve its sugar structure.
  10217. } else if (FTy->getReturnType() == RetTy &&
  10218. (!NoReturn || FTy->getNoReturnAttr())) {
  10219. BlockTy = BSI->FunctionType;
  10220. // Otherwise, make the minimal modifications to the function type.
  10221. } else {
  10222. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  10223. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10224. EPI.TypeQuals = 0; // FIXME: silently?
  10225. EPI.ExtInfo = Ext;
  10226. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  10227. }
  10228. // If we don't have a function type, just build one from nothing.
  10229. } else {
  10230. FunctionProtoType::ExtProtoInfo EPI;
  10231. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  10232. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10233. }
  10234. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  10235. BSI->TheDecl->param_end());
  10236. BlockTy = Context.getBlockPointerType(BlockTy);
  10237. // If needed, diagnose invalid gotos and switches in the block.
  10238. if (getCurFunction()->NeedsScopeChecking() &&
  10239. !PP.isCodeCompletionEnabled())
  10240. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  10241. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  10242. // Try to apply the named return value optimization. We have to check again
  10243. // if we can do this, though, because blocks keep return statements around
  10244. // to deduce an implicit return type.
  10245. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  10246. !BSI->TheDecl->isDependentContext())
  10247. computeNRVO(Body, BSI);
  10248. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  10249. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10250. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  10251. // If the block isn't obviously global, i.e. it captures anything at
  10252. // all, then we need to do a few things in the surrounding context:
  10253. if (Result->getBlockDecl()->hasCaptures()) {
  10254. // First, this expression has a new cleanup object.
  10255. ExprCleanupObjects.push_back(Result->getBlockDecl());
  10256. ExprNeedsCleanups = true;
  10257. // It also gets a branch-protected scope if any of the captured
  10258. // variables needs destruction.
  10259. for (const auto &CI : Result->getBlockDecl()->captures()) {
  10260. const VarDecl *var = CI.getVariable();
  10261. if (var->getType().isDestructedType() != QualType::DK_none) {
  10262. getCurFunction()->setHasBranchProtectedScope();
  10263. break;
  10264. }
  10265. }
  10266. }
  10267. return Result;
  10268. }
  10269. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  10270. Expr *E, ParsedType Ty,
  10271. SourceLocation RPLoc) {
  10272. TypeSourceInfo *TInfo;
  10273. GetTypeFromParser(Ty, &TInfo);
  10274. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  10275. }
  10276. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  10277. Expr *E, TypeSourceInfo *TInfo,
  10278. SourceLocation RPLoc) {
  10279. Expr *OrigExpr = E;
  10280. bool IsMS = false;
  10281. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  10282. // as Microsoft ABI on an actual Microsoft platform, where
  10283. // __builtin_ms_va_list and __builtin_va_list are the same.)
  10284. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  10285. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  10286. QualType MSVaListType = Context.getBuiltinMSVaListType();
  10287. if (Context.hasSameType(MSVaListType, E->getType())) {
  10288. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10289. return ExprError();
  10290. IsMS = true;
  10291. }
  10292. }
  10293. // Get the va_list type
  10294. QualType VaListType = Context.getBuiltinVaListType();
  10295. if (!IsMS) {
  10296. if (VaListType->isArrayType()) {
  10297. // Deal with implicit array decay; for example, on x86-64,
  10298. // va_list is an array, but it's supposed to decay to
  10299. // a pointer for va_arg.
  10300. VaListType = Context.getArrayDecayedType(VaListType);
  10301. // Make sure the input expression also decays appropriately.
  10302. ExprResult Result = UsualUnaryConversions(E);
  10303. if (Result.isInvalid())
  10304. return ExprError();
  10305. E = Result.get();
  10306. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  10307. // If va_list is a record type and we are compiling in C++ mode,
  10308. // check the argument using reference binding.
  10309. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  10310. Context, Context.getLValueReferenceType(VaListType), false);
  10311. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  10312. if (Init.isInvalid())
  10313. return ExprError();
  10314. E = Init.getAs<Expr>();
  10315. } else {
  10316. // Otherwise, the va_list argument must be an l-value because
  10317. // it is modified by va_arg.
  10318. if (!E->isTypeDependent() &&
  10319. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10320. return ExprError();
  10321. }
  10322. }
  10323. if (!IsMS && !E->isTypeDependent() &&
  10324. !Context.hasSameType(VaListType, E->getType()))
  10325. return ExprError(Diag(E->getLocStart(),
  10326. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  10327. << OrigExpr->getType() << E->getSourceRange());
  10328. if (!TInfo->getType()->isDependentType()) {
  10329. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  10330. diag::err_second_parameter_to_va_arg_incomplete,
  10331. TInfo->getTypeLoc()))
  10332. return ExprError();
  10333. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  10334. TInfo->getType(),
  10335. diag::err_second_parameter_to_va_arg_abstract,
  10336. TInfo->getTypeLoc()))
  10337. return ExprError();
  10338. if (!TInfo->getType().isPODType(Context)) {
  10339. Diag(TInfo->getTypeLoc().getBeginLoc(),
  10340. TInfo->getType()->isObjCLifetimeType()
  10341. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  10342. : diag::warn_second_parameter_to_va_arg_not_pod)
  10343. << TInfo->getType()
  10344. << TInfo->getTypeLoc().getSourceRange();
  10345. }
  10346. // Check for va_arg where arguments of the given type will be promoted
  10347. // (i.e. this va_arg is guaranteed to have undefined behavior).
  10348. QualType PromoteType;
  10349. if (TInfo->getType()->isPromotableIntegerType()) {
  10350. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  10351. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  10352. PromoteType = QualType();
  10353. }
  10354. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  10355. PromoteType = Context.DoubleTy;
  10356. if (!PromoteType.isNull())
  10357. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  10358. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  10359. << TInfo->getType()
  10360. << PromoteType
  10361. << TInfo->getTypeLoc().getSourceRange());
  10362. }
  10363. QualType T = TInfo->getType().getNonLValueExprType(Context);
  10364. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  10365. }
  10366. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  10367. // The type of __null will be int or long, depending on the size of
  10368. // pointers on the target.
  10369. QualType Ty;
  10370. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  10371. if (pw == Context.getTargetInfo().getIntWidth())
  10372. Ty = Context.IntTy;
  10373. else if (pw == Context.getTargetInfo().getLongWidth())
  10374. Ty = Context.LongTy;
  10375. else if (pw == Context.getTargetInfo().getLongLongWidth())
  10376. Ty = Context.LongLongTy;
  10377. else {
  10378. llvm_unreachable("I don't know size of pointer!");
  10379. }
  10380. return new (Context) GNUNullExpr(Ty, TokenLoc);
  10381. }
  10382. bool
  10383. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  10384. if (!getLangOpts().ObjC1)
  10385. return false;
  10386. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  10387. if (!PT)
  10388. return false;
  10389. if (!PT->isObjCIdType()) {
  10390. // Check if the destination is the 'NSString' interface.
  10391. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  10392. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  10393. return false;
  10394. }
  10395. // Ignore any parens, implicit casts (should only be
  10396. // array-to-pointer decays), and not-so-opaque values. The last is
  10397. // important for making this trigger for property assignments.
  10398. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  10399. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  10400. if (OV->getSourceExpr())
  10401. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  10402. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  10403. if (!SL || !SL->isAscii())
  10404. return false;
  10405. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  10406. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  10407. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  10408. return true;
  10409. }
  10410. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  10411. const Expr *SrcExpr) {
  10412. if (!DstType->isFunctionPointerType() ||
  10413. !SrcExpr->getType()->isFunctionType())
  10414. return false;
  10415. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  10416. if (!DRE)
  10417. return false;
  10418. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  10419. if (!FD)
  10420. return false;
  10421. return !S.checkAddressOfFunctionIsAvailable(FD,
  10422. /*Complain=*/true,
  10423. SrcExpr->getLocStart());
  10424. }
  10425. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  10426. SourceLocation Loc,
  10427. QualType DstType, QualType SrcType,
  10428. Expr *SrcExpr, AssignmentAction Action,
  10429. bool *Complained) {
  10430. if (Complained)
  10431. *Complained = false;
  10432. // Decode the result (notice that AST's are still created for extensions).
  10433. bool CheckInferredResultType = false;
  10434. bool isInvalid = false;
  10435. unsigned DiagKind = 0;
  10436. FixItHint Hint;
  10437. ConversionFixItGenerator ConvHints;
  10438. bool MayHaveConvFixit = false;
  10439. bool MayHaveFunctionDiff = false;
  10440. const ObjCInterfaceDecl *IFace = nullptr;
  10441. const ObjCProtocolDecl *PDecl = nullptr;
  10442. switch (ConvTy) {
  10443. case Compatible:
  10444. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  10445. return false;
  10446. case PointerToInt:
  10447. DiagKind = diag::ext_typecheck_convert_pointer_int;
  10448. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10449. MayHaveConvFixit = true;
  10450. break;
  10451. case IntToPointer:
  10452. DiagKind = diag::ext_typecheck_convert_int_pointer;
  10453. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10454. MayHaveConvFixit = true;
  10455. break;
  10456. case IncompatiblePointer:
  10457. DiagKind =
  10458. (Action == AA_Passing_CFAudited ?
  10459. diag::err_arc_typecheck_convert_incompatible_pointer :
  10460. diag::ext_typecheck_convert_incompatible_pointer);
  10461. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  10462. SrcType->isObjCObjectPointerType();
  10463. if (Hint.isNull() && !CheckInferredResultType) {
  10464. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10465. }
  10466. else if (CheckInferredResultType) {
  10467. SrcType = SrcType.getUnqualifiedType();
  10468. DstType = DstType.getUnqualifiedType();
  10469. }
  10470. MayHaveConvFixit = true;
  10471. break;
  10472. case IncompatiblePointerSign:
  10473. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  10474. break;
  10475. case FunctionVoidPointer:
  10476. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  10477. break;
  10478. case IncompatiblePointerDiscardsQualifiers: {
  10479. // Perform array-to-pointer decay if necessary.
  10480. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  10481. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  10482. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  10483. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  10484. DiagKind = diag::err_typecheck_incompatible_address_space;
  10485. break;
  10486. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  10487. DiagKind = diag::err_typecheck_incompatible_ownership;
  10488. break;
  10489. }
  10490. llvm_unreachable("unknown error case for discarding qualifiers!");
  10491. // fallthrough
  10492. }
  10493. case CompatiblePointerDiscardsQualifiers:
  10494. // If the qualifiers lost were because we were applying the
  10495. // (deprecated) C++ conversion from a string literal to a char*
  10496. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  10497. // Ideally, this check would be performed in
  10498. // checkPointerTypesForAssignment. However, that would require a
  10499. // bit of refactoring (so that the second argument is an
  10500. // expression, rather than a type), which should be done as part
  10501. // of a larger effort to fix checkPointerTypesForAssignment for
  10502. // C++ semantics.
  10503. if (getLangOpts().CPlusPlus &&
  10504. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  10505. return false;
  10506. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  10507. break;
  10508. case IncompatibleNestedPointerQualifiers:
  10509. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  10510. break;
  10511. case IntToBlockPointer:
  10512. DiagKind = diag::err_int_to_block_pointer;
  10513. break;
  10514. case IncompatibleBlockPointer:
  10515. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  10516. break;
  10517. case IncompatibleObjCQualifiedId: {
  10518. if (SrcType->isObjCQualifiedIdType()) {
  10519. const ObjCObjectPointerType *srcOPT =
  10520. SrcType->getAs<ObjCObjectPointerType>();
  10521. for (auto *srcProto : srcOPT->quals()) {
  10522. PDecl = srcProto;
  10523. break;
  10524. }
  10525. if (const ObjCInterfaceType *IFaceT =
  10526. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10527. IFace = IFaceT->getDecl();
  10528. }
  10529. else if (DstType->isObjCQualifiedIdType()) {
  10530. const ObjCObjectPointerType *dstOPT =
  10531. DstType->getAs<ObjCObjectPointerType>();
  10532. for (auto *dstProto : dstOPT->quals()) {
  10533. PDecl = dstProto;
  10534. break;
  10535. }
  10536. if (const ObjCInterfaceType *IFaceT =
  10537. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10538. IFace = IFaceT->getDecl();
  10539. }
  10540. DiagKind = diag::warn_incompatible_qualified_id;
  10541. break;
  10542. }
  10543. case IncompatibleVectors:
  10544. DiagKind = diag::warn_incompatible_vectors;
  10545. break;
  10546. case IncompatibleObjCWeakRef:
  10547. DiagKind = diag::err_arc_weak_unavailable_assign;
  10548. break;
  10549. case Incompatible:
  10550. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  10551. if (Complained)
  10552. *Complained = true;
  10553. return true;
  10554. }
  10555. DiagKind = diag::err_typecheck_convert_incompatible;
  10556. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10557. MayHaveConvFixit = true;
  10558. isInvalid = true;
  10559. MayHaveFunctionDiff = true;
  10560. break;
  10561. }
  10562. QualType FirstType, SecondType;
  10563. switch (Action) {
  10564. case AA_Assigning:
  10565. case AA_Initializing:
  10566. // The destination type comes first.
  10567. FirstType = DstType;
  10568. SecondType = SrcType;
  10569. break;
  10570. case AA_Returning:
  10571. case AA_Passing:
  10572. case AA_Passing_CFAudited:
  10573. case AA_Converting:
  10574. case AA_Sending:
  10575. case AA_Casting:
  10576. // The source type comes first.
  10577. FirstType = SrcType;
  10578. SecondType = DstType;
  10579. break;
  10580. }
  10581. PartialDiagnostic FDiag = PDiag(DiagKind);
  10582. if (Action == AA_Passing_CFAudited)
  10583. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10584. else
  10585. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10586. // If we can fix the conversion, suggest the FixIts.
  10587. assert(ConvHints.isNull() || Hint.isNull());
  10588. if (!ConvHints.isNull()) {
  10589. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10590. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10591. FDiag << *HI;
  10592. } else {
  10593. FDiag << Hint;
  10594. }
  10595. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10596. if (MayHaveFunctionDiff)
  10597. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10598. Diag(Loc, FDiag);
  10599. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10600. PDecl && IFace && !IFace->hasDefinition())
  10601. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10602. << IFace->getName() << PDecl->getName();
  10603. if (SecondType == Context.OverloadTy)
  10604. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10605. FirstType, /*TakingAddress=*/true);
  10606. if (CheckInferredResultType)
  10607. EmitRelatedResultTypeNote(SrcExpr);
  10608. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10609. EmitRelatedResultTypeNoteForReturn(DstType);
  10610. if (Complained)
  10611. *Complained = true;
  10612. return isInvalid;
  10613. }
  10614. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10615. llvm::APSInt *Result) {
  10616. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10617. public:
  10618. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10619. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10620. }
  10621. } Diagnoser;
  10622. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10623. }
  10624. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10625. llvm::APSInt *Result,
  10626. unsigned DiagID,
  10627. bool AllowFold) {
  10628. class IDDiagnoser : public VerifyICEDiagnoser {
  10629. unsigned DiagID;
  10630. public:
  10631. IDDiagnoser(unsigned DiagID)
  10632. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10633. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10634. S.Diag(Loc, DiagID) << SR;
  10635. }
  10636. } Diagnoser(DiagID);
  10637. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10638. }
  10639. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10640. SourceRange SR) {
  10641. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10642. }
  10643. ExprResult
  10644. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10645. VerifyICEDiagnoser &Diagnoser,
  10646. bool AllowFold) {
  10647. SourceLocation DiagLoc = E->getLocStart();
  10648. if (getLangOpts().CPlusPlus11) {
  10649. // C++11 [expr.const]p5:
  10650. // If an expression of literal class type is used in a context where an
  10651. // integral constant expression is required, then that class type shall
  10652. // have a single non-explicit conversion function to an integral or
  10653. // unscoped enumeration type
  10654. ExprResult Converted;
  10655. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10656. public:
  10657. CXX11ConvertDiagnoser(bool Silent)
  10658. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10659. Silent, true) {}
  10660. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10661. QualType T) override {
  10662. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10663. }
  10664. SemaDiagnosticBuilder diagnoseIncomplete(
  10665. Sema &S, SourceLocation Loc, QualType T) override {
  10666. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10667. }
  10668. SemaDiagnosticBuilder diagnoseExplicitConv(
  10669. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10670. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10671. }
  10672. SemaDiagnosticBuilder noteExplicitConv(
  10673. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10674. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10675. << ConvTy->isEnumeralType() << ConvTy;
  10676. }
  10677. SemaDiagnosticBuilder diagnoseAmbiguous(
  10678. Sema &S, SourceLocation Loc, QualType T) override {
  10679. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10680. }
  10681. SemaDiagnosticBuilder noteAmbiguous(
  10682. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10683. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10684. << ConvTy->isEnumeralType() << ConvTy;
  10685. }
  10686. SemaDiagnosticBuilder diagnoseConversion(
  10687. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10688. llvm_unreachable("conversion functions are permitted");
  10689. }
  10690. } ConvertDiagnoser(Diagnoser.Suppress);
  10691. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10692. ConvertDiagnoser);
  10693. if (Converted.isInvalid())
  10694. return Converted;
  10695. E = Converted.get();
  10696. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10697. return ExprError();
  10698. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10699. // An ICE must be of integral or unscoped enumeration type.
  10700. if (!Diagnoser.Suppress)
  10701. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10702. return ExprError();
  10703. }
  10704. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10705. // in the non-ICE case.
  10706. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10707. if (Result)
  10708. *Result = E->EvaluateKnownConstInt(Context);
  10709. return E;
  10710. }
  10711. Expr::EvalResult EvalResult;
  10712. SmallVector<PartialDiagnosticAt, 8> Notes;
  10713. EvalResult.Diag = &Notes;
  10714. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10715. // not a constant expression as a side-effect.
  10716. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10717. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10718. // In C++11, we can rely on diagnostics being produced for any expression
  10719. // which is not a constant expression. If no diagnostics were produced, then
  10720. // this is a constant expression.
  10721. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10722. if (Result)
  10723. *Result = EvalResult.Val.getInt();
  10724. return E;
  10725. }
  10726. // If our only note is the usual "invalid subexpression" note, just point
  10727. // the caret at its location rather than producing an essentially
  10728. // redundant note.
  10729. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10730. diag::note_invalid_subexpr_in_const_expr) {
  10731. DiagLoc = Notes[0].first;
  10732. Notes.clear();
  10733. }
  10734. if (!Folded || !AllowFold) {
  10735. if (!Diagnoser.Suppress) {
  10736. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10737. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10738. Diag(Notes[I].first, Notes[I].second);
  10739. }
  10740. return ExprError();
  10741. }
  10742. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10743. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10744. Diag(Notes[I].first, Notes[I].second);
  10745. if (Result)
  10746. *Result = EvalResult.Val.getInt();
  10747. return E;
  10748. }
  10749. namespace {
  10750. // Handle the case where we conclude a expression which we speculatively
  10751. // considered to be unevaluated is actually evaluated.
  10752. class TransformToPE : public TreeTransform<TransformToPE> {
  10753. typedef TreeTransform<TransformToPE> BaseTransform;
  10754. public:
  10755. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10756. // Make sure we redo semantic analysis
  10757. bool AlwaysRebuild() { return true; }
  10758. // Make sure we handle LabelStmts correctly.
  10759. // FIXME: This does the right thing, but maybe we need a more general
  10760. // fix to TreeTransform?
  10761. StmtResult TransformLabelStmt(LabelStmt *S) {
  10762. S->getDecl()->setStmt(nullptr);
  10763. return BaseTransform::TransformLabelStmt(S);
  10764. }
  10765. // We need to special-case DeclRefExprs referring to FieldDecls which
  10766. // are not part of a member pointer formation; normal TreeTransforming
  10767. // doesn't catch this case because of the way we represent them in the AST.
  10768. // FIXME: This is a bit ugly; is it really the best way to handle this
  10769. // case?
  10770. //
  10771. // Error on DeclRefExprs referring to FieldDecls.
  10772. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10773. if (isa<FieldDecl>(E->getDecl()) &&
  10774. !SemaRef.isUnevaluatedContext())
  10775. return SemaRef.Diag(E->getLocation(),
  10776. diag::err_invalid_non_static_member_use)
  10777. << E->getDecl() << E->getSourceRange();
  10778. return BaseTransform::TransformDeclRefExpr(E);
  10779. }
  10780. // Exception: filter out member pointer formation
  10781. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10782. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10783. return E;
  10784. return BaseTransform::TransformUnaryOperator(E);
  10785. }
  10786. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10787. // Lambdas never need to be transformed.
  10788. return E;
  10789. }
  10790. };
  10791. }
  10792. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10793. assert(isUnevaluatedContext() &&
  10794. "Should only transform unevaluated expressions");
  10795. ExprEvalContexts.back().Context =
  10796. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10797. if (isUnevaluatedContext())
  10798. return E;
  10799. return TransformToPE(*this).TransformExpr(E);
  10800. }
  10801. void
  10802. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10803. Decl *LambdaContextDecl,
  10804. bool IsDecltype) {
  10805. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10806. ExprNeedsCleanups, LambdaContextDecl,
  10807. IsDecltype);
  10808. ExprNeedsCleanups = false;
  10809. if (!MaybeODRUseExprs.empty())
  10810. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10811. }
  10812. void
  10813. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10814. ReuseLambdaContextDecl_t,
  10815. bool IsDecltype) {
  10816. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10817. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10818. }
  10819. void Sema::PopExpressionEvaluationContext() {
  10820. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10821. unsigned NumTypos = Rec.NumTypos;
  10822. if (!Rec.Lambdas.empty()) {
  10823. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10824. unsigned D;
  10825. if (Rec.isUnevaluated()) {
  10826. // C++11 [expr.prim.lambda]p2:
  10827. // A lambda-expression shall not appear in an unevaluated operand
  10828. // (Clause 5).
  10829. D = diag::err_lambda_unevaluated_operand;
  10830. } else {
  10831. // C++1y [expr.const]p2:
  10832. // A conditional-expression e is a core constant expression unless the
  10833. // evaluation of e, following the rules of the abstract machine, would
  10834. // evaluate [...] a lambda-expression.
  10835. D = diag::err_lambda_in_constant_expression;
  10836. }
  10837. for (const auto *L : Rec.Lambdas)
  10838. Diag(L->getLocStart(), D);
  10839. } else {
  10840. // Mark the capture expressions odr-used. This was deferred
  10841. // during lambda expression creation.
  10842. for (auto *Lambda : Rec.Lambdas) {
  10843. for (auto *C : Lambda->capture_inits())
  10844. MarkDeclarationsReferencedInExpr(C);
  10845. }
  10846. }
  10847. }
  10848. // When are coming out of an unevaluated context, clear out any
  10849. // temporaries that we may have created as part of the evaluation of
  10850. // the expression in that context: they aren't relevant because they
  10851. // will never be constructed.
  10852. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10853. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10854. ExprCleanupObjects.end());
  10855. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10856. CleanupVarDeclMarking();
  10857. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10858. // Otherwise, merge the contexts together.
  10859. } else {
  10860. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10861. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10862. Rec.SavedMaybeODRUseExprs.end());
  10863. }
  10864. // Pop the current expression evaluation context off the stack.
  10865. ExprEvalContexts.pop_back();
  10866. if (!ExprEvalContexts.empty())
  10867. ExprEvalContexts.back().NumTypos += NumTypos;
  10868. else
  10869. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10870. "last ExpressionEvaluationContextRecord");
  10871. }
  10872. void Sema::DiscardCleanupsInEvaluationContext() {
  10873. ExprCleanupObjects.erase(
  10874. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10875. ExprCleanupObjects.end());
  10876. ExprNeedsCleanups = false;
  10877. MaybeODRUseExprs.clear();
  10878. }
  10879. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10880. if (!E->getType()->isVariablyModifiedType())
  10881. return E;
  10882. return TransformToPotentiallyEvaluated(E);
  10883. }
  10884. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10885. // Do not mark anything as "used" within a dependent context; wait for
  10886. // an instantiation.
  10887. if (SemaRef.CurContext->isDependentContext())
  10888. return false;
  10889. switch (SemaRef.ExprEvalContexts.back().Context) {
  10890. case Sema::Unevaluated:
  10891. case Sema::UnevaluatedAbstract:
  10892. // We are in an expression that is not potentially evaluated; do nothing.
  10893. // (Depending on how you read the standard, we actually do need to do
  10894. // something here for null pointer constants, but the standard's
  10895. // definition of a null pointer constant is completely crazy.)
  10896. return false;
  10897. case Sema::ConstantEvaluated:
  10898. case Sema::PotentiallyEvaluated:
  10899. // We are in a potentially evaluated expression (or a constant-expression
  10900. // in C++03); we need to do implicit template instantiation, implicitly
  10901. // define class members, and mark most declarations as used.
  10902. return true;
  10903. case Sema::PotentiallyEvaluatedIfUsed:
  10904. // Referenced declarations will only be used if the construct in the
  10905. // containing expression is used.
  10906. return false;
  10907. }
  10908. llvm_unreachable("Invalid context");
  10909. }
  10910. /// \brief Mark a function referenced, and check whether it is odr-used
  10911. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10912. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10913. bool OdrUse) {
  10914. assert(Func && "No function?");
  10915. Func->setReferenced();
  10916. // C++11 [basic.def.odr]p3:
  10917. // A function whose name appears as a potentially-evaluated expression is
  10918. // odr-used if it is the unique lookup result or the selected member of a
  10919. // set of overloaded functions [...].
  10920. //
  10921. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10922. // can just check that here. Skip the rest of this function if we've already
  10923. // marked the function as used.
  10924. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10925. !IsPotentiallyEvaluatedContext(*this)) {
  10926. // C++11 [temp.inst]p3:
  10927. // Unless a function template specialization has been explicitly
  10928. // instantiated or explicitly specialized, the function template
  10929. // specialization is implicitly instantiated when the specialization is
  10930. // referenced in a context that requires a function definition to exist.
  10931. //
  10932. // We consider constexpr function templates to be referenced in a context
  10933. // that requires a definition to exist whenever they are referenced.
  10934. //
  10935. // FIXME: This instantiates constexpr functions too frequently. If this is
  10936. // really an unevaluated context (and we're not just in the definition of a
  10937. // function template or overload resolution or other cases which we
  10938. // incorrectly consider to be unevaluated contexts), and we're not in a
  10939. // subexpression which we actually need to evaluate (for instance, a
  10940. // template argument, array bound or an expression in a braced-init-list),
  10941. // we are not permitted to instantiate this constexpr function definition.
  10942. //
  10943. // FIXME: This also implicitly defines special members too frequently. They
  10944. // are only supposed to be implicitly defined if they are odr-used, but they
  10945. // are not odr-used from constant expressions in unevaluated contexts.
  10946. // However, they cannot be referenced if they are deleted, and they are
  10947. // deleted whenever the implicit definition of the special member would
  10948. // fail.
  10949. if (!Func->isConstexpr() || Func->getBody())
  10950. return;
  10951. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  10952. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  10953. return;
  10954. }
  10955. // Note that this declaration has been used.
  10956. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  10957. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  10958. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  10959. if (Constructor->isDefaultConstructor()) {
  10960. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  10961. return;
  10962. DefineImplicitDefaultConstructor(Loc, Constructor);
  10963. } else if (Constructor->isCopyConstructor()) {
  10964. DefineImplicitCopyConstructor(Loc, Constructor);
  10965. } else if (Constructor->isMoveConstructor()) {
  10966. DefineImplicitMoveConstructor(Loc, Constructor);
  10967. }
  10968. } else if (Constructor->getInheritedConstructor()) {
  10969. DefineInheritingConstructor(Loc, Constructor);
  10970. }
  10971. } else if (CXXDestructorDecl *Destructor =
  10972. dyn_cast<CXXDestructorDecl>(Func)) {
  10973. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  10974. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  10975. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  10976. return;
  10977. DefineImplicitDestructor(Loc, Destructor);
  10978. }
  10979. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  10980. MarkVTableUsed(Loc, Destructor->getParent());
  10981. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  10982. if (MethodDecl->isOverloadedOperator() &&
  10983. MethodDecl->getOverloadedOperator() == OO_Equal) {
  10984. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  10985. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  10986. if (MethodDecl->isCopyAssignmentOperator())
  10987. DefineImplicitCopyAssignment(Loc, MethodDecl);
  10988. else
  10989. DefineImplicitMoveAssignment(Loc, MethodDecl);
  10990. }
  10991. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  10992. MethodDecl->getParent()->isLambda()) {
  10993. CXXConversionDecl *Conversion =
  10994. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  10995. if (Conversion->isLambdaToBlockPointerConversion())
  10996. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  10997. else
  10998. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  10999. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  11000. MarkVTableUsed(Loc, MethodDecl->getParent());
  11001. }
  11002. // Recursive functions should be marked when used from another function.
  11003. // FIXME: Is this really right?
  11004. if (CurContext == Func) return;
  11005. // Resolve the exception specification for any function which is
  11006. // used: CodeGen will need it.
  11007. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  11008. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  11009. ResolveExceptionSpec(Loc, FPT);
  11010. if (!OdrUse) return;
  11011. // Implicit instantiation of function templates and member functions of
  11012. // class templates.
  11013. if (Func->isImplicitlyInstantiable()) {
  11014. bool AlreadyInstantiated = false;
  11015. SourceLocation PointOfInstantiation = Loc;
  11016. if (FunctionTemplateSpecializationInfo *SpecInfo
  11017. = Func->getTemplateSpecializationInfo()) {
  11018. if (SpecInfo->getPointOfInstantiation().isInvalid())
  11019. SpecInfo->setPointOfInstantiation(Loc);
  11020. else if (SpecInfo->getTemplateSpecializationKind()
  11021. == TSK_ImplicitInstantiation) {
  11022. AlreadyInstantiated = true;
  11023. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  11024. }
  11025. } else if (MemberSpecializationInfo *MSInfo
  11026. = Func->getMemberSpecializationInfo()) {
  11027. if (MSInfo->getPointOfInstantiation().isInvalid())
  11028. MSInfo->setPointOfInstantiation(Loc);
  11029. else if (MSInfo->getTemplateSpecializationKind()
  11030. == TSK_ImplicitInstantiation) {
  11031. AlreadyInstantiated = true;
  11032. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  11033. }
  11034. }
  11035. if (!AlreadyInstantiated || Func->isConstexpr()) {
  11036. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  11037. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  11038. ActiveTemplateInstantiations.size())
  11039. PendingLocalImplicitInstantiations.push_back(
  11040. std::make_pair(Func, PointOfInstantiation));
  11041. else if (Func->isConstexpr())
  11042. // Do not defer instantiations of constexpr functions, to avoid the
  11043. // expression evaluator needing to call back into Sema if it sees a
  11044. // call to such a function.
  11045. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  11046. else {
  11047. PendingInstantiations.push_back(std::make_pair(Func,
  11048. PointOfInstantiation));
  11049. // Notify the consumer that a function was implicitly instantiated.
  11050. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  11051. }
  11052. }
  11053. } else {
  11054. // Walk redefinitions, as some of them may be instantiable.
  11055. for (auto i : Func->redecls()) {
  11056. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  11057. MarkFunctionReferenced(Loc, i);
  11058. }
  11059. }
  11060. // Keep track of used but undefined functions.
  11061. if (!Func->isDefined()) {
  11062. if (mightHaveNonExternalLinkage(Func))
  11063. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11064. else if (Func->getMostRecentDecl()->isInlined() &&
  11065. !LangOpts.GNUInline &&
  11066. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  11067. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11068. }
  11069. // Normally the most current decl is marked used while processing the use and
  11070. // any subsequent decls are marked used by decl merging. This fails with
  11071. // template instantiation since marking can happen at the end of the file
  11072. // and, because of the two phase lookup, this function is called with at
  11073. // decl in the middle of a decl chain. We loop to maintain the invariant
  11074. // that once a decl is used, all decls after it are also used.
  11075. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  11076. F->markUsed(Context);
  11077. if (F == Func)
  11078. break;
  11079. }
  11080. }
  11081. static void
  11082. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  11083. VarDecl *var, DeclContext *DC) {
  11084. DeclContext *VarDC = var->getDeclContext();
  11085. // If the parameter still belongs to the translation unit, then
  11086. // we're actually just using one parameter in the declaration of
  11087. // the next.
  11088. if (isa<ParmVarDecl>(var) &&
  11089. isa<TranslationUnitDecl>(VarDC))
  11090. return;
  11091. // For C code, don't diagnose about capture if we're not actually in code
  11092. // right now; it's impossible to write a non-constant expression outside of
  11093. // function context, so we'll get other (more useful) diagnostics later.
  11094. //
  11095. // For C++, things get a bit more nasty... it would be nice to suppress this
  11096. // diagnostic for certain cases like using a local variable in an array bound
  11097. // for a member of a local class, but the correct predicate is not obvious.
  11098. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  11099. return;
  11100. if (isa<CXXMethodDecl>(VarDC) &&
  11101. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  11102. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  11103. << var->getIdentifier();
  11104. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  11105. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  11106. << var->getIdentifier() << fn->getDeclName();
  11107. } else if (isa<BlockDecl>(VarDC)) {
  11108. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  11109. << var->getIdentifier();
  11110. } else {
  11111. // FIXME: Is there any other context where a local variable can be
  11112. // declared?
  11113. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  11114. << var->getIdentifier();
  11115. }
  11116. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  11117. << var->getIdentifier();
  11118. // FIXME: Add additional diagnostic info about class etc. which prevents
  11119. // capture.
  11120. }
  11121. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  11122. bool &SubCapturesAreNested,
  11123. QualType &CaptureType,
  11124. QualType &DeclRefType) {
  11125. // Check whether we've already captured it.
  11126. if (CSI->CaptureMap.count(Var)) {
  11127. // If we found a capture, any subcaptures are nested.
  11128. SubCapturesAreNested = true;
  11129. // Retrieve the capture type for this variable.
  11130. CaptureType = CSI->getCapture(Var).getCaptureType();
  11131. // Compute the type of an expression that refers to this variable.
  11132. DeclRefType = CaptureType.getNonReferenceType();
  11133. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  11134. // are mutable in the sense that user can change their value - they are
  11135. // private instances of the captured declarations.
  11136. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  11137. if (Cap.isCopyCapture() &&
  11138. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  11139. !(isa<CapturedRegionScopeInfo>(CSI) &&
  11140. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  11141. DeclRefType.addConst();
  11142. return true;
  11143. }
  11144. return false;
  11145. }
  11146. // Only block literals, captured statements, and lambda expressions can
  11147. // capture; other scopes don't work.
  11148. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  11149. SourceLocation Loc,
  11150. const bool Diagnose, Sema &S) {
  11151. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  11152. return getLambdaAwareParentOfDeclContext(DC);
  11153. else if (Var->hasLocalStorage()) {
  11154. if (Diagnose)
  11155. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  11156. }
  11157. return nullptr;
  11158. }
  11159. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11160. // certain types of variables (unnamed, variably modified types etc.)
  11161. // so check for eligibility.
  11162. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  11163. SourceLocation Loc,
  11164. const bool Diagnose, Sema &S) {
  11165. bool IsBlock = isa<BlockScopeInfo>(CSI);
  11166. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  11167. // Lambdas are not allowed to capture unnamed variables
  11168. // (e.g. anonymous unions).
  11169. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  11170. // assuming that's the intent.
  11171. if (IsLambda && !Var->getDeclName()) {
  11172. if (Diagnose) {
  11173. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  11174. S.Diag(Var->getLocation(), diag::note_declared_at);
  11175. }
  11176. return false;
  11177. }
  11178. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  11179. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  11180. if (Diagnose) {
  11181. S.Diag(Loc, diag::err_ref_vm_type);
  11182. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11183. << Var->getDeclName();
  11184. }
  11185. return false;
  11186. }
  11187. // Prohibit structs with flexible array members too.
  11188. // We cannot capture what is in the tail end of the struct.
  11189. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  11190. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  11191. if (Diagnose) {
  11192. if (IsBlock)
  11193. S.Diag(Loc, diag::err_ref_flexarray_type);
  11194. else
  11195. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  11196. << Var->getDeclName();
  11197. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11198. << Var->getDeclName();
  11199. }
  11200. return false;
  11201. }
  11202. }
  11203. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11204. // Lambdas and captured statements are not allowed to capture __block
  11205. // variables; they don't support the expected semantics.
  11206. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  11207. if (Diagnose) {
  11208. S.Diag(Loc, diag::err_capture_block_variable)
  11209. << Var->getDeclName() << !IsLambda;
  11210. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11211. << Var->getDeclName();
  11212. }
  11213. return false;
  11214. }
  11215. return true;
  11216. }
  11217. // Returns true if the capture by block was successful.
  11218. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  11219. SourceLocation Loc,
  11220. const bool BuildAndDiagnose,
  11221. QualType &CaptureType,
  11222. QualType &DeclRefType,
  11223. const bool Nested,
  11224. Sema &S) {
  11225. Expr *CopyExpr = nullptr;
  11226. bool ByRef = false;
  11227. // Blocks are not allowed to capture arrays.
  11228. if (CaptureType->isArrayType()) {
  11229. if (BuildAndDiagnose) {
  11230. S.Diag(Loc, diag::err_ref_array_type);
  11231. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11232. << Var->getDeclName();
  11233. }
  11234. return false;
  11235. }
  11236. // Forbid the block-capture of autoreleasing variables.
  11237. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11238. if (BuildAndDiagnose) {
  11239. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  11240. << /*block*/ 0;
  11241. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11242. << Var->getDeclName();
  11243. }
  11244. return false;
  11245. }
  11246. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11247. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  11248. // Block capture by reference does not change the capture or
  11249. // declaration reference types.
  11250. ByRef = true;
  11251. } else {
  11252. // Block capture by copy introduces 'const'.
  11253. CaptureType = CaptureType.getNonReferenceType().withConst();
  11254. DeclRefType = CaptureType;
  11255. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  11256. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  11257. // The capture logic needs the destructor, so make sure we mark it.
  11258. // Usually this is unnecessary because most local variables have
  11259. // their destructors marked at declaration time, but parameters are
  11260. // an exception because it's technically only the call site that
  11261. // actually requires the destructor.
  11262. if (isa<ParmVarDecl>(Var))
  11263. S.FinalizeVarWithDestructor(Var, Record);
  11264. // Enter a new evaluation context to insulate the copy
  11265. // full-expression.
  11266. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  11267. // According to the blocks spec, the capture of a variable from
  11268. // the stack requires a const copy constructor. This is not true
  11269. // of the copy/move done to move a __block variable to the heap.
  11270. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  11271. DeclRefType.withConst(),
  11272. VK_LValue, Loc);
  11273. ExprResult Result
  11274. = S.PerformCopyInitialization(
  11275. InitializedEntity::InitializeBlock(Var->getLocation(),
  11276. CaptureType, false),
  11277. Loc, DeclRef);
  11278. // Build a full-expression copy expression if initialization
  11279. // succeeded and used a non-trivial constructor. Recover from
  11280. // errors by pretending that the copy isn't necessary.
  11281. if (!Result.isInvalid() &&
  11282. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  11283. ->isTrivial()) {
  11284. Result = S.MaybeCreateExprWithCleanups(Result);
  11285. CopyExpr = Result.get();
  11286. }
  11287. }
  11288. }
  11289. }
  11290. // Actually capture the variable.
  11291. if (BuildAndDiagnose)
  11292. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  11293. SourceLocation(), CaptureType, CopyExpr);
  11294. return true;
  11295. }
  11296. /// \brief Capture the given variable in the captured region.
  11297. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  11298. VarDecl *Var,
  11299. SourceLocation Loc,
  11300. const bool BuildAndDiagnose,
  11301. QualType &CaptureType,
  11302. QualType &DeclRefType,
  11303. const bool RefersToCapturedVariable,
  11304. Sema &S) {
  11305. // By default, capture variables by reference.
  11306. bool ByRef = true;
  11307. // Using an LValue reference type is consistent with Lambdas (see below).
  11308. if (S.getLangOpts().OpenMP) {
  11309. ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
  11310. if (S.IsOpenMPCapturedVar(Var))
  11311. DeclRefType = DeclRefType.getUnqualifiedType();
  11312. }
  11313. if (ByRef)
  11314. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11315. else
  11316. CaptureType = DeclRefType;
  11317. Expr *CopyExpr = nullptr;
  11318. if (BuildAndDiagnose) {
  11319. // The current implementation assumes that all variables are captured
  11320. // by references. Since there is no capture by copy, no expression
  11321. // evaluation will be needed.
  11322. RecordDecl *RD = RSI->TheRecordDecl;
  11323. FieldDecl *Field
  11324. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  11325. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  11326. nullptr, false, ICIS_NoInit);
  11327. Field->setImplicit(true);
  11328. Field->setAccess(AS_private);
  11329. RD->addDecl(Field);
  11330. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  11331. DeclRefType, VK_LValue, Loc);
  11332. Var->setReferenced(true);
  11333. Var->markUsed(S.Context);
  11334. }
  11335. // Actually capture the variable.
  11336. if (BuildAndDiagnose)
  11337. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  11338. SourceLocation(), CaptureType, CopyExpr);
  11339. return true;
  11340. }
  11341. /// \brief Create a field within the lambda class for the variable
  11342. /// being captured.
  11343. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
  11344. QualType FieldType, QualType DeclRefType,
  11345. SourceLocation Loc,
  11346. bool RefersToCapturedVariable) {
  11347. CXXRecordDecl *Lambda = LSI->Lambda;
  11348. // Build the non-static data member.
  11349. FieldDecl *Field
  11350. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  11351. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  11352. nullptr, false, ICIS_NoInit);
  11353. Field->setImplicit(true);
  11354. Field->setAccess(AS_private);
  11355. Lambda->addDecl(Field);
  11356. }
  11357. /// \brief Capture the given variable in the lambda.
  11358. static bool captureInLambda(LambdaScopeInfo *LSI,
  11359. VarDecl *Var,
  11360. SourceLocation Loc,
  11361. const bool BuildAndDiagnose,
  11362. QualType &CaptureType,
  11363. QualType &DeclRefType,
  11364. const bool RefersToCapturedVariable,
  11365. const Sema::TryCaptureKind Kind,
  11366. SourceLocation EllipsisLoc,
  11367. const bool IsTopScope,
  11368. Sema &S) {
  11369. // Determine whether we are capturing by reference or by value.
  11370. bool ByRef = false;
  11371. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  11372. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  11373. } else {
  11374. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  11375. }
  11376. // Compute the type of the field that will capture this variable.
  11377. if (ByRef) {
  11378. // C++11 [expr.prim.lambda]p15:
  11379. // An entity is captured by reference if it is implicitly or
  11380. // explicitly captured but not captured by copy. It is
  11381. // unspecified whether additional unnamed non-static data
  11382. // members are declared in the closure type for entities
  11383. // captured by reference.
  11384. //
  11385. // FIXME: It is not clear whether we want to build an lvalue reference
  11386. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  11387. // to do the former, while EDG does the latter. Core issue 1249 will
  11388. // clarify, but for now we follow GCC because it's a more permissive and
  11389. // easily defensible position.
  11390. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11391. } else {
  11392. // C++11 [expr.prim.lambda]p14:
  11393. // For each entity captured by copy, an unnamed non-static
  11394. // data member is declared in the closure type. The
  11395. // declaration order of these members is unspecified. The type
  11396. // of such a data member is the type of the corresponding
  11397. // captured entity if the entity is not a reference to an
  11398. // object, or the referenced type otherwise. [Note: If the
  11399. // captured entity is a reference to a function, the
  11400. // corresponding data member is also a reference to a
  11401. // function. - end note ]
  11402. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  11403. if (!RefType->getPointeeType()->isFunctionType())
  11404. CaptureType = RefType->getPointeeType();
  11405. }
  11406. // Forbid the lambda copy-capture of autoreleasing variables.
  11407. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11408. if (BuildAndDiagnose) {
  11409. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  11410. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11411. << Var->getDeclName();
  11412. }
  11413. return false;
  11414. }
  11415. // Make sure that by-copy captures are of a complete and non-abstract type.
  11416. if (BuildAndDiagnose) {
  11417. if (!CaptureType->isDependentType() &&
  11418. S.RequireCompleteType(Loc, CaptureType,
  11419. diag::err_capture_of_incomplete_type,
  11420. Var->getDeclName()))
  11421. return false;
  11422. if (S.RequireNonAbstractType(Loc, CaptureType,
  11423. diag::err_capture_of_abstract_type))
  11424. return false;
  11425. }
  11426. }
  11427. // Capture this variable in the lambda.
  11428. if (BuildAndDiagnose)
  11429. addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
  11430. RefersToCapturedVariable);
  11431. // Compute the type of a reference to this captured variable.
  11432. if (ByRef)
  11433. DeclRefType = CaptureType.getNonReferenceType();
  11434. else {
  11435. // C++ [expr.prim.lambda]p5:
  11436. // The closure type for a lambda-expression has a public inline
  11437. // function call operator [...]. This function call operator is
  11438. // declared const (9.3.1) if and only if the lambda-expression’s
  11439. // parameter-declaration-clause is not followed by mutable.
  11440. DeclRefType = CaptureType.getNonReferenceType();
  11441. if (!LSI->Mutable && !CaptureType->isReferenceType())
  11442. DeclRefType.addConst();
  11443. }
  11444. // Add the capture.
  11445. if (BuildAndDiagnose)
  11446. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  11447. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  11448. return true;
  11449. }
  11450. bool Sema::tryCaptureVariable(
  11451. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  11452. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  11453. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  11454. // An init-capture is notionally from the context surrounding its
  11455. // declaration, but its parent DC is the lambda class.
  11456. DeclContext *VarDC = Var->getDeclContext();
  11457. if (Var->isInitCapture())
  11458. VarDC = VarDC->getParent();
  11459. DeclContext *DC = CurContext;
  11460. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  11461. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  11462. // We need to sync up the Declaration Context with the
  11463. // FunctionScopeIndexToStopAt
  11464. if (FunctionScopeIndexToStopAt) {
  11465. unsigned FSIndex = FunctionScopes.size() - 1;
  11466. while (FSIndex != MaxFunctionScopesIndex) {
  11467. DC = getLambdaAwareParentOfDeclContext(DC);
  11468. --FSIndex;
  11469. }
  11470. }
  11471. // If the variable is declared in the current context, there is no need to
  11472. // capture it.
  11473. if (VarDC == DC) return true;
  11474. // Capture global variables if it is required to use private copy of this
  11475. // variable.
  11476. bool IsGlobal = !Var->hasLocalStorage();
  11477. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  11478. return true;
  11479. // Walk up the stack to determine whether we can capture the variable,
  11480. // performing the "simple" checks that don't depend on type. We stop when
  11481. // we've either hit the declared scope of the variable or find an existing
  11482. // capture of that variable. We start from the innermost capturing-entity
  11483. // (the DC) and ensure that all intervening capturing-entities
  11484. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  11485. // declcontext can either capture the variable or have already captured
  11486. // the variable.
  11487. CaptureType = Var->getType();
  11488. DeclRefType = CaptureType.getNonReferenceType();
  11489. bool Nested = false;
  11490. bool Explicit = (Kind != TryCapture_Implicit);
  11491. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  11492. unsigned OpenMPLevel = 0;
  11493. do {
  11494. // Only block literals, captured statements, and lambda expressions can
  11495. // capture; other scopes don't work.
  11496. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11497. ExprLoc,
  11498. BuildAndDiagnose,
  11499. *this);
  11500. // We need to check for the parent *first* because, if we *have*
  11501. // private-captured a global variable, we need to recursively capture it in
  11502. // intermediate blocks, lambdas, etc.
  11503. if (!ParentDC) {
  11504. if (IsGlobal) {
  11505. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11506. break;
  11507. }
  11508. return true;
  11509. }
  11510. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11511. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11512. // Check whether we've already captured it.
  11513. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11514. DeclRefType))
  11515. break;
  11516. // If we are instantiating a generic lambda call operator body,
  11517. // we do not want to capture new variables. What was captured
  11518. // during either a lambdas transformation or initial parsing
  11519. // should be used.
  11520. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11521. if (BuildAndDiagnose) {
  11522. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11523. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11524. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11525. Diag(Var->getLocation(), diag::note_previous_decl)
  11526. << Var->getDeclName();
  11527. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11528. } else
  11529. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11530. }
  11531. return true;
  11532. }
  11533. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11534. // certain types of variables (unnamed, variably modified types etc.)
  11535. // so check for eligibility.
  11536. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11537. return true;
  11538. // Try to capture variable-length arrays types.
  11539. if (Var->getType()->isVariablyModifiedType()) {
  11540. // We're going to walk down into the type and look for VLA
  11541. // expressions.
  11542. QualType QTy = Var->getType();
  11543. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11544. QTy = PVD->getOriginalType();
  11545. do {
  11546. const Type *Ty = QTy.getTypePtr();
  11547. switch (Ty->getTypeClass()) {
  11548. #define TYPE(Class, Base)
  11549. #define ABSTRACT_TYPE(Class, Base)
  11550. #define NON_CANONICAL_TYPE(Class, Base)
  11551. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11552. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11553. #include "clang/AST/TypeNodes.def"
  11554. QTy = QualType();
  11555. break;
  11556. // These types are never variably-modified.
  11557. case Type::Builtin:
  11558. case Type::Complex:
  11559. case Type::Vector:
  11560. case Type::ExtVector:
  11561. case Type::Record:
  11562. case Type::Enum:
  11563. case Type::Elaborated:
  11564. case Type::TemplateSpecialization:
  11565. case Type::ObjCObject:
  11566. case Type::ObjCInterface:
  11567. case Type::ObjCObjectPointer:
  11568. llvm_unreachable("type class is never variably-modified!");
  11569. case Type::Adjusted:
  11570. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11571. break;
  11572. case Type::Decayed:
  11573. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11574. break;
  11575. case Type::Pointer:
  11576. QTy = cast<PointerType>(Ty)->getPointeeType();
  11577. break;
  11578. case Type::BlockPointer:
  11579. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11580. break;
  11581. case Type::LValueReference:
  11582. case Type::RValueReference:
  11583. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11584. break;
  11585. case Type::MemberPointer:
  11586. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11587. break;
  11588. case Type::ConstantArray:
  11589. case Type::IncompleteArray:
  11590. // Losing element qualification here is fine.
  11591. QTy = cast<ArrayType>(Ty)->getElementType();
  11592. break;
  11593. case Type::VariableArray: {
  11594. // Losing element qualification here is fine.
  11595. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11596. // Unknown size indication requires no size computation.
  11597. // Otherwise, evaluate and record it.
  11598. if (auto Size = VAT->getSizeExpr()) {
  11599. if (!CSI->isVLATypeCaptured(VAT)) {
  11600. RecordDecl *CapRecord = nullptr;
  11601. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11602. CapRecord = LSI->Lambda;
  11603. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11604. CapRecord = CRSI->TheRecordDecl;
  11605. }
  11606. if (CapRecord) {
  11607. auto ExprLoc = Size->getExprLoc();
  11608. auto SizeType = Context.getSizeType();
  11609. // Build the non-static data member.
  11610. auto Field = FieldDecl::Create(
  11611. Context, CapRecord, ExprLoc, ExprLoc,
  11612. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11613. /*BW*/ nullptr, /*Mutable*/ false,
  11614. /*InitStyle*/ ICIS_NoInit);
  11615. Field->setImplicit(true);
  11616. Field->setAccess(AS_private);
  11617. Field->setCapturedVLAType(VAT);
  11618. CapRecord->addDecl(Field);
  11619. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11620. }
  11621. }
  11622. }
  11623. QTy = VAT->getElementType();
  11624. break;
  11625. }
  11626. case Type::FunctionProto:
  11627. case Type::FunctionNoProto:
  11628. QTy = cast<FunctionType>(Ty)->getReturnType();
  11629. break;
  11630. case Type::Paren:
  11631. case Type::TypeOf:
  11632. case Type::UnaryTransform:
  11633. case Type::Attributed:
  11634. case Type::SubstTemplateTypeParm:
  11635. case Type::PackExpansion:
  11636. // Keep walking after single level desugaring.
  11637. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11638. break;
  11639. case Type::Typedef:
  11640. QTy = cast<TypedefType>(Ty)->desugar();
  11641. break;
  11642. case Type::Decltype:
  11643. QTy = cast<DecltypeType>(Ty)->desugar();
  11644. break;
  11645. case Type::Auto:
  11646. QTy = cast<AutoType>(Ty)->getDeducedType();
  11647. break;
  11648. case Type::TypeOfExpr:
  11649. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11650. break;
  11651. case Type::Atomic:
  11652. QTy = cast<AtomicType>(Ty)->getValueType();
  11653. break;
  11654. }
  11655. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11656. }
  11657. if (getLangOpts().OpenMP) {
  11658. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11659. // OpenMP private variables should not be captured in outer scope, so
  11660. // just break here. Similarly, global variables that are captured in a
  11661. // target region should not be captured outside the scope of the region.
  11662. if (RSI->CapRegionKind == CR_OpenMP) {
  11663. auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel);
  11664. // When we detect target captures we are looking from inside the
  11665. // target region, therefore we need to propagate the capture from the
  11666. // enclosing region. Therefore, the capture is not initially nested.
  11667. if (isTargetCap)
  11668. FunctionScopesIndex--;
  11669. if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) {
  11670. Nested = !isTargetCap;
  11671. DeclRefType = DeclRefType.getUnqualifiedType();
  11672. CaptureType = Context.getLValueReferenceType(DeclRefType);
  11673. break;
  11674. }
  11675. ++OpenMPLevel;
  11676. }
  11677. }
  11678. }
  11679. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11680. // No capture-default, and this is not an explicit capture
  11681. // so cannot capture this variable.
  11682. if (BuildAndDiagnose) {
  11683. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11684. Diag(Var->getLocation(), diag::note_previous_decl)
  11685. << Var->getDeclName();
  11686. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11687. diag::note_lambda_decl);
  11688. // FIXME: If we error out because an outer lambda can not implicitly
  11689. // capture a variable that an inner lambda explicitly captures, we
  11690. // should have the inner lambda do the explicit capture - because
  11691. // it makes for cleaner diagnostics later. This would purely be done
  11692. // so that the diagnostic does not misleadingly claim that a variable
  11693. // can not be captured by a lambda implicitly even though it is captured
  11694. // explicitly. Suggestion:
  11695. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11696. // at the function head
  11697. // - cache the StartingDeclContext - this must be a lambda
  11698. // - captureInLambda in the innermost lambda the variable.
  11699. }
  11700. return true;
  11701. }
  11702. FunctionScopesIndex--;
  11703. DC = ParentDC;
  11704. Explicit = false;
  11705. } while (!VarDC->Equals(DC));
  11706. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11707. // computing the type of the capture at each step, checking type-specific
  11708. // requirements, and adding captures if requested.
  11709. // If the variable had already been captured previously, we start capturing
  11710. // at the lambda nested within that one.
  11711. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11712. ++I) {
  11713. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11714. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11715. if (!captureInBlock(BSI, Var, ExprLoc,
  11716. BuildAndDiagnose, CaptureType,
  11717. DeclRefType, Nested, *this))
  11718. return true;
  11719. Nested = true;
  11720. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11721. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11722. BuildAndDiagnose, CaptureType,
  11723. DeclRefType, Nested, *this))
  11724. return true;
  11725. Nested = true;
  11726. } else {
  11727. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11728. if (!captureInLambda(LSI, Var, ExprLoc,
  11729. BuildAndDiagnose, CaptureType,
  11730. DeclRefType, Nested, Kind, EllipsisLoc,
  11731. /*IsTopScope*/I == N - 1, *this))
  11732. return true;
  11733. Nested = true;
  11734. }
  11735. }
  11736. return false;
  11737. }
  11738. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11739. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11740. QualType CaptureType;
  11741. QualType DeclRefType;
  11742. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11743. /*BuildAndDiagnose=*/true, CaptureType,
  11744. DeclRefType, nullptr);
  11745. }
  11746. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11747. QualType CaptureType;
  11748. QualType DeclRefType;
  11749. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11750. /*BuildAndDiagnose=*/false, CaptureType,
  11751. DeclRefType, nullptr);
  11752. }
  11753. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11754. QualType CaptureType;
  11755. QualType DeclRefType;
  11756. // Determine whether we can capture this variable.
  11757. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11758. /*BuildAndDiagnose=*/false, CaptureType,
  11759. DeclRefType, nullptr))
  11760. return QualType();
  11761. return DeclRefType;
  11762. }
  11763. // If either the type of the variable or the initializer is dependent,
  11764. // return false. Otherwise, determine whether the variable is a constant
  11765. // expression. Use this if you need to know if a variable that might or
  11766. // might not be dependent is truly a constant expression.
  11767. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11768. ASTContext &Context) {
  11769. if (Var->getType()->isDependentType())
  11770. return false;
  11771. const VarDecl *DefVD = nullptr;
  11772. Var->getAnyInitializer(DefVD);
  11773. if (!DefVD)
  11774. return false;
  11775. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11776. Expr *Init = cast<Expr>(Eval->Value);
  11777. if (Init->isValueDependent())
  11778. return false;
  11779. return IsVariableAConstantExpression(Var, Context);
  11780. }
  11781. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11782. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11783. // an object that satisfies the requirements for appearing in a
  11784. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11785. // is immediately applied." This function handles the lvalue-to-rvalue
  11786. // conversion part.
  11787. MaybeODRUseExprs.erase(E->IgnoreParens());
  11788. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11789. // to a variable that is a constant expression, and if so, identify it as
  11790. // a reference to a variable that does not involve an odr-use of that
  11791. // variable.
  11792. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11793. Expr *SansParensExpr = E->IgnoreParens();
  11794. VarDecl *Var = nullptr;
  11795. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11796. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11797. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11798. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11799. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11800. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11801. }
  11802. }
  11803. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11804. Res = CorrectDelayedTyposInExpr(Res);
  11805. if (!Res.isUsable())
  11806. return Res;
  11807. // If a constant-expression is a reference to a variable where we delay
  11808. // deciding whether it is an odr-use, just assume we will apply the
  11809. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11810. // (a non-type template argument), we have special handling anyway.
  11811. UpdateMarkingForLValueToRValue(Res.get());
  11812. return Res;
  11813. }
  11814. void Sema::CleanupVarDeclMarking() {
  11815. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11816. e = MaybeODRUseExprs.end();
  11817. i != e; ++i) {
  11818. VarDecl *Var;
  11819. SourceLocation Loc;
  11820. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11821. Var = cast<VarDecl>(DRE->getDecl());
  11822. Loc = DRE->getLocation();
  11823. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11824. Var = cast<VarDecl>(ME->getMemberDecl());
  11825. Loc = ME->getMemberLoc();
  11826. } else {
  11827. llvm_unreachable("Unexpected expression");
  11828. }
  11829. MarkVarDeclODRUsed(Var, Loc, *this,
  11830. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11831. }
  11832. MaybeODRUseExprs.clear();
  11833. }
  11834. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11835. VarDecl *Var, Expr *E) {
  11836. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11837. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11838. Var->setReferenced();
  11839. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11840. bool MarkODRUsed = true;
  11841. // If the context is not potentially evaluated, this is not an odr-use and
  11842. // does not trigger instantiation.
  11843. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11844. if (SemaRef.isUnevaluatedContext())
  11845. return;
  11846. // If we don't yet know whether this context is going to end up being an
  11847. // evaluated context, and we're referencing a variable from an enclosing
  11848. // scope, add a potential capture.
  11849. //
  11850. // FIXME: Is this necessary? These contexts are only used for default
  11851. // arguments, where local variables can't be used.
  11852. const bool RefersToEnclosingScope =
  11853. (SemaRef.CurContext != Var->getDeclContext() &&
  11854. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11855. if (RefersToEnclosingScope) {
  11856. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11857. // If a variable could potentially be odr-used, defer marking it so
  11858. // until we finish analyzing the full expression for any
  11859. // lvalue-to-rvalue
  11860. // or discarded value conversions that would obviate odr-use.
  11861. // Add it to the list of potential captures that will be analyzed
  11862. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11863. // unless the variable is a reference that was initialized by a constant
  11864. // expression (this will never need to be captured or odr-used).
  11865. assert(E && "Capture variable should be used in an expression.");
  11866. if (!Var->getType()->isReferenceType() ||
  11867. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11868. LSI->addPotentialCapture(E->IgnoreParens());
  11869. }
  11870. }
  11871. if (!isTemplateInstantiation(TSK))
  11872. return;
  11873. // Instantiate, but do not mark as odr-used, variable templates.
  11874. MarkODRUsed = false;
  11875. }
  11876. VarTemplateSpecializationDecl *VarSpec =
  11877. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11878. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11879. "Can't instantiate a partial template specialization.");
  11880. // Perform implicit instantiation of static data members, static data member
  11881. // templates of class templates, and variable template specializations. Delay
  11882. // instantiations of variable templates, except for those that could be used
  11883. // in a constant expression.
  11884. if (isTemplateInstantiation(TSK)) {
  11885. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11886. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11887. if (Var->getPointOfInstantiation().isInvalid()) {
  11888. // This is a modification of an existing AST node. Notify listeners.
  11889. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11890. L->StaticDataMemberInstantiated(Var);
  11891. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11892. // Don't bother trying to instantiate it again, unless we might need
  11893. // its initializer before we get to the end of the TU.
  11894. TryInstantiating = false;
  11895. }
  11896. if (Var->getPointOfInstantiation().isInvalid())
  11897. Var->setTemplateSpecializationKind(TSK, Loc);
  11898. if (TryInstantiating) {
  11899. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11900. bool InstantiationDependent = false;
  11901. bool IsNonDependent =
  11902. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11903. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11904. : true;
  11905. // Do not instantiate specializations that are still type-dependent.
  11906. if (IsNonDependent) {
  11907. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11908. // Do not defer instantiations of variables which could be used in a
  11909. // constant expression.
  11910. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11911. } else {
  11912. SemaRef.PendingInstantiations
  11913. .push_back(std::make_pair(Var, PointOfInstantiation));
  11914. }
  11915. }
  11916. }
  11917. }
  11918. if(!MarkODRUsed) return;
  11919. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11920. // the requirements for appearing in a constant expression (5.19) and, if
  11921. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11922. // is immediately applied." We check the first part here, and
  11923. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11924. // Note that we use the C++11 definition everywhere because nothing in
  11925. // C++03 depends on whether we get the C++03 version correct. The second
  11926. // part does not apply to references, since they are not objects.
  11927. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11928. // A reference initialized by a constant expression can never be
  11929. // odr-used, so simply ignore it.
  11930. if (!Var->getType()->isReferenceType())
  11931. SemaRef.MaybeODRUseExprs.insert(E);
  11932. } else
  11933. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11934. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11935. }
  11936. /// \brief Mark a variable referenced, and check whether it is odr-used
  11937. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11938. /// used directly for normal expressions referring to VarDecl.
  11939. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11940. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11941. }
  11942. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11943. Decl *D, Expr *E, bool OdrUse) {
  11944. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11945. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11946. return;
  11947. }
  11948. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11949. // If this is a call to a method via a cast, also mark the method in the
  11950. // derived class used in case codegen can devirtualize the call.
  11951. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11952. if (!ME)
  11953. return;
  11954. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11955. if (!MD)
  11956. return;
  11957. // Only attempt to devirtualize if this is truly a virtual call.
  11958. bool IsVirtualCall = MD->isVirtual() &&
  11959. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  11960. if (!IsVirtualCall)
  11961. return;
  11962. const Expr *Base = ME->getBase();
  11963. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  11964. if (!MostDerivedClassDecl)
  11965. return;
  11966. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  11967. if (!DM || DM->isPure())
  11968. return;
  11969. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  11970. }
  11971. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  11972. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  11973. // TODO: update this with DR# once a defect report is filed.
  11974. // C++11 defect. The address of a pure member should not be an ODR use, even
  11975. // if it's a qualified reference.
  11976. bool OdrUse = true;
  11977. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  11978. if (Method->isVirtual())
  11979. OdrUse = false;
  11980. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  11981. }
  11982. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  11983. void Sema::MarkMemberReferenced(MemberExpr *E) {
  11984. // C++11 [basic.def.odr]p2:
  11985. // A non-overloaded function whose name appears as a potentially-evaluated
  11986. // expression or a member of a set of candidate functions, if selected by
  11987. // overload resolution when referred to from a potentially-evaluated
  11988. // expression, is odr-used, unless it is a pure virtual function and its
  11989. // name is not explicitly qualified.
  11990. bool OdrUse = true;
  11991. if (E->performsVirtualDispatch(getLangOpts())) {
  11992. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  11993. if (Method->isPure())
  11994. OdrUse = false;
  11995. }
  11996. SourceLocation Loc = E->getMemberLoc().isValid() ?
  11997. E->getMemberLoc() : E->getLocStart();
  11998. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  11999. }
  12000. /// \brief Perform marking for a reference to an arbitrary declaration. It
  12001. /// marks the declaration referenced, and performs odr-use checking for
  12002. /// functions and variables. This method should not be used when building a
  12003. /// normal expression which refers to a variable.
  12004. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  12005. if (OdrUse) {
  12006. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12007. MarkVariableReferenced(Loc, VD);
  12008. return;
  12009. }
  12010. }
  12011. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  12012. MarkFunctionReferenced(Loc, FD, OdrUse);
  12013. return;
  12014. }
  12015. D->setReferenced();
  12016. }
  12017. namespace {
  12018. // Mark all of the declarations referenced
  12019. // FIXME: Not fully implemented yet! We need to have a better understanding
  12020. // of when we're entering
  12021. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  12022. Sema &S;
  12023. SourceLocation Loc;
  12024. public:
  12025. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  12026. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  12027. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  12028. bool TraverseRecordType(RecordType *T);
  12029. };
  12030. }
  12031. bool MarkReferencedDecls::TraverseTemplateArgument(
  12032. const TemplateArgument &Arg) {
  12033. if (Arg.getKind() == TemplateArgument::Declaration) {
  12034. if (Decl *D = Arg.getAsDecl())
  12035. S.MarkAnyDeclReferenced(Loc, D, true);
  12036. }
  12037. return Inherited::TraverseTemplateArgument(Arg);
  12038. }
  12039. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  12040. if (ClassTemplateSpecializationDecl *Spec
  12041. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  12042. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  12043. return TraverseTemplateArguments(Args.data(), Args.size());
  12044. }
  12045. return true;
  12046. }
  12047. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  12048. MarkReferencedDecls Marker(*this, Loc);
  12049. Marker.TraverseType(Context.getCanonicalType(T));
  12050. }
  12051. namespace {
  12052. /// \brief Helper class that marks all of the declarations referenced by
  12053. /// potentially-evaluated subexpressions as "referenced".
  12054. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  12055. Sema &S;
  12056. bool SkipLocalVariables;
  12057. public:
  12058. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  12059. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  12060. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  12061. void VisitDeclRefExpr(DeclRefExpr *E) {
  12062. // If we were asked not to visit local variables, don't.
  12063. if (SkipLocalVariables) {
  12064. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  12065. if (VD->hasLocalStorage())
  12066. return;
  12067. }
  12068. S.MarkDeclRefReferenced(E);
  12069. }
  12070. void VisitMemberExpr(MemberExpr *E) {
  12071. S.MarkMemberReferenced(E);
  12072. Inherited::VisitMemberExpr(E);
  12073. }
  12074. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  12075. S.MarkFunctionReferenced(E->getLocStart(),
  12076. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  12077. Visit(E->getSubExpr());
  12078. }
  12079. void VisitCXXNewExpr(CXXNewExpr *E) {
  12080. if (E->getOperatorNew())
  12081. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  12082. if (E->getOperatorDelete())
  12083. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12084. Inherited::VisitCXXNewExpr(E);
  12085. }
  12086. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  12087. if (E->getOperatorDelete())
  12088. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12089. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  12090. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  12091. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  12092. S.MarkFunctionReferenced(E->getLocStart(),
  12093. S.LookupDestructor(Record));
  12094. }
  12095. Inherited::VisitCXXDeleteExpr(E);
  12096. }
  12097. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  12098. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  12099. Inherited::VisitCXXConstructExpr(E);
  12100. }
  12101. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  12102. Visit(E->getExpr());
  12103. }
  12104. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12105. Inherited::VisitImplicitCastExpr(E);
  12106. if (E->getCastKind() == CK_LValueToRValue)
  12107. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  12108. }
  12109. };
  12110. }
  12111. /// \brief Mark any declarations that appear within this expression or any
  12112. /// potentially-evaluated subexpressions as "referenced".
  12113. ///
  12114. /// \param SkipLocalVariables If true, don't mark local variables as
  12115. /// 'referenced'.
  12116. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  12117. bool SkipLocalVariables) {
  12118. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  12119. }
  12120. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  12121. /// of the program being compiled.
  12122. ///
  12123. /// This routine emits the given diagnostic when the code currently being
  12124. /// type-checked is "potentially evaluated", meaning that there is a
  12125. /// possibility that the code will actually be executable. Code in sizeof()
  12126. /// expressions, code used only during overload resolution, etc., are not
  12127. /// potentially evaluated. This routine will suppress such diagnostics or,
  12128. /// in the absolutely nutty case of potentially potentially evaluated
  12129. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  12130. /// later.
  12131. ///
  12132. /// This routine should be used for all diagnostics that describe the run-time
  12133. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  12134. /// Failure to do so will likely result in spurious diagnostics or failures
  12135. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  12136. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  12137. const PartialDiagnostic &PD) {
  12138. switch (ExprEvalContexts.back().Context) {
  12139. case Unevaluated:
  12140. case UnevaluatedAbstract:
  12141. // The argument will never be evaluated, so don't complain.
  12142. break;
  12143. case ConstantEvaluated:
  12144. // Relevant diagnostics should be produced by constant evaluation.
  12145. break;
  12146. case PotentiallyEvaluated:
  12147. case PotentiallyEvaluatedIfUsed:
  12148. if (Statement && getCurFunctionOrMethodDecl()) {
  12149. FunctionScopes.back()->PossiblyUnreachableDiags.
  12150. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  12151. }
  12152. else
  12153. Diag(Loc, PD);
  12154. return true;
  12155. }
  12156. return false;
  12157. }
  12158. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  12159. CallExpr *CE, FunctionDecl *FD) {
  12160. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  12161. return false;
  12162. // If we're inside a decltype's expression, don't check for a valid return
  12163. // type or construct temporaries until we know whether this is the last call.
  12164. if (ExprEvalContexts.back().IsDecltype) {
  12165. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  12166. return false;
  12167. }
  12168. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  12169. FunctionDecl *FD;
  12170. CallExpr *CE;
  12171. public:
  12172. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  12173. : FD(FD), CE(CE) { }
  12174. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  12175. if (!FD) {
  12176. S.Diag(Loc, diag::err_call_incomplete_return)
  12177. << T << CE->getSourceRange();
  12178. return;
  12179. }
  12180. S.Diag(Loc, diag::err_call_function_incomplete_return)
  12181. << CE->getSourceRange() << FD->getDeclName() << T;
  12182. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  12183. << FD->getDeclName();
  12184. }
  12185. } Diagnoser(FD, CE);
  12186. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  12187. return true;
  12188. return false;
  12189. }
  12190. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  12191. // will prevent this condition from triggering, which is what we want.
  12192. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  12193. SourceLocation Loc;
  12194. unsigned diagnostic = diag::warn_condition_is_assignment;
  12195. bool IsOrAssign = false;
  12196. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  12197. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  12198. return;
  12199. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  12200. // Greylist some idioms by putting them into a warning subcategory.
  12201. if (ObjCMessageExpr *ME
  12202. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  12203. Selector Sel = ME->getSelector();
  12204. // self = [<foo> init...]
  12205. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  12206. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12207. // <foo> = [<bar> nextObject]
  12208. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  12209. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12210. }
  12211. Loc = Op->getOperatorLoc();
  12212. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  12213. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  12214. return;
  12215. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  12216. Loc = Op->getOperatorLoc();
  12217. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  12218. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  12219. else {
  12220. // Not an assignment.
  12221. return;
  12222. }
  12223. Diag(Loc, diagnostic) << E->getSourceRange();
  12224. SourceLocation Open = E->getLocStart();
  12225. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  12226. Diag(Loc, diag::note_condition_assign_silence)
  12227. << FixItHint::CreateInsertion(Open, "(")
  12228. << FixItHint::CreateInsertion(Close, ")");
  12229. if (IsOrAssign)
  12230. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  12231. << FixItHint::CreateReplacement(Loc, "!=");
  12232. else
  12233. Diag(Loc, diag::note_condition_assign_to_comparison)
  12234. << FixItHint::CreateReplacement(Loc, "==");
  12235. }
  12236. /// \brief Redundant parentheses over an equality comparison can indicate
  12237. /// that the user intended an assignment used as condition.
  12238. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  12239. // Don't warn if the parens came from a macro.
  12240. SourceLocation parenLoc = ParenE->getLocStart();
  12241. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  12242. return;
  12243. // Don't warn for dependent expressions.
  12244. if (ParenE->isTypeDependent())
  12245. return;
  12246. Expr *E = ParenE->IgnoreParens();
  12247. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  12248. if (opE->getOpcode() == BO_EQ &&
  12249. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  12250. == Expr::MLV_Valid) {
  12251. SourceLocation Loc = opE->getOperatorLoc();
  12252. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  12253. SourceRange ParenERange = ParenE->getSourceRange();
  12254. Diag(Loc, diag::note_equality_comparison_silence)
  12255. << FixItHint::CreateRemoval(ParenERange.getBegin())
  12256. << FixItHint::CreateRemoval(ParenERange.getEnd());
  12257. Diag(Loc, diag::note_equality_comparison_to_assign)
  12258. << FixItHint::CreateReplacement(Loc, "=");
  12259. }
  12260. }
  12261. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  12262. DiagnoseAssignmentAsCondition(E);
  12263. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  12264. DiagnoseEqualityWithExtraParens(parenE);
  12265. ExprResult result = CheckPlaceholderExpr(E);
  12266. if (result.isInvalid()) return ExprError();
  12267. E = result.get();
  12268. if (!E->isTypeDependent()) {
  12269. if (getLangOpts().CPlusPlus)
  12270. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  12271. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  12272. if (ERes.isInvalid())
  12273. return ExprError();
  12274. E = ERes.get();
  12275. QualType T = E->getType();
  12276. if (!T->isScalarType()) { // C99 6.8.4.1p1
  12277. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  12278. << T << E->getSourceRange();
  12279. return ExprError();
  12280. }
  12281. CheckBoolLikeConversion(E, Loc);
  12282. }
  12283. return E;
  12284. }
  12285. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  12286. Expr *SubExpr) {
  12287. if (!SubExpr)
  12288. return ExprError();
  12289. return CheckBooleanCondition(SubExpr, Loc);
  12290. }
  12291. namespace {
  12292. /// A visitor for rebuilding a call to an __unknown_any expression
  12293. /// to have an appropriate type.
  12294. struct RebuildUnknownAnyFunction
  12295. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  12296. Sema &S;
  12297. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  12298. ExprResult VisitStmt(Stmt *S) {
  12299. llvm_unreachable("unexpected statement!");
  12300. }
  12301. ExprResult VisitExpr(Expr *E) {
  12302. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  12303. << E->getSourceRange();
  12304. return ExprError();
  12305. }
  12306. /// Rebuild an expression which simply semantically wraps another
  12307. /// expression which it shares the type and value kind of.
  12308. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12309. ExprResult SubResult = Visit(E->getSubExpr());
  12310. if (SubResult.isInvalid()) return ExprError();
  12311. Expr *SubExpr = SubResult.get();
  12312. E->setSubExpr(SubExpr);
  12313. E->setType(SubExpr->getType());
  12314. E->setValueKind(SubExpr->getValueKind());
  12315. assert(E->getObjectKind() == OK_Ordinary);
  12316. return E;
  12317. }
  12318. ExprResult VisitParenExpr(ParenExpr *E) {
  12319. return rebuildSugarExpr(E);
  12320. }
  12321. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12322. return rebuildSugarExpr(E);
  12323. }
  12324. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12325. ExprResult SubResult = Visit(E->getSubExpr());
  12326. if (SubResult.isInvalid()) return ExprError();
  12327. Expr *SubExpr = SubResult.get();
  12328. E->setSubExpr(SubExpr);
  12329. E->setType(S.Context.getPointerType(SubExpr->getType()));
  12330. assert(E->getValueKind() == VK_RValue);
  12331. assert(E->getObjectKind() == OK_Ordinary);
  12332. return E;
  12333. }
  12334. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  12335. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  12336. E->setType(VD->getType());
  12337. assert(E->getValueKind() == VK_RValue);
  12338. if (S.getLangOpts().CPlusPlus &&
  12339. !(isa<CXXMethodDecl>(VD) &&
  12340. cast<CXXMethodDecl>(VD)->isInstance()))
  12341. E->setValueKind(VK_LValue);
  12342. return E;
  12343. }
  12344. ExprResult VisitMemberExpr(MemberExpr *E) {
  12345. return resolveDecl(E, E->getMemberDecl());
  12346. }
  12347. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12348. return resolveDecl(E, E->getDecl());
  12349. }
  12350. };
  12351. }
  12352. /// Given a function expression of unknown-any type, try to rebuild it
  12353. /// to have a function type.
  12354. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  12355. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  12356. if (Result.isInvalid()) return ExprError();
  12357. return S.DefaultFunctionArrayConversion(Result.get());
  12358. }
  12359. namespace {
  12360. /// A visitor for rebuilding an expression of type __unknown_anytype
  12361. /// into one which resolves the type directly on the referring
  12362. /// expression. Strict preservation of the original source
  12363. /// structure is not a goal.
  12364. struct RebuildUnknownAnyExpr
  12365. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  12366. Sema &S;
  12367. /// The current destination type.
  12368. QualType DestType;
  12369. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  12370. : S(S), DestType(CastType) {}
  12371. ExprResult VisitStmt(Stmt *S) {
  12372. llvm_unreachable("unexpected statement!");
  12373. }
  12374. ExprResult VisitExpr(Expr *E) {
  12375. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12376. << E->getSourceRange();
  12377. return ExprError();
  12378. }
  12379. ExprResult VisitCallExpr(CallExpr *E);
  12380. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  12381. /// Rebuild an expression which simply semantically wraps another
  12382. /// expression which it shares the type and value kind of.
  12383. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12384. ExprResult SubResult = Visit(E->getSubExpr());
  12385. if (SubResult.isInvalid()) return ExprError();
  12386. Expr *SubExpr = SubResult.get();
  12387. E->setSubExpr(SubExpr);
  12388. E->setType(SubExpr->getType());
  12389. E->setValueKind(SubExpr->getValueKind());
  12390. assert(E->getObjectKind() == OK_Ordinary);
  12391. return E;
  12392. }
  12393. ExprResult VisitParenExpr(ParenExpr *E) {
  12394. return rebuildSugarExpr(E);
  12395. }
  12396. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12397. return rebuildSugarExpr(E);
  12398. }
  12399. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12400. const PointerType *Ptr = DestType->getAs<PointerType>();
  12401. if (!Ptr) {
  12402. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  12403. << E->getSourceRange();
  12404. return ExprError();
  12405. }
  12406. assert(E->getValueKind() == VK_RValue);
  12407. assert(E->getObjectKind() == OK_Ordinary);
  12408. E->setType(DestType);
  12409. // Build the sub-expression as if it were an object of the pointee type.
  12410. DestType = Ptr->getPointeeType();
  12411. ExprResult SubResult = Visit(E->getSubExpr());
  12412. if (SubResult.isInvalid()) return ExprError();
  12413. E->setSubExpr(SubResult.get());
  12414. return E;
  12415. }
  12416. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  12417. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  12418. ExprResult VisitMemberExpr(MemberExpr *E) {
  12419. return resolveDecl(E, E->getMemberDecl());
  12420. }
  12421. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12422. return resolveDecl(E, E->getDecl());
  12423. }
  12424. };
  12425. }
  12426. /// Rebuilds a call expression which yielded __unknown_anytype.
  12427. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  12428. Expr *CalleeExpr = E->getCallee();
  12429. enum FnKind {
  12430. FK_MemberFunction,
  12431. FK_FunctionPointer,
  12432. FK_BlockPointer
  12433. };
  12434. FnKind Kind;
  12435. QualType CalleeType = CalleeExpr->getType();
  12436. if (CalleeType == S.Context.BoundMemberTy) {
  12437. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  12438. Kind = FK_MemberFunction;
  12439. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  12440. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  12441. CalleeType = Ptr->getPointeeType();
  12442. Kind = FK_FunctionPointer;
  12443. } else {
  12444. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  12445. Kind = FK_BlockPointer;
  12446. }
  12447. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  12448. // Verify that this is a legal result type of a function.
  12449. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12450. unsigned diagID = diag::err_func_returning_array_function;
  12451. if (Kind == FK_BlockPointer)
  12452. diagID = diag::err_block_returning_array_function;
  12453. S.Diag(E->getExprLoc(), diagID)
  12454. << DestType->isFunctionType() << DestType;
  12455. return ExprError();
  12456. }
  12457. // Otherwise, go ahead and set DestType as the call's result.
  12458. E->setType(DestType.getNonLValueExprType(S.Context));
  12459. E->setValueKind(Expr::getValueKindForType(DestType));
  12460. assert(E->getObjectKind() == OK_Ordinary);
  12461. // Rebuild the function type, replacing the result type with DestType.
  12462. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  12463. if (Proto) {
  12464. // __unknown_anytype(...) is a special case used by the debugger when
  12465. // it has no idea what a function's signature is.
  12466. //
  12467. // We want to build this call essentially under the K&R
  12468. // unprototyped rules, but making a FunctionNoProtoType in C++
  12469. // would foul up all sorts of assumptions. However, we cannot
  12470. // simply pass all arguments as variadic arguments, nor can we
  12471. // portably just call the function under a non-variadic type; see
  12472. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  12473. // However, it turns out that in practice it is generally safe to
  12474. // call a function declared as "A foo(B,C,D);" under the prototype
  12475. // "A foo(B,C,D,...);". The only known exception is with the
  12476. // Windows ABI, where any variadic function is implicitly cdecl
  12477. // regardless of its normal CC. Therefore we change the parameter
  12478. // types to match the types of the arguments.
  12479. //
  12480. // This is a hack, but it is far superior to moving the
  12481. // corresponding target-specific code from IR-gen to Sema/AST.
  12482. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  12483. SmallVector<QualType, 8> ArgTypes;
  12484. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  12485. ArgTypes.reserve(E->getNumArgs());
  12486. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  12487. Expr *Arg = E->getArg(i);
  12488. QualType ArgType = Arg->getType();
  12489. if (E->isLValue()) {
  12490. ArgType = S.Context.getLValueReferenceType(ArgType);
  12491. } else if (E->isXValue()) {
  12492. ArgType = S.Context.getRValueReferenceType(ArgType);
  12493. }
  12494. ArgTypes.push_back(ArgType);
  12495. }
  12496. ParamTypes = ArgTypes;
  12497. }
  12498. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  12499. Proto->getExtProtoInfo());
  12500. } else {
  12501. DestType = S.Context.getFunctionNoProtoType(DestType,
  12502. FnType->getExtInfo());
  12503. }
  12504. // Rebuild the appropriate pointer-to-function type.
  12505. switch (Kind) {
  12506. case FK_MemberFunction:
  12507. // Nothing to do.
  12508. break;
  12509. case FK_FunctionPointer:
  12510. DestType = S.Context.getPointerType(DestType);
  12511. break;
  12512. case FK_BlockPointer:
  12513. DestType = S.Context.getBlockPointerType(DestType);
  12514. break;
  12515. }
  12516. // Finally, we can recurse.
  12517. ExprResult CalleeResult = Visit(CalleeExpr);
  12518. if (!CalleeResult.isUsable()) return ExprError();
  12519. E->setCallee(CalleeResult.get());
  12520. // Bind a temporary if necessary.
  12521. return S.MaybeBindToTemporary(E);
  12522. }
  12523. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12524. // Verify that this is a legal result type of a call.
  12525. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12526. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12527. << DestType->isFunctionType() << DestType;
  12528. return ExprError();
  12529. }
  12530. // Rewrite the method result type if available.
  12531. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12532. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12533. Method->setReturnType(DestType);
  12534. }
  12535. // Change the type of the message.
  12536. E->setType(DestType.getNonReferenceType());
  12537. E->setValueKind(Expr::getValueKindForType(DestType));
  12538. return S.MaybeBindToTemporary(E);
  12539. }
  12540. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12541. // The only case we should ever see here is a function-to-pointer decay.
  12542. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12543. assert(E->getValueKind() == VK_RValue);
  12544. assert(E->getObjectKind() == OK_Ordinary);
  12545. E->setType(DestType);
  12546. // Rebuild the sub-expression as the pointee (function) type.
  12547. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12548. ExprResult Result = Visit(E->getSubExpr());
  12549. if (!Result.isUsable()) return ExprError();
  12550. E->setSubExpr(Result.get());
  12551. return E;
  12552. } else if (E->getCastKind() == CK_LValueToRValue) {
  12553. assert(E->getValueKind() == VK_RValue);
  12554. assert(E->getObjectKind() == OK_Ordinary);
  12555. assert(isa<BlockPointerType>(E->getType()));
  12556. E->setType(DestType);
  12557. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12558. DestType = S.Context.getLValueReferenceType(DestType);
  12559. ExprResult Result = Visit(E->getSubExpr());
  12560. if (!Result.isUsable()) return ExprError();
  12561. E->setSubExpr(Result.get());
  12562. return E;
  12563. } else {
  12564. llvm_unreachable("Unhandled cast type!");
  12565. }
  12566. }
  12567. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12568. ExprValueKind ValueKind = VK_LValue;
  12569. QualType Type = DestType;
  12570. // We know how to make this work for certain kinds of decls:
  12571. // - functions
  12572. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12573. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12574. DestType = Ptr->getPointeeType();
  12575. ExprResult Result = resolveDecl(E, VD);
  12576. if (Result.isInvalid()) return ExprError();
  12577. return S.ImpCastExprToType(Result.get(), Type,
  12578. CK_FunctionToPointerDecay, VK_RValue);
  12579. }
  12580. if (!Type->isFunctionType()) {
  12581. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12582. << VD << E->getSourceRange();
  12583. return ExprError();
  12584. }
  12585. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12586. // We must match the FunctionDecl's type to the hack introduced in
  12587. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12588. // type. See the lengthy commentary in that routine.
  12589. QualType FDT = FD->getType();
  12590. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12591. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12592. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12593. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12594. SourceLocation Loc = FD->getLocation();
  12595. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12596. FD->getDeclContext(),
  12597. Loc, Loc, FD->getNameInfo().getName(),
  12598. DestType, FD->getTypeSourceInfo(),
  12599. SC_None, false/*isInlineSpecified*/,
  12600. FD->hasPrototype(),
  12601. false/*isConstexprSpecified*/);
  12602. if (FD->getQualifier())
  12603. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12604. SmallVector<ParmVarDecl*, 16> Params;
  12605. for (const auto &AI : FT->param_types()) {
  12606. ParmVarDecl *Param =
  12607. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12608. Param->setScopeInfo(0, Params.size());
  12609. Params.push_back(Param);
  12610. }
  12611. NewFD->setParams(Params);
  12612. DRE->setDecl(NewFD);
  12613. VD = DRE->getDecl();
  12614. }
  12615. }
  12616. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12617. if (MD->isInstance()) {
  12618. ValueKind = VK_RValue;
  12619. Type = S.Context.BoundMemberTy;
  12620. }
  12621. // Function references aren't l-values in C.
  12622. if (!S.getLangOpts().CPlusPlus)
  12623. ValueKind = VK_RValue;
  12624. // - variables
  12625. } else if (isa<VarDecl>(VD)) {
  12626. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12627. Type = RefTy->getPointeeType();
  12628. } else if (Type->isFunctionType()) {
  12629. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12630. << VD << E->getSourceRange();
  12631. return ExprError();
  12632. }
  12633. // - nothing else
  12634. } else {
  12635. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12636. << VD << E->getSourceRange();
  12637. return ExprError();
  12638. }
  12639. // Modifying the declaration like this is friendly to IR-gen but
  12640. // also really dangerous.
  12641. VD->setType(DestType);
  12642. E->setType(Type);
  12643. E->setValueKind(ValueKind);
  12644. return E;
  12645. }
  12646. /// Check a cast of an unknown-any type. We intentionally only
  12647. /// trigger this for C-style casts.
  12648. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12649. Expr *CastExpr, CastKind &CastKind,
  12650. ExprValueKind &VK, CXXCastPath &Path) {
  12651. // Rewrite the casted expression from scratch.
  12652. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12653. if (!result.isUsable()) return ExprError();
  12654. CastExpr = result.get();
  12655. VK = CastExpr->getValueKind();
  12656. CastKind = CK_NoOp;
  12657. return CastExpr;
  12658. }
  12659. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12660. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12661. }
  12662. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12663. Expr *arg, QualType &paramType) {
  12664. // If the syntactic form of the argument is not an explicit cast of
  12665. // any sort, just do default argument promotion.
  12666. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12667. if (!castArg) {
  12668. ExprResult result = DefaultArgumentPromotion(arg);
  12669. if (result.isInvalid()) return ExprError();
  12670. paramType = result.get()->getType();
  12671. return result;
  12672. }
  12673. // Otherwise, use the type that was written in the explicit cast.
  12674. assert(!arg->hasPlaceholderType());
  12675. paramType = castArg->getTypeAsWritten();
  12676. // Copy-initialize a parameter of that type.
  12677. InitializedEntity entity =
  12678. InitializedEntity::InitializeParameter(Context, paramType,
  12679. /*consumed*/ false);
  12680. return PerformCopyInitialization(entity, callLoc, arg);
  12681. }
  12682. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12683. Expr *orig = E;
  12684. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12685. while (true) {
  12686. E = E->IgnoreParenImpCasts();
  12687. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12688. E = call->getCallee();
  12689. diagID = diag::err_uncasted_call_of_unknown_any;
  12690. } else {
  12691. break;
  12692. }
  12693. }
  12694. SourceLocation loc;
  12695. NamedDecl *d;
  12696. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12697. loc = ref->getLocation();
  12698. d = ref->getDecl();
  12699. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12700. loc = mem->getMemberLoc();
  12701. d = mem->getMemberDecl();
  12702. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12703. diagID = diag::err_uncasted_call_of_unknown_any;
  12704. loc = msg->getSelectorStartLoc();
  12705. d = msg->getMethodDecl();
  12706. if (!d) {
  12707. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12708. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12709. << orig->getSourceRange();
  12710. return ExprError();
  12711. }
  12712. } else {
  12713. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12714. << E->getSourceRange();
  12715. return ExprError();
  12716. }
  12717. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12718. // Never recoverable.
  12719. return ExprError();
  12720. }
  12721. /// Check for operands with placeholder types and complain if found.
  12722. /// Returns true if there was an error and no recovery was possible.
  12723. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12724. if (!getLangOpts().CPlusPlus) {
  12725. // C cannot handle TypoExpr nodes on either side of a binop because it
  12726. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12727. // been dealt with before checking the operands.
  12728. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12729. if (!Result.isUsable()) return ExprError();
  12730. E = Result.get();
  12731. }
  12732. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12733. if (!placeholderType) return E;
  12734. switch (placeholderType->getKind()) {
  12735. // Overloaded expressions.
  12736. case BuiltinType::Overload: {
  12737. // Try to resolve a single function template specialization.
  12738. // This is obligatory.
  12739. ExprResult result = E;
  12740. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12741. return result;
  12742. // If that failed, try to recover with a call.
  12743. } else {
  12744. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12745. /*complain*/ true);
  12746. return result;
  12747. }
  12748. }
  12749. // Bound member functions.
  12750. case BuiltinType::BoundMember: {
  12751. ExprResult result = E;
  12752. const Expr *BME = E->IgnoreParens();
  12753. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  12754. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  12755. if (isa<CXXPseudoDestructorExpr>(BME)) {
  12756. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  12757. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  12758. if (ME->getMemberNameInfo().getName().getNameKind() ==
  12759. DeclarationName::CXXDestructorName)
  12760. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  12761. }
  12762. tryToRecoverWithCall(result, PD,
  12763. /*complain*/ true);
  12764. return result;
  12765. }
  12766. // ARC unbridged casts.
  12767. case BuiltinType::ARCUnbridgedCast: {
  12768. Expr *realCast = stripARCUnbridgedCast(E);
  12769. diagnoseARCUnbridgedCast(realCast);
  12770. return realCast;
  12771. }
  12772. // Expressions of unknown type.
  12773. case BuiltinType::UnknownAny:
  12774. return diagnoseUnknownAnyExpr(*this, E);
  12775. // Pseudo-objects.
  12776. case BuiltinType::PseudoObject:
  12777. return checkPseudoObjectRValue(E);
  12778. case BuiltinType::BuiltinFn: {
  12779. // Accept __noop without parens by implicitly converting it to a call expr.
  12780. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12781. if (DRE) {
  12782. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12783. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12784. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12785. CK_BuiltinFnToFnPtr).get();
  12786. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12787. VK_RValue, SourceLocation());
  12788. }
  12789. }
  12790. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12791. return ExprError();
  12792. }
  12793. // Expressions of unknown type.
  12794. case BuiltinType::OMPArraySection:
  12795. Diag(E->getLocStart(), diag::err_omp_array_section_use);
  12796. return ExprError();
  12797. // Everything else should be impossible.
  12798. #define BUILTIN_TYPE(Id, SingletonId) \
  12799. case BuiltinType::Id:
  12800. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12801. #include "clang/AST/BuiltinTypes.def"
  12802. break;
  12803. }
  12804. llvm_unreachable("invalid placeholder type!");
  12805. }
  12806. bool Sema::CheckCaseExpression(Expr *E) {
  12807. if (E->isTypeDependent())
  12808. return true;
  12809. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12810. return E->getType()->isIntegralOrEnumerationType();
  12811. return false;
  12812. }
  12813. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12814. ExprResult
  12815. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12816. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12817. "Unknown Objective-C Boolean value!");
  12818. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12819. if (!Context.getBOOLDecl()) {
  12820. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12821. Sema::LookupOrdinaryName);
  12822. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12823. NamedDecl *ND = Result.getFoundDecl();
  12824. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12825. Context.setBOOLDecl(TD);
  12826. }
  12827. }
  12828. if (Context.getBOOLDecl())
  12829. BoolT = Context.getBOOLType();
  12830. return new (Context)
  12831. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12832. }