SemaExpr.cpp 540 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044
  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/RecursiveASTVisitor.h"
  27. #include "clang/AST/TypeLoc.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/LiteralSupport.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/AnalysisBasedWarnings.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Designator.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaFixItUtils.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/Support/ConvertUTF.h"
  45. using namespace clang;
  46. using namespace sema;
  47. /// \brief Determine whether the use of this declaration is valid, without
  48. /// emitting diagnostics.
  49. bool Sema::CanUseDecl(NamedDecl *D) {
  50. // See if this is an auto-typed variable whose initializer we are parsing.
  51. if (ParsingInitForAutoVars.count(D))
  52. return false;
  53. // See if this is a deleted function.
  54. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  55. if (FD->isDeleted())
  56. return false;
  57. // If the function has a deduced return type, and we can't deduce it,
  58. // then we can't use it either.
  59. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  60. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  61. return false;
  62. }
  63. // See if this function is unavailable.
  64. if (D->getAvailability() == AR_Unavailable &&
  65. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  66. return false;
  67. return true;
  68. }
  69. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  70. // Warn if this is used but marked unused.
  71. if (D->hasAttr<UnusedAttr>()) {
  72. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  73. if (DC && !DC->hasAttr<UnusedAttr>())
  74. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  75. }
  76. }
  77. static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
  78. NamedDecl *D, SourceLocation Loc,
  79. const ObjCInterfaceDecl *UnknownObjCClass,
  80. bool ObjCPropertyAccess) {
  81. // See if this declaration is unavailable or deprecated.
  82. std::string Message;
  83. // Forward class declarations get their attributes from their definition.
  84. if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
  85. if (IDecl->getDefinition())
  86. D = IDecl->getDefinition();
  87. }
  88. AvailabilityResult Result = D->getAvailability(&Message);
  89. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
  90. if (Result == AR_Available) {
  91. const DeclContext *DC = ECD->getDeclContext();
  92. if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
  93. Result = TheEnumDecl->getAvailability(&Message);
  94. }
  95. const ObjCPropertyDecl *ObjCPDecl = nullptr;
  96. if (Result == AR_Deprecated || Result == AR_Unavailable) {
  97. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  98. if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
  99. AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
  100. if (PDeclResult == Result)
  101. ObjCPDecl = PD;
  102. }
  103. }
  104. }
  105. switch (Result) {
  106. case AR_Available:
  107. case AR_NotYetIntroduced:
  108. break;
  109. case AR_Deprecated:
  110. if (S.getCurContextAvailability() != AR_Deprecated)
  111. S.EmitAvailabilityWarning(Sema::AD_Deprecation,
  112. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  113. ObjCPropertyAccess);
  114. break;
  115. case AR_Unavailable:
  116. if (S.getCurContextAvailability() != AR_Unavailable)
  117. S.EmitAvailabilityWarning(Sema::AD_Unavailable,
  118. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  119. ObjCPropertyAccess);
  120. break;
  121. }
  122. return Result;
  123. }
  124. /// \brief Emit a note explaining that this function is deleted.
  125. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  126. assert(Decl->isDeleted());
  127. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  128. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  129. // If the method was explicitly defaulted, point at that declaration.
  130. if (!Method->isImplicit())
  131. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  132. // Try to diagnose why this special member function was implicitly
  133. // deleted. This might fail, if that reason no longer applies.
  134. CXXSpecialMember CSM = getSpecialMember(Method);
  135. if (CSM != CXXInvalid)
  136. ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
  137. return;
  138. }
  139. if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
  140. if (CXXConstructorDecl *BaseCD =
  141. const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
  142. Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
  143. if (BaseCD->isDeleted()) {
  144. NoteDeletedFunction(BaseCD);
  145. } else {
  146. // FIXME: An explanation of why exactly it can't be inherited
  147. // would be nice.
  148. Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
  149. }
  150. return;
  151. }
  152. }
  153. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  154. << Decl << true;
  155. }
  156. /// \brief Determine whether a FunctionDecl was ever declared with an
  157. /// explicit storage class.
  158. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  159. for (auto I : D->redecls()) {
  160. if (I->getStorageClass() != SC_None)
  161. return true;
  162. }
  163. return false;
  164. }
  165. /// \brief Check whether we're in an extern inline function and referring to a
  166. /// variable or function with internal linkage (C11 6.7.4p3).
  167. ///
  168. /// This is only a warning because we used to silently accept this code, but
  169. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  170. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  171. /// and so while there may still be user mistakes, most of the time we can't
  172. /// prove that there are errors.
  173. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  174. const NamedDecl *D,
  175. SourceLocation Loc) {
  176. // This is disabled under C++; there are too many ways for this to fire in
  177. // contexts where the warning is a false positive, or where it is technically
  178. // correct but benign.
  179. if (S.getLangOpts().CPlusPlus)
  180. return;
  181. // Check if this is an inlined function or method.
  182. FunctionDecl *Current = S.getCurFunctionDecl();
  183. if (!Current)
  184. return;
  185. if (!Current->isInlined())
  186. return;
  187. if (!Current->isExternallyVisible())
  188. return;
  189. // Check if the decl has internal linkage.
  190. if (D->getFormalLinkage() != InternalLinkage)
  191. return;
  192. // Downgrade from ExtWarn to Extension if
  193. // (1) the supposedly external inline function is in the main file,
  194. // and probably won't be included anywhere else.
  195. // (2) the thing we're referencing is a pure function.
  196. // (3) the thing we're referencing is another inline function.
  197. // This last can give us false negatives, but it's better than warning on
  198. // wrappers for simple C library functions.
  199. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  200. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  201. if (!DowngradeWarning && UsedFn)
  202. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  203. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  204. : diag::ext_internal_in_extern_inline)
  205. << /*IsVar=*/!UsedFn << D;
  206. S.MaybeSuggestAddingStaticToDecl(Current);
  207. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  208. << D;
  209. }
  210. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  211. const FunctionDecl *First = Cur->getFirstDecl();
  212. // Suggest "static" on the function, if possible.
  213. if (!hasAnyExplicitStorageClass(First)) {
  214. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  215. Diag(DeclBegin, diag::note_convert_inline_to_static)
  216. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  217. }
  218. }
  219. /// \brief Determine whether the use of this declaration is valid, and
  220. /// emit any corresponding diagnostics.
  221. ///
  222. /// This routine diagnoses various problems with referencing
  223. /// declarations that can occur when using a declaration. For example,
  224. /// it might warn if a deprecated or unavailable declaration is being
  225. /// used, or produce an error (and return true) if a C++0x deleted
  226. /// function is being used.
  227. ///
  228. /// \returns true if there was an error (this declaration cannot be
  229. /// referenced), false otherwise.
  230. ///
  231. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  232. const ObjCInterfaceDecl *UnknownObjCClass,
  233. bool ObjCPropertyAccess) {
  234. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  235. // If there were any diagnostics suppressed by template argument deduction,
  236. // emit them now.
  237. SuppressedDiagnosticsMap::iterator
  238. Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  239. if (Pos != SuppressedDiagnostics.end()) {
  240. SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
  241. for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
  242. Diag(Suppressed[I].first, Suppressed[I].second);
  243. // Clear out the list of suppressed diagnostics, so that we don't emit
  244. // them again for this specialization. However, we don't obsolete this
  245. // entry from the table, because we want to avoid ever emitting these
  246. // diagnostics again.
  247. Suppressed.clear();
  248. }
  249. // C++ [basic.start.main]p3:
  250. // The function 'main' shall not be used within a program.
  251. if (cast<FunctionDecl>(D)->isMain())
  252. Diag(Loc, diag::ext_main_used);
  253. }
  254. // See if this is an auto-typed variable whose initializer we are parsing.
  255. if (ParsingInitForAutoVars.count(D)) {
  256. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  257. << D->getDeclName();
  258. return true;
  259. }
  260. // See if this is a deleted function.
  261. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  262. if (FD->isDeleted()) {
  263. Diag(Loc, diag::err_deleted_function_use);
  264. NoteDeletedFunction(FD);
  265. return true;
  266. }
  267. // If the function has a deduced return type, and we can't deduce it,
  268. // then we can't use it either.
  269. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  270. DeduceReturnType(FD, Loc))
  271. return true;
  272. }
  273. DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
  274. DiagnoseUnusedOfDecl(*this, D, Loc);
  275. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  276. return false;
  277. }
  278. /// \brief Retrieve the message suffix that should be added to a
  279. /// diagnostic complaining about the given function being deleted or
  280. /// unavailable.
  281. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  282. std::string Message;
  283. if (FD->getAvailability(&Message))
  284. return ": " + Message;
  285. return std::string();
  286. }
  287. /// DiagnoseSentinelCalls - This routine checks whether a call or
  288. /// message-send is to a declaration with the sentinel attribute, and
  289. /// if so, it checks that the requirements of the sentinel are
  290. /// satisfied.
  291. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  292. ArrayRef<Expr *> Args) {
  293. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  294. if (!attr)
  295. return;
  296. // The number of formal parameters of the declaration.
  297. unsigned numFormalParams;
  298. // The kind of declaration. This is also an index into a %select in
  299. // the diagnostic.
  300. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  301. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  302. numFormalParams = MD->param_size();
  303. calleeType = CT_Method;
  304. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  305. numFormalParams = FD->param_size();
  306. calleeType = CT_Function;
  307. } else if (isa<VarDecl>(D)) {
  308. QualType type = cast<ValueDecl>(D)->getType();
  309. const FunctionType *fn = nullptr;
  310. if (const PointerType *ptr = type->getAs<PointerType>()) {
  311. fn = ptr->getPointeeType()->getAs<FunctionType>();
  312. if (!fn) return;
  313. calleeType = CT_Function;
  314. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  315. fn = ptr->getPointeeType()->castAs<FunctionType>();
  316. calleeType = CT_Block;
  317. } else {
  318. return;
  319. }
  320. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  321. numFormalParams = proto->getNumParams();
  322. } else {
  323. numFormalParams = 0;
  324. }
  325. } else {
  326. return;
  327. }
  328. // "nullPos" is the number of formal parameters at the end which
  329. // effectively count as part of the variadic arguments. This is
  330. // useful if you would prefer to not have *any* formal parameters,
  331. // but the language forces you to have at least one.
  332. unsigned nullPos = attr->getNullPos();
  333. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  334. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  335. // The number of arguments which should follow the sentinel.
  336. unsigned numArgsAfterSentinel = attr->getSentinel();
  337. // If there aren't enough arguments for all the formal parameters,
  338. // the sentinel, and the args after the sentinel, complain.
  339. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  340. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  341. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  342. return;
  343. }
  344. // Otherwise, find the sentinel expression.
  345. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  346. if (!sentinelExpr) return;
  347. if (sentinelExpr->isValueDependent()) return;
  348. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  349. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  350. // or 'NULL' if those are actually defined in the context. Only use
  351. // 'nil' for ObjC methods, where it's much more likely that the
  352. // variadic arguments form a list of object pointers.
  353. SourceLocation MissingNilLoc
  354. = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
  355. std::string NullValue;
  356. if (calleeType == CT_Method &&
  357. PP.getIdentifierInfo("nil")->hasMacroDefinition())
  358. NullValue = "nil";
  359. else if (getLangOpts().CPlusPlus11)
  360. NullValue = "nullptr";
  361. else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
  362. NullValue = "NULL";
  363. else
  364. NullValue = "(void*) 0";
  365. if (MissingNilLoc.isInvalid())
  366. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  367. else
  368. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  369. << int(calleeType)
  370. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  371. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  372. }
  373. SourceRange Sema::getExprRange(Expr *E) const {
  374. return E ? E->getSourceRange() : SourceRange();
  375. }
  376. //===----------------------------------------------------------------------===//
  377. // Standard Promotions and Conversions
  378. //===----------------------------------------------------------------------===//
  379. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  380. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
  381. // Handle any placeholder expressions which made it here.
  382. if (E->getType()->isPlaceholderType()) {
  383. ExprResult result = CheckPlaceholderExpr(E);
  384. if (result.isInvalid()) return ExprError();
  385. E = result.get();
  386. }
  387. QualType Ty = E->getType();
  388. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  389. if (Ty->isFunctionType()) {
  390. // If we are here, we are not calling a function but taking
  391. // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
  392. if (getLangOpts().OpenCL) {
  393. Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
  394. return ExprError();
  395. }
  396. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  397. CK_FunctionToPointerDecay).get();
  398. } else if (Ty->isArrayType()) {
  399. // In C90 mode, arrays only promote to pointers if the array expression is
  400. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  401. // type 'array of type' is converted to an expression that has type 'pointer
  402. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  403. // that has type 'array of type' ...". The relevant change is "an lvalue"
  404. // (C90) to "an expression" (C99).
  405. //
  406. // C++ 4.2p1:
  407. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  408. // T" can be converted to an rvalue of type "pointer to T".
  409. //
  410. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  411. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  412. CK_ArrayToPointerDecay).get();
  413. }
  414. return E;
  415. }
  416. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  417. // Check to see if we are dereferencing a null pointer. If so,
  418. // and if not volatile-qualified, this is undefined behavior that the
  419. // optimizer will delete, so warn about it. People sometimes try to use this
  420. // to get a deterministic trap and are surprised by clang's behavior. This
  421. // only handles the pattern "*null", which is a very syntactic check.
  422. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  423. if (UO->getOpcode() == UO_Deref &&
  424. UO->getSubExpr()->IgnoreParenCasts()->
  425. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  426. !UO->getType().isVolatileQualified()) {
  427. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  428. S.PDiag(diag::warn_indirection_through_null)
  429. << UO->getSubExpr()->getSourceRange());
  430. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  431. S.PDiag(diag::note_indirection_through_null));
  432. }
  433. }
  434. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  435. SourceLocation AssignLoc,
  436. const Expr* RHS) {
  437. const ObjCIvarDecl *IV = OIRE->getDecl();
  438. if (!IV)
  439. return;
  440. DeclarationName MemberName = IV->getDeclName();
  441. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  442. if (!Member || !Member->isStr("isa"))
  443. return;
  444. const Expr *Base = OIRE->getBase();
  445. QualType BaseType = Base->getType();
  446. if (OIRE->isArrow())
  447. BaseType = BaseType->getPointeeType();
  448. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  449. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  450. ObjCInterfaceDecl *ClassDeclared = nullptr;
  451. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  452. if (!ClassDeclared->getSuperClass()
  453. && (*ClassDeclared->ivar_begin()) == IV) {
  454. if (RHS) {
  455. NamedDecl *ObjectSetClass =
  456. S.LookupSingleName(S.TUScope,
  457. &S.Context.Idents.get("object_setClass"),
  458. SourceLocation(), S.LookupOrdinaryName);
  459. if (ObjectSetClass) {
  460. SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
  461. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  462. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  463. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  464. AssignLoc), ",") <<
  465. FixItHint::CreateInsertion(RHSLocEnd, ")");
  466. }
  467. else
  468. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  469. } else {
  470. NamedDecl *ObjectGetClass =
  471. S.LookupSingleName(S.TUScope,
  472. &S.Context.Idents.get("object_getClass"),
  473. SourceLocation(), S.LookupOrdinaryName);
  474. if (ObjectGetClass)
  475. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  476. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  477. FixItHint::CreateReplacement(
  478. SourceRange(OIRE->getOpLoc(),
  479. OIRE->getLocEnd()), ")");
  480. else
  481. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  482. }
  483. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  484. }
  485. }
  486. }
  487. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  488. // Handle any placeholder expressions which made it here.
  489. if (E->getType()->isPlaceholderType()) {
  490. ExprResult result = CheckPlaceholderExpr(E);
  491. if (result.isInvalid()) return ExprError();
  492. E = result.get();
  493. }
  494. // C++ [conv.lval]p1:
  495. // A glvalue of a non-function, non-array type T can be
  496. // converted to a prvalue.
  497. if (!E->isGLValue()) return E;
  498. QualType T = E->getType();
  499. assert(!T.isNull() && "r-value conversion on typeless expression?");
  500. // We don't want to throw lvalue-to-rvalue casts on top of
  501. // expressions of certain types in C++.
  502. if (getLangOpts().CPlusPlus &&
  503. (E->getType() == Context.OverloadTy ||
  504. T->isDependentType() ||
  505. T->isRecordType()))
  506. return E;
  507. // The C standard is actually really unclear on this point, and
  508. // DR106 tells us what the result should be but not why. It's
  509. // generally best to say that void types just doesn't undergo
  510. // lvalue-to-rvalue at all. Note that expressions of unqualified
  511. // 'void' type are never l-values, but qualified void can be.
  512. if (T->isVoidType())
  513. return E;
  514. // OpenCL usually rejects direct accesses to values of 'half' type.
  515. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
  516. T->isHalfType()) {
  517. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  518. << 0 << T;
  519. return ExprError();
  520. }
  521. CheckForNullPointerDereference(*this, E);
  522. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  523. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  524. &Context.Idents.get("object_getClass"),
  525. SourceLocation(), LookupOrdinaryName);
  526. if (ObjectGetClass)
  527. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  528. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  529. FixItHint::CreateReplacement(
  530. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  531. else
  532. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  533. }
  534. else if (const ObjCIvarRefExpr *OIRE =
  535. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  536. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  537. // C++ [conv.lval]p1:
  538. // [...] If T is a non-class type, the type of the prvalue is the
  539. // cv-unqualified version of T. Otherwise, the type of the
  540. // rvalue is T.
  541. //
  542. // C99 6.3.2.1p2:
  543. // If the lvalue has qualified type, the value has the unqualified
  544. // version of the type of the lvalue; otherwise, the value has the
  545. // type of the lvalue.
  546. if (T.hasQualifiers())
  547. T = T.getUnqualifiedType();
  548. UpdateMarkingForLValueToRValue(E);
  549. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  550. // balance that.
  551. if (getLangOpts().ObjCAutoRefCount &&
  552. E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  553. ExprNeedsCleanups = true;
  554. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  555. nullptr, VK_RValue);
  556. // C11 6.3.2.1p2:
  557. // ... if the lvalue has atomic type, the value has the non-atomic version
  558. // of the type of the lvalue ...
  559. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  560. T = Atomic->getValueType().getUnqualifiedType();
  561. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  562. nullptr, VK_RValue);
  563. }
  564. return Res;
  565. }
  566. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
  567. ExprResult Res = DefaultFunctionArrayConversion(E);
  568. if (Res.isInvalid())
  569. return ExprError();
  570. Res = DefaultLvalueConversion(Res.get());
  571. if (Res.isInvalid())
  572. return ExprError();
  573. return Res;
  574. }
  575. /// CallExprUnaryConversions - a special case of an unary conversion
  576. /// performed on a function designator of a call expression.
  577. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  578. QualType Ty = E->getType();
  579. ExprResult Res = E;
  580. // Only do implicit cast for a function type, but not for a pointer
  581. // to function type.
  582. if (Ty->isFunctionType()) {
  583. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  584. CK_FunctionToPointerDecay).get();
  585. if (Res.isInvalid())
  586. return ExprError();
  587. }
  588. Res = DefaultLvalueConversion(Res.get());
  589. if (Res.isInvalid())
  590. return ExprError();
  591. return Res.get();
  592. }
  593. /// UsualUnaryConversions - Performs various conversions that are common to most
  594. /// operators (C99 6.3). The conversions of array and function types are
  595. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  596. /// apply if the array is an argument to the sizeof or address (&) operators.
  597. /// In these instances, this routine should *not* be called.
  598. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  599. // First, convert to an r-value.
  600. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  601. if (Res.isInvalid())
  602. return ExprError();
  603. E = Res.get();
  604. QualType Ty = E->getType();
  605. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  606. // Half FP have to be promoted to float unless it is natively supported
  607. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  608. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  609. // Try to perform integral promotions if the object has a theoretically
  610. // promotable type.
  611. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  612. // C99 6.3.1.1p2:
  613. //
  614. // The following may be used in an expression wherever an int or
  615. // unsigned int may be used:
  616. // - an object or expression with an integer type whose integer
  617. // conversion rank is less than or equal to the rank of int
  618. // and unsigned int.
  619. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  620. //
  621. // If an int can represent all values of the original type, the
  622. // value is converted to an int; otherwise, it is converted to an
  623. // unsigned int. These are called the integer promotions. All
  624. // other types are unchanged by the integer promotions.
  625. QualType PTy = Context.isPromotableBitField(E);
  626. if (!PTy.isNull()) {
  627. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  628. return E;
  629. }
  630. if (Ty->isPromotableIntegerType()) {
  631. QualType PT = Context.getPromotedIntegerType(Ty);
  632. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  633. return E;
  634. }
  635. }
  636. return E;
  637. }
  638. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  639. /// do not have a prototype. Arguments that have type float or __fp16
  640. /// are promoted to double. All other argument types are converted by
  641. /// UsualUnaryConversions().
  642. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  643. QualType Ty = E->getType();
  644. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  645. ExprResult Res = UsualUnaryConversions(E);
  646. if (Res.isInvalid())
  647. return ExprError();
  648. E = Res.get();
  649. // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  650. // double.
  651. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  652. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  653. BTy->getKind() == BuiltinType::Float))
  654. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  655. // C++ performs lvalue-to-rvalue conversion as a default argument
  656. // promotion, even on class types, but note:
  657. // C++11 [conv.lval]p2:
  658. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  659. // operand or a subexpression thereof the value contained in the
  660. // referenced object is not accessed. Otherwise, if the glvalue
  661. // has a class type, the conversion copy-initializes a temporary
  662. // of type T from the glvalue and the result of the conversion
  663. // is a prvalue for the temporary.
  664. // FIXME: add some way to gate this entire thing for correctness in
  665. // potentially potentially evaluated contexts.
  666. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  667. ExprResult Temp = PerformCopyInitialization(
  668. InitializedEntity::InitializeTemporary(E->getType()),
  669. E->getExprLoc(), E);
  670. if (Temp.isInvalid())
  671. return ExprError();
  672. E = Temp.get();
  673. }
  674. return E;
  675. }
  676. /// Determine the degree of POD-ness for an expression.
  677. /// Incomplete types are considered POD, since this check can be performed
  678. /// when we're in an unevaluated context.
  679. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  680. if (Ty->isIncompleteType()) {
  681. // C++11 [expr.call]p7:
  682. // After these conversions, if the argument does not have arithmetic,
  683. // enumeration, pointer, pointer to member, or class type, the program
  684. // is ill-formed.
  685. //
  686. // Since we've already performed array-to-pointer and function-to-pointer
  687. // decay, the only such type in C++ is cv void. This also handles
  688. // initializer lists as variadic arguments.
  689. if (Ty->isVoidType())
  690. return VAK_Invalid;
  691. if (Ty->isObjCObjectType())
  692. return VAK_Invalid;
  693. return VAK_Valid;
  694. }
  695. if (Ty.isCXX98PODType(Context))
  696. return VAK_Valid;
  697. // C++11 [expr.call]p7:
  698. // Passing a potentially-evaluated argument of class type (Clause 9)
  699. // having a non-trivial copy constructor, a non-trivial move constructor,
  700. // or a non-trivial destructor, with no corresponding parameter,
  701. // is conditionally-supported with implementation-defined semantics.
  702. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  703. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  704. if (!Record->hasNonTrivialCopyConstructor() &&
  705. !Record->hasNonTrivialMoveConstructor() &&
  706. !Record->hasNonTrivialDestructor())
  707. return VAK_ValidInCXX11;
  708. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  709. return VAK_Valid;
  710. if (Ty->isObjCObjectType())
  711. return VAK_Invalid;
  712. if (getLangOpts().MSVCCompat)
  713. return VAK_MSVCUndefined;
  714. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  715. // permitted to reject them. We should consider doing so.
  716. return VAK_Undefined;
  717. }
  718. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  719. // Don't allow one to pass an Objective-C interface to a vararg.
  720. const QualType &Ty = E->getType();
  721. VarArgKind VAK = isValidVarArgType(Ty);
  722. // Complain about passing non-POD types through varargs.
  723. switch (VAK) {
  724. case VAK_ValidInCXX11:
  725. DiagRuntimeBehavior(
  726. E->getLocStart(), nullptr,
  727. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  728. << Ty << CT);
  729. // Fall through.
  730. case VAK_Valid:
  731. if (Ty->isRecordType()) {
  732. // This is unlikely to be what the user intended. If the class has a
  733. // 'c_str' member function, the user probably meant to call that.
  734. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  735. PDiag(diag::warn_pass_class_arg_to_vararg)
  736. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  737. }
  738. break;
  739. case VAK_Undefined:
  740. case VAK_MSVCUndefined:
  741. DiagRuntimeBehavior(
  742. E->getLocStart(), nullptr,
  743. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  744. << getLangOpts().CPlusPlus11 << Ty << CT);
  745. break;
  746. case VAK_Invalid:
  747. if (Ty->isObjCObjectType())
  748. DiagRuntimeBehavior(
  749. E->getLocStart(), nullptr,
  750. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  751. << Ty << CT);
  752. else
  753. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  754. << isa<InitListExpr>(E) << Ty << CT;
  755. break;
  756. }
  757. }
  758. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  759. /// will create a trap if the resulting type is not a POD type.
  760. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  761. FunctionDecl *FDecl) {
  762. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  763. // Strip the unbridged-cast placeholder expression off, if applicable.
  764. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  765. (CT == VariadicMethod ||
  766. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  767. E = stripARCUnbridgedCast(E);
  768. // Otherwise, do normal placeholder checking.
  769. } else {
  770. ExprResult ExprRes = CheckPlaceholderExpr(E);
  771. if (ExprRes.isInvalid())
  772. return ExprError();
  773. E = ExprRes.get();
  774. }
  775. }
  776. ExprResult ExprRes = DefaultArgumentPromotion(E);
  777. if (ExprRes.isInvalid())
  778. return ExprError();
  779. E = ExprRes.get();
  780. // Diagnostics regarding non-POD argument types are
  781. // emitted along with format string checking in Sema::CheckFunctionCall().
  782. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  783. // Turn this into a trap.
  784. CXXScopeSpec SS;
  785. SourceLocation TemplateKWLoc;
  786. UnqualifiedId Name;
  787. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  788. E->getLocStart());
  789. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  790. Name, true, false);
  791. if (TrapFn.isInvalid())
  792. return ExprError();
  793. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  794. E->getLocStart(), None,
  795. E->getLocEnd());
  796. if (Call.isInvalid())
  797. return ExprError();
  798. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  799. Call.get(), E);
  800. if (Comma.isInvalid())
  801. return ExprError();
  802. return Comma.get();
  803. }
  804. if (!getLangOpts().CPlusPlus &&
  805. RequireCompleteType(E->getExprLoc(), E->getType(),
  806. diag::err_call_incomplete_argument))
  807. return ExprError();
  808. return E;
  809. }
  810. /// \brief Converts an integer to complex float type. Helper function of
  811. /// UsualArithmeticConversions()
  812. ///
  813. /// \return false if the integer expression is an integer type and is
  814. /// successfully converted to the complex type.
  815. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  816. ExprResult &ComplexExpr,
  817. QualType IntTy,
  818. QualType ComplexTy,
  819. bool SkipCast) {
  820. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  821. if (SkipCast) return false;
  822. if (IntTy->isIntegerType()) {
  823. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  824. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  825. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  826. CK_FloatingRealToComplex);
  827. } else {
  828. assert(IntTy->isComplexIntegerType());
  829. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  830. CK_IntegralComplexToFloatingComplex);
  831. }
  832. return false;
  833. }
  834. /// \brief Handle arithmetic conversion with complex types. Helper function of
  835. /// UsualArithmeticConversions()
  836. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  837. ExprResult &RHS, QualType LHSType,
  838. QualType RHSType,
  839. bool IsCompAssign) {
  840. // if we have an integer operand, the result is the complex type.
  841. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  842. /*skipCast*/false))
  843. return LHSType;
  844. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  845. /*skipCast*/IsCompAssign))
  846. return RHSType;
  847. // This handles complex/complex, complex/float, or float/complex.
  848. // When both operands are complex, the shorter operand is converted to the
  849. // type of the longer, and that is the type of the result. This corresponds
  850. // to what is done when combining two real floating-point operands.
  851. // The fun begins when size promotion occur across type domains.
  852. // From H&S 6.3.4: When one operand is complex and the other is a real
  853. // floating-point type, the less precise type is converted, within it's
  854. // real or complex domain, to the precision of the other type. For example,
  855. // when combining a "long double" with a "double _Complex", the
  856. // "double _Complex" is promoted to "long double _Complex".
  857. // Compute the rank of the two types, regardless of whether they are complex.
  858. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  859. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  860. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  861. QualType LHSElementType =
  862. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  863. QualType RHSElementType =
  864. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  865. QualType ResultType = S.Context.getComplexType(LHSElementType);
  866. if (Order < 0) {
  867. // Promote the precision of the LHS if not an assignment.
  868. ResultType = S.Context.getComplexType(RHSElementType);
  869. if (!IsCompAssign) {
  870. if (LHSComplexType)
  871. LHS =
  872. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  873. else
  874. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  875. }
  876. } else if (Order > 0) {
  877. // Promote the precision of the RHS.
  878. if (RHSComplexType)
  879. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  880. else
  881. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  882. }
  883. return ResultType;
  884. }
  885. /// \brief Hande arithmetic conversion from integer to float. Helper function
  886. /// of UsualArithmeticConversions()
  887. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  888. ExprResult &IntExpr,
  889. QualType FloatTy, QualType IntTy,
  890. bool ConvertFloat, bool ConvertInt) {
  891. if (IntTy->isIntegerType()) {
  892. if (ConvertInt)
  893. // Convert intExpr to the lhs floating point type.
  894. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  895. CK_IntegralToFloating);
  896. return FloatTy;
  897. }
  898. // Convert both sides to the appropriate complex float.
  899. assert(IntTy->isComplexIntegerType());
  900. QualType result = S.Context.getComplexType(FloatTy);
  901. // _Complex int -> _Complex float
  902. if (ConvertInt)
  903. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  904. CK_IntegralComplexToFloatingComplex);
  905. // float -> _Complex float
  906. if (ConvertFloat)
  907. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  908. CK_FloatingRealToComplex);
  909. return result;
  910. }
  911. /// \brief Handle arithmethic conversion with floating point types. Helper
  912. /// function of UsualArithmeticConversions()
  913. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  914. ExprResult &RHS, QualType LHSType,
  915. QualType RHSType, bool IsCompAssign) {
  916. bool LHSFloat = LHSType->isRealFloatingType();
  917. bool RHSFloat = RHSType->isRealFloatingType();
  918. // If we have two real floating types, convert the smaller operand
  919. // to the bigger result.
  920. if (LHSFloat && RHSFloat) {
  921. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  922. if (order > 0) {
  923. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  924. return LHSType;
  925. }
  926. assert(order < 0 && "illegal float comparison");
  927. if (!IsCompAssign)
  928. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  929. return RHSType;
  930. }
  931. if (LHSFloat)
  932. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  933. /*convertFloat=*/!IsCompAssign,
  934. /*convertInt=*/ true);
  935. assert(RHSFloat);
  936. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  937. /*convertInt=*/ true,
  938. /*convertFloat=*/!IsCompAssign);
  939. }
  940. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  941. namespace {
  942. /// These helper callbacks are placed in an anonymous namespace to
  943. /// permit their use as function template parameters.
  944. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  945. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  946. }
  947. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  948. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  949. CK_IntegralComplexCast);
  950. }
  951. }
  952. /// \brief Handle integer arithmetic conversions. Helper function of
  953. /// UsualArithmeticConversions()
  954. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  955. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  956. ExprResult &RHS, QualType LHSType,
  957. QualType RHSType, bool IsCompAssign) {
  958. // The rules for this case are in C99 6.3.1.8
  959. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  960. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  961. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  962. if (LHSSigned == RHSSigned) {
  963. // Same signedness; use the higher-ranked type
  964. if (order >= 0) {
  965. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  966. return LHSType;
  967. } else if (!IsCompAssign)
  968. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  969. return RHSType;
  970. } else if (order != (LHSSigned ? 1 : -1)) {
  971. // The unsigned type has greater than or equal rank to the
  972. // signed type, so use the unsigned type
  973. if (RHSSigned) {
  974. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  975. return LHSType;
  976. } else if (!IsCompAssign)
  977. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  978. return RHSType;
  979. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  980. // The two types are different widths; if we are here, that
  981. // means the signed type is larger than the unsigned type, so
  982. // use the signed type.
  983. if (LHSSigned) {
  984. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  985. return LHSType;
  986. } else if (!IsCompAssign)
  987. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  988. return RHSType;
  989. } else {
  990. // The signed type is higher-ranked than the unsigned type,
  991. // but isn't actually any bigger (like unsigned int and long
  992. // on most 32-bit systems). Use the unsigned type corresponding
  993. // to the signed type.
  994. QualType result =
  995. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  996. RHS = (*doRHSCast)(S, RHS.get(), result);
  997. if (!IsCompAssign)
  998. LHS = (*doLHSCast)(S, LHS.get(), result);
  999. return result;
  1000. }
  1001. }
  1002. /// \brief Handle conversions with GCC complex int extension. Helper function
  1003. /// of UsualArithmeticConversions()
  1004. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1005. ExprResult &RHS, QualType LHSType,
  1006. QualType RHSType,
  1007. bool IsCompAssign) {
  1008. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1009. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1010. if (LHSComplexInt && RHSComplexInt) {
  1011. QualType LHSEltType = LHSComplexInt->getElementType();
  1012. QualType RHSEltType = RHSComplexInt->getElementType();
  1013. QualType ScalarType =
  1014. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1015. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1016. return S.Context.getComplexType(ScalarType);
  1017. }
  1018. if (LHSComplexInt) {
  1019. QualType LHSEltType = LHSComplexInt->getElementType();
  1020. QualType ScalarType =
  1021. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1022. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1023. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1024. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1025. CK_IntegralRealToComplex);
  1026. return ComplexType;
  1027. }
  1028. assert(RHSComplexInt);
  1029. QualType RHSEltType = RHSComplexInt->getElementType();
  1030. QualType ScalarType =
  1031. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1032. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1033. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1034. if (!IsCompAssign)
  1035. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1036. CK_IntegralRealToComplex);
  1037. return ComplexType;
  1038. }
  1039. /// UsualArithmeticConversions - Performs various conversions that are common to
  1040. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1041. /// routine returns the first non-arithmetic type found. The client is
  1042. /// responsible for emitting appropriate error diagnostics.
  1043. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1044. bool IsCompAssign) {
  1045. if (!IsCompAssign) {
  1046. LHS = UsualUnaryConversions(LHS.get());
  1047. if (LHS.isInvalid())
  1048. return QualType();
  1049. }
  1050. RHS = UsualUnaryConversions(RHS.get());
  1051. if (RHS.isInvalid())
  1052. return QualType();
  1053. // For conversion purposes, we ignore any qualifiers.
  1054. // For example, "const float" and "float" are equivalent.
  1055. QualType LHSType =
  1056. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1057. QualType RHSType =
  1058. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1059. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1060. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1061. LHSType = AtomicLHS->getValueType();
  1062. // If both types are identical, no conversion is needed.
  1063. if (LHSType == RHSType)
  1064. return LHSType;
  1065. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1066. // The caller can deal with this (e.g. pointer + int).
  1067. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1068. return QualType();
  1069. // Apply unary and bitfield promotions to the LHS's type.
  1070. QualType LHSUnpromotedType = LHSType;
  1071. if (LHSType->isPromotableIntegerType())
  1072. LHSType = Context.getPromotedIntegerType(LHSType);
  1073. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1074. if (!LHSBitfieldPromoteTy.isNull())
  1075. LHSType = LHSBitfieldPromoteTy;
  1076. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1077. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1078. // If both types are identical, no conversion is needed.
  1079. if (LHSType == RHSType)
  1080. return LHSType;
  1081. // At this point, we have two different arithmetic types.
  1082. // Handle complex types first (C99 6.3.1.8p1).
  1083. if (LHSType->isComplexType() || RHSType->isComplexType())
  1084. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1085. IsCompAssign);
  1086. // Now handle "real" floating types (i.e. float, double, long double).
  1087. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1088. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1089. IsCompAssign);
  1090. // Handle GCC complex int extension.
  1091. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1092. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1093. IsCompAssign);
  1094. // Finally, we have two differing integer types.
  1095. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1096. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1097. }
  1098. //===----------------------------------------------------------------------===//
  1099. // Semantic Analysis for various Expression Types
  1100. //===----------------------------------------------------------------------===//
  1101. ExprResult
  1102. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1103. SourceLocation DefaultLoc,
  1104. SourceLocation RParenLoc,
  1105. Expr *ControllingExpr,
  1106. ArrayRef<ParsedType> ArgTypes,
  1107. ArrayRef<Expr *> ArgExprs) {
  1108. unsigned NumAssocs = ArgTypes.size();
  1109. assert(NumAssocs == ArgExprs.size());
  1110. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1111. for (unsigned i = 0; i < NumAssocs; ++i) {
  1112. if (ArgTypes[i])
  1113. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1114. else
  1115. Types[i] = nullptr;
  1116. }
  1117. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1118. ControllingExpr,
  1119. llvm::makeArrayRef(Types, NumAssocs),
  1120. ArgExprs);
  1121. delete [] Types;
  1122. return ER;
  1123. }
  1124. ExprResult
  1125. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1126. SourceLocation DefaultLoc,
  1127. SourceLocation RParenLoc,
  1128. Expr *ControllingExpr,
  1129. ArrayRef<TypeSourceInfo *> Types,
  1130. ArrayRef<Expr *> Exprs) {
  1131. unsigned NumAssocs = Types.size();
  1132. assert(NumAssocs == Exprs.size());
  1133. if (ControllingExpr->getType()->isPlaceholderType()) {
  1134. ExprResult result = CheckPlaceholderExpr(ControllingExpr);
  1135. if (result.isInvalid()) return ExprError();
  1136. ControllingExpr = result.get();
  1137. }
  1138. // The controlling expression is an unevaluated operand, so side effects are
  1139. // likely unintended.
  1140. if (ActiveTemplateInstantiations.empty() &&
  1141. ControllingExpr->HasSideEffects(Context, false))
  1142. Diag(ControllingExpr->getExprLoc(),
  1143. diag::warn_side_effects_unevaluated_context);
  1144. bool TypeErrorFound = false,
  1145. IsResultDependent = ControllingExpr->isTypeDependent(),
  1146. ContainsUnexpandedParameterPack
  1147. = ControllingExpr->containsUnexpandedParameterPack();
  1148. for (unsigned i = 0; i < NumAssocs; ++i) {
  1149. if (Exprs[i]->containsUnexpandedParameterPack())
  1150. ContainsUnexpandedParameterPack = true;
  1151. if (Types[i]) {
  1152. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1153. ContainsUnexpandedParameterPack = true;
  1154. if (Types[i]->getType()->isDependentType()) {
  1155. IsResultDependent = true;
  1156. } else {
  1157. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1158. // complete object type other than a variably modified type."
  1159. unsigned D = 0;
  1160. if (Types[i]->getType()->isIncompleteType())
  1161. D = diag::err_assoc_type_incomplete;
  1162. else if (!Types[i]->getType()->isObjectType())
  1163. D = diag::err_assoc_type_nonobject;
  1164. else if (Types[i]->getType()->isVariablyModifiedType())
  1165. D = diag::err_assoc_type_variably_modified;
  1166. if (D != 0) {
  1167. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1168. << Types[i]->getTypeLoc().getSourceRange()
  1169. << Types[i]->getType();
  1170. TypeErrorFound = true;
  1171. }
  1172. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1173. // selection shall specify compatible types."
  1174. for (unsigned j = i+1; j < NumAssocs; ++j)
  1175. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1176. Context.typesAreCompatible(Types[i]->getType(),
  1177. Types[j]->getType())) {
  1178. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1179. diag::err_assoc_compatible_types)
  1180. << Types[j]->getTypeLoc().getSourceRange()
  1181. << Types[j]->getType()
  1182. << Types[i]->getType();
  1183. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1184. diag::note_compat_assoc)
  1185. << Types[i]->getTypeLoc().getSourceRange()
  1186. << Types[i]->getType();
  1187. TypeErrorFound = true;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. if (TypeErrorFound)
  1193. return ExprError();
  1194. // If we determined that the generic selection is result-dependent, don't
  1195. // try to compute the result expression.
  1196. if (IsResultDependent)
  1197. return new (Context) GenericSelectionExpr(
  1198. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1199. ContainsUnexpandedParameterPack);
  1200. SmallVector<unsigned, 1> CompatIndices;
  1201. unsigned DefaultIndex = -1U;
  1202. for (unsigned i = 0; i < NumAssocs; ++i) {
  1203. if (!Types[i])
  1204. DefaultIndex = i;
  1205. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1206. Types[i]->getType()))
  1207. CompatIndices.push_back(i);
  1208. }
  1209. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1210. // type compatible with at most one of the types named in its generic
  1211. // association list."
  1212. if (CompatIndices.size() > 1) {
  1213. // We strip parens here because the controlling expression is typically
  1214. // parenthesized in macro definitions.
  1215. ControllingExpr = ControllingExpr->IgnoreParens();
  1216. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1217. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1218. << (unsigned) CompatIndices.size();
  1219. for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
  1220. E = CompatIndices.end(); I != E; ++I) {
  1221. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1222. diag::note_compat_assoc)
  1223. << Types[*I]->getTypeLoc().getSourceRange()
  1224. << Types[*I]->getType();
  1225. }
  1226. return ExprError();
  1227. }
  1228. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1229. // its controlling expression shall have type compatible with exactly one of
  1230. // the types named in its generic association list."
  1231. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1232. // We strip parens here because the controlling expression is typically
  1233. // parenthesized in macro definitions.
  1234. ControllingExpr = ControllingExpr->IgnoreParens();
  1235. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1236. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1237. return ExprError();
  1238. }
  1239. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1240. // type name that is compatible with the type of the controlling expression,
  1241. // then the result expression of the generic selection is the expression
  1242. // in that generic association. Otherwise, the result expression of the
  1243. // generic selection is the expression in the default generic association."
  1244. unsigned ResultIndex =
  1245. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1246. return new (Context) GenericSelectionExpr(
  1247. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1248. ContainsUnexpandedParameterPack, ResultIndex);
  1249. }
  1250. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1251. /// location of the token and the offset of the ud-suffix within it.
  1252. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1253. unsigned Offset) {
  1254. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1255. S.getLangOpts());
  1256. }
  1257. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1258. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1259. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1260. IdentifierInfo *UDSuffix,
  1261. SourceLocation UDSuffixLoc,
  1262. ArrayRef<Expr*> Args,
  1263. SourceLocation LitEndLoc) {
  1264. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1265. QualType ArgTy[2];
  1266. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1267. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1268. if (ArgTy[ArgIdx]->isArrayType())
  1269. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1270. }
  1271. DeclarationName OpName =
  1272. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1273. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1274. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1275. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1276. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1277. /*AllowRaw*/false, /*AllowTemplate*/false,
  1278. /*AllowStringTemplate*/false) == Sema::LOLR_Error)
  1279. return ExprError();
  1280. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1281. }
  1282. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1283. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1284. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1285. /// multiple tokens. However, the common case is that StringToks points to one
  1286. /// string.
  1287. ///
  1288. ExprResult
  1289. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1290. assert(!StringToks.empty() && "Must have at least one string!");
  1291. StringLiteralParser Literal(StringToks, PP);
  1292. if (Literal.hadError)
  1293. return ExprError();
  1294. SmallVector<SourceLocation, 4> StringTokLocs;
  1295. for (unsigned i = 0; i != StringToks.size(); ++i)
  1296. StringTokLocs.push_back(StringToks[i].getLocation());
  1297. QualType CharTy = Context.CharTy;
  1298. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1299. if (Literal.isWide()) {
  1300. CharTy = Context.getWideCharType();
  1301. Kind = StringLiteral::Wide;
  1302. } else if (Literal.isUTF8()) {
  1303. Kind = StringLiteral::UTF8;
  1304. } else if (Literal.isUTF16()) {
  1305. CharTy = Context.Char16Ty;
  1306. Kind = StringLiteral::UTF16;
  1307. } else if (Literal.isUTF32()) {
  1308. CharTy = Context.Char32Ty;
  1309. Kind = StringLiteral::UTF32;
  1310. } else if (Literal.isPascal()) {
  1311. CharTy = Context.UnsignedCharTy;
  1312. }
  1313. QualType CharTyConst = CharTy;
  1314. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1315. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1316. CharTyConst.addConst();
  1317. // Get an array type for the string, according to C99 6.4.5. This includes
  1318. // the nul terminator character as well as the string length for pascal
  1319. // strings.
  1320. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1321. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1322. ArrayType::Normal, 0);
  1323. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1324. if (getLangOpts().OpenCL) {
  1325. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1326. }
  1327. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1328. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1329. Kind, Literal.Pascal, StrTy,
  1330. &StringTokLocs[0],
  1331. StringTokLocs.size());
  1332. if (Literal.getUDSuffix().empty())
  1333. return Lit;
  1334. // We're building a user-defined literal.
  1335. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1336. SourceLocation UDSuffixLoc =
  1337. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1338. Literal.getUDSuffixOffset());
  1339. // Make sure we're allowed user-defined literals here.
  1340. if (!UDLScope)
  1341. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1342. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1343. // operator "" X (str, len)
  1344. QualType SizeType = Context.getSizeType();
  1345. DeclarationName OpName =
  1346. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1347. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1348. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1349. QualType ArgTy[] = {
  1350. Context.getArrayDecayedType(StrTy), SizeType
  1351. };
  1352. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1353. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1354. /*AllowRaw*/false, /*AllowTemplate*/false,
  1355. /*AllowStringTemplate*/true)) {
  1356. case LOLR_Cooked: {
  1357. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1358. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1359. StringTokLocs[0]);
  1360. Expr *Args[] = { Lit, LenArg };
  1361. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1362. }
  1363. case LOLR_StringTemplate: {
  1364. TemplateArgumentListInfo ExplicitArgs;
  1365. unsigned CharBits = Context.getIntWidth(CharTy);
  1366. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1367. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1368. TemplateArgument TypeArg(CharTy);
  1369. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1370. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1371. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1372. Value = Lit->getCodeUnit(I);
  1373. TemplateArgument Arg(Context, Value, CharTy);
  1374. TemplateArgumentLocInfo ArgInfo;
  1375. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1376. }
  1377. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1378. &ExplicitArgs);
  1379. }
  1380. case LOLR_Raw:
  1381. case LOLR_Template:
  1382. llvm_unreachable("unexpected literal operator lookup result");
  1383. case LOLR_Error:
  1384. return ExprError();
  1385. }
  1386. llvm_unreachable("unexpected literal operator lookup result");
  1387. }
  1388. ExprResult
  1389. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1390. SourceLocation Loc,
  1391. const CXXScopeSpec *SS) {
  1392. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1393. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1394. }
  1395. /// BuildDeclRefExpr - Build an expression that references a
  1396. /// declaration that does not require a closure capture.
  1397. ExprResult
  1398. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1399. const DeclarationNameInfo &NameInfo,
  1400. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1401. const TemplateArgumentListInfo *TemplateArgs) {
  1402. if (getLangOpts().CUDA)
  1403. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1404. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1405. if (CheckCUDATarget(Caller, Callee)) {
  1406. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1407. << IdentifyCUDATarget(Callee) << D->getIdentifier()
  1408. << IdentifyCUDATarget(Caller);
  1409. Diag(D->getLocation(), diag::note_previous_decl)
  1410. << D->getIdentifier();
  1411. return ExprError();
  1412. }
  1413. }
  1414. bool RefersToCapturedVariable =
  1415. isa<VarDecl>(D) &&
  1416. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1417. DeclRefExpr *E;
  1418. if (isa<VarTemplateSpecializationDecl>(D)) {
  1419. VarTemplateSpecializationDecl *VarSpec =
  1420. cast<VarTemplateSpecializationDecl>(D);
  1421. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1422. : NestedNameSpecifierLoc(),
  1423. VarSpec->getTemplateKeywordLoc(), D,
  1424. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1425. FoundD, TemplateArgs);
  1426. } else {
  1427. assert(!TemplateArgs && "No template arguments for non-variable"
  1428. " template specialization references");
  1429. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1430. : NestedNameSpecifierLoc(),
  1431. SourceLocation(), D, RefersToCapturedVariable,
  1432. NameInfo, Ty, VK, FoundD);
  1433. }
  1434. MarkDeclRefReferenced(E);
  1435. if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
  1436. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1437. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1438. recordUseOfEvaluatedWeak(E);
  1439. // Just in case we're building an illegal pointer-to-member.
  1440. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1441. if (FD && FD->isBitField())
  1442. E->setObjectKind(OK_BitField);
  1443. return E;
  1444. }
  1445. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1446. /// possibly a list of template arguments.
  1447. ///
  1448. /// If this produces template arguments, it is permitted to call
  1449. /// DecomposeTemplateName.
  1450. ///
  1451. /// This actually loses a lot of source location information for
  1452. /// non-standard name kinds; we should consider preserving that in
  1453. /// some way.
  1454. void
  1455. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1456. TemplateArgumentListInfo &Buffer,
  1457. DeclarationNameInfo &NameInfo,
  1458. const TemplateArgumentListInfo *&TemplateArgs) {
  1459. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1460. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1461. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1462. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1463. Id.TemplateId->NumArgs);
  1464. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1465. TemplateName TName = Id.TemplateId->Template.get();
  1466. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1467. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1468. TemplateArgs = &Buffer;
  1469. } else {
  1470. NameInfo = GetNameFromUnqualifiedId(Id);
  1471. TemplateArgs = nullptr;
  1472. }
  1473. }
  1474. static void emitEmptyLookupTypoDiagnostic(
  1475. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1476. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1477. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1478. DeclContext *Ctx =
  1479. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1480. if (!TC) {
  1481. // Emit a special diagnostic for failed member lookups.
  1482. // FIXME: computing the declaration context might fail here (?)
  1483. if (Ctx)
  1484. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1485. << SS.getRange();
  1486. else
  1487. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1488. return;
  1489. }
  1490. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1491. bool DroppedSpecifier =
  1492. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1493. unsigned NoteID =
  1494. (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
  1495. ? diag::note_implicit_param_decl
  1496. : diag::note_previous_decl;
  1497. if (!Ctx)
  1498. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1499. SemaRef.PDiag(NoteID));
  1500. else
  1501. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1502. << Typo << Ctx << DroppedSpecifier
  1503. << SS.getRange(),
  1504. SemaRef.PDiag(NoteID));
  1505. }
  1506. /// Diagnose an empty lookup.
  1507. ///
  1508. /// \return false if new lookup candidates were found
  1509. bool
  1510. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1511. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1512. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1513. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1514. DeclarationName Name = R.getLookupName();
  1515. unsigned diagnostic = diag::err_undeclared_var_use;
  1516. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1517. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1518. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1519. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1520. diagnostic = diag::err_undeclared_use;
  1521. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1522. }
  1523. // If the original lookup was an unqualified lookup, fake an
  1524. // unqualified lookup. This is useful when (for example) the
  1525. // original lookup would not have found something because it was a
  1526. // dependent name.
  1527. DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
  1528. ? CurContext : nullptr;
  1529. while (DC) {
  1530. if (isa<CXXRecordDecl>(DC)) {
  1531. LookupQualifiedName(R, DC);
  1532. if (!R.empty()) {
  1533. // Don't give errors about ambiguities in this lookup.
  1534. R.suppressDiagnostics();
  1535. // During a default argument instantiation the CurContext points
  1536. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1537. // function parameter list, hence add an explicit check.
  1538. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1539. ActiveTemplateInstantiations.back().Kind ==
  1540. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1541. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1542. bool isInstance = CurMethod &&
  1543. CurMethod->isInstance() &&
  1544. DC == CurMethod->getParent() && !isDefaultArgument;
  1545. // Give a code modification hint to insert 'this->'.
  1546. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1547. // Actually quite difficult!
  1548. if (getLangOpts().MSVCCompat)
  1549. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1550. if (isInstance) {
  1551. Diag(R.getNameLoc(), diagnostic) << Name
  1552. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1553. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
  1554. CallsUndergoingInstantiation.back()->getCallee());
  1555. CXXMethodDecl *DepMethod;
  1556. if (CurMethod->isDependentContext())
  1557. DepMethod = CurMethod;
  1558. else if (CurMethod->getTemplatedKind() ==
  1559. FunctionDecl::TK_FunctionTemplateSpecialization)
  1560. DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
  1561. getInstantiatedFromMemberTemplate()->getTemplatedDecl());
  1562. else
  1563. DepMethod = cast<CXXMethodDecl>(
  1564. CurMethod->getInstantiatedFromMemberFunction());
  1565. assert(DepMethod && "No template pattern found");
  1566. QualType DepThisType = DepMethod->getThisType(Context);
  1567. CheckCXXThisCapture(R.getNameLoc());
  1568. CXXThisExpr *DepThis = new (Context) CXXThisExpr(
  1569. R.getNameLoc(), DepThisType, false);
  1570. TemplateArgumentListInfo TList;
  1571. if (ULE->hasExplicitTemplateArgs())
  1572. ULE->copyTemplateArgumentsInto(TList);
  1573. CXXScopeSpec SS;
  1574. SS.Adopt(ULE->getQualifierLoc());
  1575. CXXDependentScopeMemberExpr *DepExpr =
  1576. CXXDependentScopeMemberExpr::Create(
  1577. Context, DepThis, DepThisType, true, SourceLocation(),
  1578. SS.getWithLocInContext(Context),
  1579. ULE->getTemplateKeywordLoc(), nullptr,
  1580. R.getLookupNameInfo(),
  1581. ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
  1582. CallsUndergoingInstantiation.back()->setCallee(DepExpr);
  1583. } else {
  1584. Diag(R.getNameLoc(), diagnostic) << Name;
  1585. }
  1586. // Do we really want to note all of these?
  1587. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1588. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1589. // Return true if we are inside a default argument instantiation
  1590. // and the found name refers to an instance member function, otherwise
  1591. // the function calling DiagnoseEmptyLookup will try to create an
  1592. // implicit member call and this is wrong for default argument.
  1593. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1594. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1595. return true;
  1596. }
  1597. // Tell the callee to try to recover.
  1598. return false;
  1599. }
  1600. R.clear();
  1601. }
  1602. // In Microsoft mode, if we are performing lookup from within a friend
  1603. // function definition declared at class scope then we must set
  1604. // DC to the lexical parent to be able to search into the parent
  1605. // class.
  1606. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1607. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1608. DC->getLexicalParent()->isRecord())
  1609. DC = DC->getLexicalParent();
  1610. else
  1611. DC = DC->getParent();
  1612. }
  1613. // We didn't find anything, so try to correct for a typo.
  1614. TypoCorrection Corrected;
  1615. if (S && Out) {
  1616. SourceLocation TypoLoc = R.getNameLoc();
  1617. assert(!ExplicitTemplateArgs &&
  1618. "Diagnosing an empty lookup with explicit template args!");
  1619. *Out = CorrectTypoDelayed(
  1620. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1621. [=](const TypoCorrection &TC) {
  1622. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1623. diagnostic, diagnostic_suggest);
  1624. },
  1625. nullptr, CTK_ErrorRecovery);
  1626. if (*Out)
  1627. return true;
  1628. } else if (S && (Corrected =
  1629. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1630. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1631. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1632. bool DroppedSpecifier =
  1633. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1634. R.setLookupName(Corrected.getCorrection());
  1635. bool AcceptableWithRecovery = false;
  1636. bool AcceptableWithoutRecovery = false;
  1637. NamedDecl *ND = Corrected.getCorrectionDecl();
  1638. if (ND) {
  1639. if (Corrected.isOverloaded()) {
  1640. OverloadCandidateSet OCS(R.getNameLoc(),
  1641. OverloadCandidateSet::CSK_Normal);
  1642. OverloadCandidateSet::iterator Best;
  1643. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1644. CDEnd = Corrected.end();
  1645. CD != CDEnd; ++CD) {
  1646. if (FunctionTemplateDecl *FTD =
  1647. dyn_cast<FunctionTemplateDecl>(*CD))
  1648. AddTemplateOverloadCandidate(
  1649. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1650. Args, OCS);
  1651. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1652. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1653. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1654. Args, OCS);
  1655. }
  1656. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1657. case OR_Success:
  1658. ND = Best->Function;
  1659. Corrected.setCorrectionDecl(ND);
  1660. break;
  1661. default:
  1662. // FIXME: Arbitrarily pick the first declaration for the note.
  1663. Corrected.setCorrectionDecl(ND);
  1664. break;
  1665. }
  1666. }
  1667. R.addDecl(ND);
  1668. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1669. CXXRecordDecl *Record = nullptr;
  1670. if (Corrected.getCorrectionSpecifier()) {
  1671. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1672. Record = Ty->getAsCXXRecordDecl();
  1673. }
  1674. if (!Record)
  1675. Record = cast<CXXRecordDecl>(
  1676. ND->getDeclContext()->getRedeclContext());
  1677. R.setNamingClass(Record);
  1678. }
  1679. AcceptableWithRecovery =
  1680. isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
  1681. // FIXME: If we ended up with a typo for a type name or
  1682. // Objective-C class name, we're in trouble because the parser
  1683. // is in the wrong place to recover. Suggest the typo
  1684. // correction, but don't make it a fix-it since we're not going
  1685. // to recover well anyway.
  1686. AcceptableWithoutRecovery =
  1687. isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1688. } else {
  1689. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1690. // because we aren't able to recover.
  1691. AcceptableWithoutRecovery = true;
  1692. }
  1693. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1694. unsigned NoteID = (Corrected.getCorrectionDecl() &&
  1695. isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
  1696. ? diag::note_implicit_param_decl
  1697. : diag::note_previous_decl;
  1698. if (SS.isEmpty())
  1699. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1700. PDiag(NoteID), AcceptableWithRecovery);
  1701. else
  1702. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1703. << Name << computeDeclContext(SS, false)
  1704. << DroppedSpecifier << SS.getRange(),
  1705. PDiag(NoteID), AcceptableWithRecovery);
  1706. // Tell the callee whether to try to recover.
  1707. return !AcceptableWithRecovery;
  1708. }
  1709. }
  1710. R.clear();
  1711. // Emit a special diagnostic for failed member lookups.
  1712. // FIXME: computing the declaration context might fail here (?)
  1713. if (!SS.isEmpty()) {
  1714. Diag(R.getNameLoc(), diag::err_no_member)
  1715. << Name << computeDeclContext(SS, false)
  1716. << SS.getRange();
  1717. return true;
  1718. }
  1719. // Give up, we can't recover.
  1720. Diag(R.getNameLoc(), diagnostic) << Name;
  1721. return true;
  1722. }
  1723. /// In Microsoft mode, if we are inside a template class whose parent class has
  1724. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1725. /// assume the identifier is a member of a dependent base class. We can only
  1726. /// recover successfully in static methods, instance methods, and other contexts
  1727. /// where 'this' is available. This doesn't precisely match MSVC's
  1728. /// instantiation model, but it's close enough.
  1729. static Expr *
  1730. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1731. DeclarationNameInfo &NameInfo,
  1732. SourceLocation TemplateKWLoc,
  1733. const TemplateArgumentListInfo *TemplateArgs) {
  1734. // Only try to recover from lookup into dependent bases in static methods or
  1735. // contexts where 'this' is available.
  1736. QualType ThisType = S.getCurrentThisType();
  1737. const CXXRecordDecl *RD = nullptr;
  1738. if (!ThisType.isNull())
  1739. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1740. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1741. RD = MD->getParent();
  1742. if (!RD || !RD->hasAnyDependentBases())
  1743. return nullptr;
  1744. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1745. // is available, suggest inserting 'this->' as a fixit.
  1746. SourceLocation Loc = NameInfo.getLoc();
  1747. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1748. DB << NameInfo.getName() << RD;
  1749. if (!ThisType.isNull()) {
  1750. DB << FixItHint::CreateInsertion(Loc, "this->");
  1751. return CXXDependentScopeMemberExpr::Create(
  1752. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1753. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1754. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1755. }
  1756. // Synthesize a fake NNS that points to the derived class. This will
  1757. // perform name lookup during template instantiation.
  1758. CXXScopeSpec SS;
  1759. auto *NNS =
  1760. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1761. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1762. return DependentScopeDeclRefExpr::Create(
  1763. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1764. TemplateArgs);
  1765. }
  1766. ExprResult
  1767. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1768. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1769. bool HasTrailingLParen, bool IsAddressOfOperand,
  1770. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1771. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1772. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1773. "cannot be direct & operand and have a trailing lparen");
  1774. if (SS.isInvalid())
  1775. return ExprError();
  1776. TemplateArgumentListInfo TemplateArgsBuffer;
  1777. // Decompose the UnqualifiedId into the following data.
  1778. DeclarationNameInfo NameInfo;
  1779. const TemplateArgumentListInfo *TemplateArgs;
  1780. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1781. DeclarationName Name = NameInfo.getName();
  1782. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1783. SourceLocation NameLoc = NameInfo.getLoc();
  1784. // C++ [temp.dep.expr]p3:
  1785. // An id-expression is type-dependent if it contains:
  1786. // -- an identifier that was declared with a dependent type,
  1787. // (note: handled after lookup)
  1788. // -- a template-id that is dependent,
  1789. // (note: handled in BuildTemplateIdExpr)
  1790. // -- a conversion-function-id that specifies a dependent type,
  1791. // -- a nested-name-specifier that contains a class-name that
  1792. // names a dependent type.
  1793. // Determine whether this is a member of an unknown specialization;
  1794. // we need to handle these differently.
  1795. bool DependentID = false;
  1796. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1797. Name.getCXXNameType()->isDependentType()) {
  1798. DependentID = true;
  1799. } else if (SS.isSet()) {
  1800. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1801. if (RequireCompleteDeclContext(SS, DC))
  1802. return ExprError();
  1803. } else {
  1804. DependentID = true;
  1805. }
  1806. }
  1807. if (DependentID)
  1808. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1809. IsAddressOfOperand, TemplateArgs);
  1810. // Perform the required lookup.
  1811. LookupResult R(*this, NameInfo,
  1812. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1813. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1814. if (TemplateArgs) {
  1815. // Lookup the template name again to correctly establish the context in
  1816. // which it was found. This is really unfortunate as we already did the
  1817. // lookup to determine that it was a template name in the first place. If
  1818. // this becomes a performance hit, we can work harder to preserve those
  1819. // results until we get here but it's likely not worth it.
  1820. bool MemberOfUnknownSpecialization;
  1821. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1822. MemberOfUnknownSpecialization);
  1823. if (MemberOfUnknownSpecialization ||
  1824. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1825. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1826. IsAddressOfOperand, TemplateArgs);
  1827. } else {
  1828. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1829. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1830. // If the result might be in a dependent base class, this is a dependent
  1831. // id-expression.
  1832. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1833. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1834. IsAddressOfOperand, TemplateArgs);
  1835. // If this reference is in an Objective-C method, then we need to do
  1836. // some special Objective-C lookup, too.
  1837. if (IvarLookupFollowUp) {
  1838. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1839. if (E.isInvalid())
  1840. return ExprError();
  1841. if (Expr *Ex = E.getAs<Expr>())
  1842. return Ex;
  1843. }
  1844. }
  1845. if (R.isAmbiguous())
  1846. return ExprError();
  1847. // This could be an implicitly declared function reference (legal in C90,
  1848. // extension in C99, forbidden in C++).
  1849. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1850. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1851. if (D) R.addDecl(D);
  1852. }
  1853. // Determine whether this name might be a candidate for
  1854. // argument-dependent lookup.
  1855. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1856. if (R.empty() && !ADL) {
  1857. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1858. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1859. TemplateKWLoc, TemplateArgs))
  1860. return E;
  1861. }
  1862. // Don't diagnose an empty lookup for inline assembly.
  1863. if (IsInlineAsmIdentifier)
  1864. return ExprError();
  1865. // If this name wasn't predeclared and if this is not a function
  1866. // call, diagnose the problem.
  1867. TypoExpr *TE = nullptr;
  1868. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1869. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1870. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1871. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1872. "Typo correction callback misconfigured");
  1873. if (CCC) {
  1874. // Make sure the callback knows what the typo being diagnosed is.
  1875. CCC->setTypoName(II);
  1876. if (SS.isValid())
  1877. CCC->setTypoNNS(SS.getScopeRep());
  1878. }
  1879. if (DiagnoseEmptyLookup(S, SS, R,
  1880. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1881. nullptr, None, &TE)) {
  1882. if (TE && KeywordReplacement) {
  1883. auto &State = getTypoExprState(TE);
  1884. auto BestTC = State.Consumer->getNextCorrection();
  1885. if (BestTC.isKeyword()) {
  1886. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1887. if (State.DiagHandler)
  1888. State.DiagHandler(BestTC);
  1889. KeywordReplacement->startToken();
  1890. KeywordReplacement->setKind(II->getTokenID());
  1891. KeywordReplacement->setIdentifierInfo(II);
  1892. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1893. // Clean up the state associated with the TypoExpr, since it has
  1894. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1895. clearDelayedTypo(TE);
  1896. // Signal that a correction to a keyword was performed by returning a
  1897. // valid-but-null ExprResult.
  1898. return (Expr*)nullptr;
  1899. }
  1900. State.Consumer->resetCorrectionStream();
  1901. }
  1902. return TE ? TE : ExprError();
  1903. }
  1904. assert(!R.empty() &&
  1905. "DiagnoseEmptyLookup returned false but added no results");
  1906. // If we found an Objective-C instance variable, let
  1907. // LookupInObjCMethod build the appropriate expression to
  1908. // reference the ivar.
  1909. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1910. R.clear();
  1911. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1912. // In a hopelessly buggy code, Objective-C instance variable
  1913. // lookup fails and no expression will be built to reference it.
  1914. if (!E.isInvalid() && !E.get())
  1915. return ExprError();
  1916. return E;
  1917. }
  1918. }
  1919. // This is guaranteed from this point on.
  1920. assert(!R.empty() || ADL);
  1921. // Check whether this might be a C++ implicit instance member access.
  1922. // C++ [class.mfct.non-static]p3:
  1923. // When an id-expression that is not part of a class member access
  1924. // syntax and not used to form a pointer to member is used in the
  1925. // body of a non-static member function of class X, if name lookup
  1926. // resolves the name in the id-expression to a non-static non-type
  1927. // member of some class C, the id-expression is transformed into a
  1928. // class member access expression using (*this) as the
  1929. // postfix-expression to the left of the . operator.
  1930. //
  1931. // But we don't actually need to do this for '&' operands if R
  1932. // resolved to a function or overloaded function set, because the
  1933. // expression is ill-formed if it actually works out to be a
  1934. // non-static member function:
  1935. //
  1936. // C++ [expr.ref]p4:
  1937. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1938. // [t]he expression can be used only as the left-hand operand of a
  1939. // member function call.
  1940. //
  1941. // There are other safeguards against such uses, but it's important
  1942. // to get this right here so that we don't end up making a
  1943. // spuriously dependent expression if we're inside a dependent
  1944. // instance method.
  1945. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  1946. bool MightBeImplicitMember;
  1947. if (!IsAddressOfOperand)
  1948. MightBeImplicitMember = true;
  1949. else if (!SS.isEmpty())
  1950. MightBeImplicitMember = false;
  1951. else if (R.isOverloadedResult())
  1952. MightBeImplicitMember = false;
  1953. else if (R.isUnresolvableResult())
  1954. MightBeImplicitMember = true;
  1955. else
  1956. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  1957. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  1958. isa<MSPropertyDecl>(R.getFoundDecl());
  1959. if (MightBeImplicitMember)
  1960. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  1961. R, TemplateArgs);
  1962. }
  1963. if (TemplateArgs || TemplateKWLoc.isValid()) {
  1964. // In C++1y, if this is a variable template id, then check it
  1965. // in BuildTemplateIdExpr().
  1966. // The single lookup result must be a variable template declaration.
  1967. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  1968. Id.TemplateId->Kind == TNK_Var_template) {
  1969. assert(R.getAsSingle<VarTemplateDecl>() &&
  1970. "There should only be one declaration found.");
  1971. }
  1972. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  1973. }
  1974. return BuildDeclarationNameExpr(SS, R, ADL);
  1975. }
  1976. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  1977. /// declaration name, generally during template instantiation.
  1978. /// There's a large number of things which don't need to be done along
  1979. /// this path.
  1980. ExprResult
  1981. Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
  1982. const DeclarationNameInfo &NameInfo,
  1983. bool IsAddressOfOperand,
  1984. TypeSourceInfo **RecoveryTSI) {
  1985. DeclContext *DC = computeDeclContext(SS, false);
  1986. if (!DC)
  1987. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  1988. NameInfo, /*TemplateArgs=*/nullptr);
  1989. if (RequireCompleteDeclContext(SS, DC))
  1990. return ExprError();
  1991. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  1992. LookupQualifiedName(R, DC);
  1993. if (R.isAmbiguous())
  1994. return ExprError();
  1995. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1996. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  1997. NameInfo, /*TemplateArgs=*/nullptr);
  1998. if (R.empty()) {
  1999. Diag(NameInfo.getLoc(), diag::err_no_member)
  2000. << NameInfo.getName() << DC << SS.getRange();
  2001. return ExprError();
  2002. }
  2003. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2004. // Diagnose a missing typename if this resolved unambiguously to a type in
  2005. // a dependent context. If we can recover with a type, downgrade this to
  2006. // a warning in Microsoft compatibility mode.
  2007. unsigned DiagID = diag::err_typename_missing;
  2008. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2009. DiagID = diag::ext_typename_missing;
  2010. SourceLocation Loc = SS.getBeginLoc();
  2011. auto D = Diag(Loc, DiagID);
  2012. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2013. << SourceRange(Loc, NameInfo.getEndLoc());
  2014. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2015. // context.
  2016. if (!RecoveryTSI)
  2017. return ExprError();
  2018. // Only issue the fixit if we're prepared to recover.
  2019. D << FixItHint::CreateInsertion(Loc, "typename ");
  2020. // Recover by pretending this was an elaborated type.
  2021. QualType Ty = Context.getTypeDeclType(TD);
  2022. TypeLocBuilder TLB;
  2023. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2024. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2025. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2026. QTL.setElaboratedKeywordLoc(SourceLocation());
  2027. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2028. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2029. return ExprEmpty();
  2030. }
  2031. // Defend against this resolving to an implicit member access. We usually
  2032. // won't get here if this might be a legitimate a class member (we end up in
  2033. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2034. // a pointer-to-member or in an unevaluated context in C++11.
  2035. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2036. return BuildPossibleImplicitMemberExpr(SS,
  2037. /*TemplateKWLoc=*/SourceLocation(),
  2038. R, /*TemplateArgs=*/nullptr);
  2039. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2040. }
  2041. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2042. /// detected that we're currently inside an ObjC method. Perform some
  2043. /// additional lookup.
  2044. ///
  2045. /// Ideally, most of this would be done by lookup, but there's
  2046. /// actually quite a lot of extra work involved.
  2047. ///
  2048. /// Returns a null sentinel to indicate trivial success.
  2049. ExprResult
  2050. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2051. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2052. SourceLocation Loc = Lookup.getNameLoc();
  2053. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2054. // Check for error condition which is already reported.
  2055. if (!CurMethod)
  2056. return ExprError();
  2057. // There are two cases to handle here. 1) scoped lookup could have failed,
  2058. // in which case we should look for an ivar. 2) scoped lookup could have
  2059. // found a decl, but that decl is outside the current instance method (i.e.
  2060. // a global variable). In these two cases, we do a lookup for an ivar with
  2061. // this name, if the lookup sucedes, we replace it our current decl.
  2062. // If we're in a class method, we don't normally want to look for
  2063. // ivars. But if we don't find anything else, and there's an
  2064. // ivar, that's an error.
  2065. bool IsClassMethod = CurMethod->isClassMethod();
  2066. bool LookForIvars;
  2067. if (Lookup.empty())
  2068. LookForIvars = true;
  2069. else if (IsClassMethod)
  2070. LookForIvars = false;
  2071. else
  2072. LookForIvars = (Lookup.isSingleResult() &&
  2073. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2074. ObjCInterfaceDecl *IFace = nullptr;
  2075. if (LookForIvars) {
  2076. IFace = CurMethod->getClassInterface();
  2077. ObjCInterfaceDecl *ClassDeclared;
  2078. ObjCIvarDecl *IV = nullptr;
  2079. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2080. // Diagnose using an ivar in a class method.
  2081. if (IsClassMethod)
  2082. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2083. << IV->getDeclName());
  2084. // If we're referencing an invalid decl, just return this as a silent
  2085. // error node. The error diagnostic was already emitted on the decl.
  2086. if (IV->isInvalidDecl())
  2087. return ExprError();
  2088. // Check if referencing a field with __attribute__((deprecated)).
  2089. if (DiagnoseUseOfDecl(IV, Loc))
  2090. return ExprError();
  2091. // Diagnose the use of an ivar outside of the declaring class.
  2092. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2093. !declaresSameEntity(ClassDeclared, IFace) &&
  2094. !getLangOpts().DebuggerSupport)
  2095. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  2096. // FIXME: This should use a new expr for a direct reference, don't
  2097. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2098. IdentifierInfo &II = Context.Idents.get("self");
  2099. UnqualifiedId SelfName;
  2100. SelfName.setIdentifier(&II, SourceLocation());
  2101. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2102. CXXScopeSpec SelfScopeSpec;
  2103. SourceLocation TemplateKWLoc;
  2104. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2105. SelfName, false, false);
  2106. if (SelfExpr.isInvalid())
  2107. return ExprError();
  2108. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2109. if (SelfExpr.isInvalid())
  2110. return ExprError();
  2111. MarkAnyDeclReferenced(Loc, IV, true);
  2112. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2113. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2114. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2115. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2116. ObjCIvarRefExpr *Result = new (Context)
  2117. ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
  2118. SelfExpr.get(), true, true);
  2119. if (getLangOpts().ObjCAutoRefCount) {
  2120. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2121. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2122. recordUseOfEvaluatedWeak(Result);
  2123. }
  2124. if (CurContext->isClosure())
  2125. Diag(Loc, diag::warn_implicitly_retains_self)
  2126. << FixItHint::CreateInsertion(Loc, "self->");
  2127. }
  2128. return Result;
  2129. }
  2130. } else if (CurMethod->isInstanceMethod()) {
  2131. // We should warn if a local variable hides an ivar.
  2132. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2133. ObjCInterfaceDecl *ClassDeclared;
  2134. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2135. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2136. declaresSameEntity(IFace, ClassDeclared))
  2137. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2138. }
  2139. }
  2140. } else if (Lookup.isSingleResult() &&
  2141. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2142. // If accessing a stand-alone ivar in a class method, this is an error.
  2143. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2144. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2145. << IV->getDeclName());
  2146. }
  2147. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2148. // FIXME. Consolidate this with similar code in LookupName.
  2149. if (unsigned BuiltinID = II->getBuiltinID()) {
  2150. if (!(getLangOpts().CPlusPlus &&
  2151. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2152. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2153. S, Lookup.isForRedeclaration(),
  2154. Lookup.getNameLoc());
  2155. if (D) Lookup.addDecl(D);
  2156. }
  2157. }
  2158. }
  2159. // Sentinel value saying that we didn't do anything special.
  2160. return ExprResult((Expr *)nullptr);
  2161. }
  2162. /// \brief Cast a base object to a member's actual type.
  2163. ///
  2164. /// Logically this happens in three phases:
  2165. ///
  2166. /// * First we cast from the base type to the naming class.
  2167. /// The naming class is the class into which we were looking
  2168. /// when we found the member; it's the qualifier type if a
  2169. /// qualifier was provided, and otherwise it's the base type.
  2170. ///
  2171. /// * Next we cast from the naming class to the declaring class.
  2172. /// If the member we found was brought into a class's scope by
  2173. /// a using declaration, this is that class; otherwise it's
  2174. /// the class declaring the member.
  2175. ///
  2176. /// * Finally we cast from the declaring class to the "true"
  2177. /// declaring class of the member. This conversion does not
  2178. /// obey access control.
  2179. ExprResult
  2180. Sema::PerformObjectMemberConversion(Expr *From,
  2181. NestedNameSpecifier *Qualifier,
  2182. NamedDecl *FoundDecl,
  2183. NamedDecl *Member) {
  2184. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2185. if (!RD)
  2186. return From;
  2187. QualType DestRecordType;
  2188. QualType DestType;
  2189. QualType FromRecordType;
  2190. QualType FromType = From->getType();
  2191. bool PointerConversions = false;
  2192. if (isa<FieldDecl>(Member)) {
  2193. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2194. if (FromType->getAs<PointerType>()) {
  2195. DestType = Context.getPointerType(DestRecordType);
  2196. FromRecordType = FromType->getPointeeType();
  2197. PointerConversions = true;
  2198. } else {
  2199. DestType = DestRecordType;
  2200. FromRecordType = FromType;
  2201. }
  2202. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2203. if (Method->isStatic())
  2204. return From;
  2205. DestType = Method->getThisType(Context);
  2206. DestRecordType = DestType->getPointeeType();
  2207. if (FromType->getAs<PointerType>()) {
  2208. FromRecordType = FromType->getPointeeType();
  2209. PointerConversions = true;
  2210. } else {
  2211. FromRecordType = FromType;
  2212. DestType = DestRecordType;
  2213. }
  2214. } else {
  2215. // No conversion necessary.
  2216. return From;
  2217. }
  2218. if (DestType->isDependentType() || FromType->isDependentType())
  2219. return From;
  2220. // If the unqualified types are the same, no conversion is necessary.
  2221. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2222. return From;
  2223. SourceRange FromRange = From->getSourceRange();
  2224. SourceLocation FromLoc = FromRange.getBegin();
  2225. ExprValueKind VK = From->getValueKind();
  2226. // C++ [class.member.lookup]p8:
  2227. // [...] Ambiguities can often be resolved by qualifying a name with its
  2228. // class name.
  2229. //
  2230. // If the member was a qualified name and the qualified referred to a
  2231. // specific base subobject type, we'll cast to that intermediate type
  2232. // first and then to the object in which the member is declared. That allows
  2233. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2234. //
  2235. // class Base { public: int x; };
  2236. // class Derived1 : public Base { };
  2237. // class Derived2 : public Base { };
  2238. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2239. //
  2240. // void VeryDerived::f() {
  2241. // x = 17; // error: ambiguous base subobjects
  2242. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2243. // }
  2244. if (Qualifier && Qualifier->getAsType()) {
  2245. QualType QType = QualType(Qualifier->getAsType(), 0);
  2246. assert(QType->isRecordType() && "lookup done with non-record type");
  2247. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2248. // In C++98, the qualifier type doesn't actually have to be a base
  2249. // type of the object type, in which case we just ignore it.
  2250. // Otherwise build the appropriate casts.
  2251. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  2252. CXXCastPath BasePath;
  2253. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2254. FromLoc, FromRange, &BasePath))
  2255. return ExprError();
  2256. if (PointerConversions)
  2257. QType = Context.getPointerType(QType);
  2258. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2259. VK, &BasePath).get();
  2260. FromType = QType;
  2261. FromRecordType = QRecordType;
  2262. // If the qualifier type was the same as the destination type,
  2263. // we're done.
  2264. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2265. return From;
  2266. }
  2267. }
  2268. bool IgnoreAccess = false;
  2269. // If we actually found the member through a using declaration, cast
  2270. // down to the using declaration's type.
  2271. //
  2272. // Pointer equality is fine here because only one declaration of a
  2273. // class ever has member declarations.
  2274. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2275. assert(isa<UsingShadowDecl>(FoundDecl));
  2276. QualType URecordType = Context.getTypeDeclType(
  2277. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2278. // We only need to do this if the naming-class to declaring-class
  2279. // conversion is non-trivial.
  2280. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2281. assert(IsDerivedFrom(FromRecordType, URecordType));
  2282. CXXCastPath BasePath;
  2283. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2284. FromLoc, FromRange, &BasePath))
  2285. return ExprError();
  2286. QualType UType = URecordType;
  2287. if (PointerConversions)
  2288. UType = Context.getPointerType(UType);
  2289. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2290. VK, &BasePath).get();
  2291. FromType = UType;
  2292. FromRecordType = URecordType;
  2293. }
  2294. // We don't do access control for the conversion from the
  2295. // declaring class to the true declaring class.
  2296. IgnoreAccess = true;
  2297. }
  2298. CXXCastPath BasePath;
  2299. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2300. FromLoc, FromRange, &BasePath,
  2301. IgnoreAccess))
  2302. return ExprError();
  2303. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2304. VK, &BasePath);
  2305. }
  2306. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2307. const LookupResult &R,
  2308. bool HasTrailingLParen) {
  2309. // Only when used directly as the postfix-expression of a call.
  2310. if (!HasTrailingLParen)
  2311. return false;
  2312. // Never if a scope specifier was provided.
  2313. if (SS.isSet())
  2314. return false;
  2315. // Only in C++ or ObjC++.
  2316. if (!getLangOpts().CPlusPlus)
  2317. return false;
  2318. // Turn off ADL when we find certain kinds of declarations during
  2319. // normal lookup:
  2320. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2321. NamedDecl *D = *I;
  2322. // C++0x [basic.lookup.argdep]p3:
  2323. // -- a declaration of a class member
  2324. // Since using decls preserve this property, we check this on the
  2325. // original decl.
  2326. if (D->isCXXClassMember())
  2327. return false;
  2328. // C++0x [basic.lookup.argdep]p3:
  2329. // -- a block-scope function declaration that is not a
  2330. // using-declaration
  2331. // NOTE: we also trigger this for function templates (in fact, we
  2332. // don't check the decl type at all, since all other decl types
  2333. // turn off ADL anyway).
  2334. if (isa<UsingShadowDecl>(D))
  2335. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2336. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2337. return false;
  2338. // C++0x [basic.lookup.argdep]p3:
  2339. // -- a declaration that is neither a function or a function
  2340. // template
  2341. // And also for builtin functions.
  2342. if (isa<FunctionDecl>(D)) {
  2343. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2344. // But also builtin functions.
  2345. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2346. return false;
  2347. } else if (!isa<FunctionTemplateDecl>(D))
  2348. return false;
  2349. }
  2350. return true;
  2351. }
  2352. /// Diagnoses obvious problems with the use of the given declaration
  2353. /// as an expression. This is only actually called for lookups that
  2354. /// were not overloaded, and it doesn't promise that the declaration
  2355. /// will in fact be used.
  2356. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2357. if (isa<TypedefNameDecl>(D)) {
  2358. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2359. return true;
  2360. }
  2361. if (isa<ObjCInterfaceDecl>(D)) {
  2362. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2363. return true;
  2364. }
  2365. if (isa<NamespaceDecl>(D)) {
  2366. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2367. return true;
  2368. }
  2369. return false;
  2370. }
  2371. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2372. LookupResult &R, bool NeedsADL,
  2373. bool AcceptInvalidDecl) {
  2374. // If this is a single, fully-resolved result and we don't need ADL,
  2375. // just build an ordinary singleton decl ref.
  2376. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2377. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2378. R.getRepresentativeDecl(), nullptr,
  2379. AcceptInvalidDecl);
  2380. // We only need to check the declaration if there's exactly one
  2381. // result, because in the overloaded case the results can only be
  2382. // functions and function templates.
  2383. if (R.isSingleResult() &&
  2384. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2385. return ExprError();
  2386. // Otherwise, just build an unresolved lookup expression. Suppress
  2387. // any lookup-related diagnostics; we'll hash these out later, when
  2388. // we've picked a target.
  2389. R.suppressDiagnostics();
  2390. UnresolvedLookupExpr *ULE
  2391. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2392. SS.getWithLocInContext(Context),
  2393. R.getLookupNameInfo(),
  2394. NeedsADL, R.isOverloadedResult(),
  2395. R.begin(), R.end());
  2396. return ULE;
  2397. }
  2398. /// \brief Complete semantic analysis for a reference to the given declaration.
  2399. ExprResult Sema::BuildDeclarationNameExpr(
  2400. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2401. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2402. bool AcceptInvalidDecl) {
  2403. assert(D && "Cannot refer to a NULL declaration");
  2404. assert(!isa<FunctionTemplateDecl>(D) &&
  2405. "Cannot refer unambiguously to a function template");
  2406. SourceLocation Loc = NameInfo.getLoc();
  2407. if (CheckDeclInExpr(*this, Loc, D))
  2408. return ExprError();
  2409. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2410. // Specifically diagnose references to class templates that are missing
  2411. // a template argument list.
  2412. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2413. << Template << SS.getRange();
  2414. Diag(Template->getLocation(), diag::note_template_decl_here);
  2415. return ExprError();
  2416. }
  2417. // Make sure that we're referring to a value.
  2418. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2419. if (!VD) {
  2420. Diag(Loc, diag::err_ref_non_value)
  2421. << D << SS.getRange();
  2422. Diag(D->getLocation(), diag::note_declared_at);
  2423. return ExprError();
  2424. }
  2425. // Check whether this declaration can be used. Note that we suppress
  2426. // this check when we're going to perform argument-dependent lookup
  2427. // on this function name, because this might not be the function
  2428. // that overload resolution actually selects.
  2429. if (DiagnoseUseOfDecl(VD, Loc))
  2430. return ExprError();
  2431. // Only create DeclRefExpr's for valid Decl's.
  2432. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2433. return ExprError();
  2434. // Handle members of anonymous structs and unions. If we got here,
  2435. // and the reference is to a class member indirect field, then this
  2436. // must be the subject of a pointer-to-member expression.
  2437. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2438. if (!indirectField->isCXXClassMember())
  2439. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2440. indirectField);
  2441. {
  2442. QualType type = VD->getType();
  2443. ExprValueKind valueKind = VK_RValue;
  2444. switch (D->getKind()) {
  2445. // Ignore all the non-ValueDecl kinds.
  2446. #define ABSTRACT_DECL(kind)
  2447. #define VALUE(type, base)
  2448. #define DECL(type, base) \
  2449. case Decl::type:
  2450. #include "clang/AST/DeclNodes.inc"
  2451. llvm_unreachable("invalid value decl kind");
  2452. // These shouldn't make it here.
  2453. case Decl::ObjCAtDefsField:
  2454. case Decl::ObjCIvar:
  2455. llvm_unreachable("forming non-member reference to ivar?");
  2456. // Enum constants are always r-values and never references.
  2457. // Unresolved using declarations are dependent.
  2458. case Decl::EnumConstant:
  2459. case Decl::UnresolvedUsingValue:
  2460. valueKind = VK_RValue;
  2461. break;
  2462. // Fields and indirect fields that got here must be for
  2463. // pointer-to-member expressions; we just call them l-values for
  2464. // internal consistency, because this subexpression doesn't really
  2465. // exist in the high-level semantics.
  2466. case Decl::Field:
  2467. case Decl::IndirectField:
  2468. assert(getLangOpts().CPlusPlus &&
  2469. "building reference to field in C?");
  2470. // These can't have reference type in well-formed programs, but
  2471. // for internal consistency we do this anyway.
  2472. type = type.getNonReferenceType();
  2473. valueKind = VK_LValue;
  2474. break;
  2475. // Non-type template parameters are either l-values or r-values
  2476. // depending on the type.
  2477. case Decl::NonTypeTemplateParm: {
  2478. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2479. type = reftype->getPointeeType();
  2480. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2481. break;
  2482. }
  2483. // For non-references, we need to strip qualifiers just in case
  2484. // the template parameter was declared as 'const int' or whatever.
  2485. valueKind = VK_RValue;
  2486. type = type.getUnqualifiedType();
  2487. break;
  2488. }
  2489. case Decl::Var:
  2490. case Decl::VarTemplateSpecialization:
  2491. case Decl::VarTemplatePartialSpecialization:
  2492. // In C, "extern void blah;" is valid and is an r-value.
  2493. if (!getLangOpts().CPlusPlus &&
  2494. !type.hasQualifiers() &&
  2495. type->isVoidType()) {
  2496. valueKind = VK_RValue;
  2497. break;
  2498. }
  2499. // fallthrough
  2500. case Decl::ImplicitParam:
  2501. case Decl::ParmVar: {
  2502. // These are always l-values.
  2503. valueKind = VK_LValue;
  2504. type = type.getNonReferenceType();
  2505. // FIXME: Does the addition of const really only apply in
  2506. // potentially-evaluated contexts? Since the variable isn't actually
  2507. // captured in an unevaluated context, it seems that the answer is no.
  2508. if (!isUnevaluatedContext()) {
  2509. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2510. if (!CapturedType.isNull())
  2511. type = CapturedType;
  2512. }
  2513. break;
  2514. }
  2515. case Decl::Function: {
  2516. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2517. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2518. type = Context.BuiltinFnTy;
  2519. valueKind = VK_RValue;
  2520. break;
  2521. }
  2522. }
  2523. const FunctionType *fty = type->castAs<FunctionType>();
  2524. // If we're referring to a function with an __unknown_anytype
  2525. // result type, make the entire expression __unknown_anytype.
  2526. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2527. type = Context.UnknownAnyTy;
  2528. valueKind = VK_RValue;
  2529. break;
  2530. }
  2531. // Functions are l-values in C++.
  2532. if (getLangOpts().CPlusPlus) {
  2533. valueKind = VK_LValue;
  2534. break;
  2535. }
  2536. // C99 DR 316 says that, if a function type comes from a
  2537. // function definition (without a prototype), that type is only
  2538. // used for checking compatibility. Therefore, when referencing
  2539. // the function, we pretend that we don't have the full function
  2540. // type.
  2541. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2542. isa<FunctionProtoType>(fty))
  2543. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2544. fty->getExtInfo());
  2545. // Functions are r-values in C.
  2546. valueKind = VK_RValue;
  2547. break;
  2548. }
  2549. case Decl::MSProperty:
  2550. valueKind = VK_LValue;
  2551. break;
  2552. case Decl::CXXMethod:
  2553. // If we're referring to a method with an __unknown_anytype
  2554. // result type, make the entire expression __unknown_anytype.
  2555. // This should only be possible with a type written directly.
  2556. if (const FunctionProtoType *proto
  2557. = dyn_cast<FunctionProtoType>(VD->getType()))
  2558. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2559. type = Context.UnknownAnyTy;
  2560. valueKind = VK_RValue;
  2561. break;
  2562. }
  2563. // C++ methods are l-values if static, r-values if non-static.
  2564. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2565. valueKind = VK_LValue;
  2566. break;
  2567. }
  2568. // fallthrough
  2569. case Decl::CXXConversion:
  2570. case Decl::CXXDestructor:
  2571. case Decl::CXXConstructor:
  2572. valueKind = VK_RValue;
  2573. break;
  2574. }
  2575. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2576. TemplateArgs);
  2577. }
  2578. }
  2579. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2580. SmallString<32> &Target) {
  2581. Target.resize(CharByteWidth * (Source.size() + 1));
  2582. char *ResultPtr = &Target[0];
  2583. const UTF8 *ErrorPtr;
  2584. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2585. (void)success;
  2586. assert(success);
  2587. Target.resize(ResultPtr - &Target[0]);
  2588. }
  2589. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2590. PredefinedExpr::IdentType IT) {
  2591. // Pick the current block, lambda, captured statement or function.
  2592. Decl *currentDecl = nullptr;
  2593. if (const BlockScopeInfo *BSI = getCurBlock())
  2594. currentDecl = BSI->TheDecl;
  2595. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2596. currentDecl = LSI->CallOperator;
  2597. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2598. currentDecl = CSI->TheCapturedDecl;
  2599. else
  2600. currentDecl = getCurFunctionOrMethodDecl();
  2601. if (!currentDecl) {
  2602. Diag(Loc, diag::ext_predef_outside_function);
  2603. currentDecl = Context.getTranslationUnitDecl();
  2604. }
  2605. QualType ResTy;
  2606. StringLiteral *SL = nullptr;
  2607. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2608. ResTy = Context.DependentTy;
  2609. else {
  2610. // Pre-defined identifiers are of type char[x], where x is the length of
  2611. // the string.
  2612. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2613. unsigned Length = Str.length();
  2614. llvm::APInt LengthI(32, Length + 1);
  2615. if (IT == PredefinedExpr::LFunction) {
  2616. ResTy = Context.WideCharTy.withConst();
  2617. SmallString<32> RawChars;
  2618. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2619. Str, RawChars);
  2620. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2621. /*IndexTypeQuals*/ 0);
  2622. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2623. /*Pascal*/ false, ResTy, Loc);
  2624. } else {
  2625. ResTy = Context.CharTy.withConst();
  2626. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2627. /*IndexTypeQuals*/ 0);
  2628. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2629. /*Pascal*/ false, ResTy, Loc);
  2630. }
  2631. }
  2632. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2633. }
  2634. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2635. PredefinedExpr::IdentType IT;
  2636. switch (Kind) {
  2637. default: llvm_unreachable("Unknown simple primary expr!");
  2638. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2639. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2640. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2641. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2642. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2643. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2644. }
  2645. return BuildPredefinedExpr(Loc, IT);
  2646. }
  2647. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2648. SmallString<16> CharBuffer;
  2649. bool Invalid = false;
  2650. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2651. if (Invalid)
  2652. return ExprError();
  2653. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2654. PP, Tok.getKind());
  2655. if (Literal.hadError())
  2656. return ExprError();
  2657. QualType Ty;
  2658. if (Literal.isWide())
  2659. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2660. else if (Literal.isUTF16())
  2661. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2662. else if (Literal.isUTF32())
  2663. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2664. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2665. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2666. else
  2667. Ty = Context.CharTy; // 'x' -> char in C++
  2668. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2669. if (Literal.isWide())
  2670. Kind = CharacterLiteral::Wide;
  2671. else if (Literal.isUTF16())
  2672. Kind = CharacterLiteral::UTF16;
  2673. else if (Literal.isUTF32())
  2674. Kind = CharacterLiteral::UTF32;
  2675. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2676. Tok.getLocation());
  2677. if (Literal.getUDSuffix().empty())
  2678. return Lit;
  2679. // We're building a user-defined literal.
  2680. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2681. SourceLocation UDSuffixLoc =
  2682. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2683. // Make sure we're allowed user-defined literals here.
  2684. if (!UDLScope)
  2685. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2686. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2687. // operator "" X (ch)
  2688. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2689. Lit, Tok.getLocation());
  2690. }
  2691. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2692. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2693. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2694. Context.IntTy, Loc);
  2695. }
  2696. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2697. QualType Ty, SourceLocation Loc) {
  2698. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2699. using llvm::APFloat;
  2700. APFloat Val(Format);
  2701. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2702. // Overflow is always an error, but underflow is only an error if
  2703. // we underflowed to zero (APFloat reports denormals as underflow).
  2704. if ((result & APFloat::opOverflow) ||
  2705. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2706. unsigned diagnostic;
  2707. SmallString<20> buffer;
  2708. if (result & APFloat::opOverflow) {
  2709. diagnostic = diag::warn_float_overflow;
  2710. APFloat::getLargest(Format).toString(buffer);
  2711. } else {
  2712. diagnostic = diag::warn_float_underflow;
  2713. APFloat::getSmallest(Format).toString(buffer);
  2714. }
  2715. S.Diag(Loc, diagnostic)
  2716. << Ty
  2717. << StringRef(buffer.data(), buffer.size());
  2718. }
  2719. bool isExact = (result == APFloat::opOK);
  2720. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2721. }
  2722. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2723. assert(E && "Invalid expression");
  2724. if (E->isValueDependent())
  2725. return false;
  2726. QualType QT = E->getType();
  2727. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2728. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2729. return true;
  2730. }
  2731. llvm::APSInt ValueAPS;
  2732. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2733. if (R.isInvalid())
  2734. return true;
  2735. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2736. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2737. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2738. << ValueAPS.toString(10) << ValueIsPositive;
  2739. return true;
  2740. }
  2741. return false;
  2742. }
  2743. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2744. // Fast path for a single digit (which is quite common). A single digit
  2745. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2746. if (Tok.getLength() == 1) {
  2747. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2748. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2749. }
  2750. SmallString<128> SpellingBuffer;
  2751. // NumericLiteralParser wants to overread by one character. Add padding to
  2752. // the buffer in case the token is copied to the buffer. If getSpelling()
  2753. // returns a StringRef to the memory buffer, it should have a null char at
  2754. // the EOF, so it is also safe.
  2755. SpellingBuffer.resize(Tok.getLength() + 1);
  2756. // Get the spelling of the token, which eliminates trigraphs, etc.
  2757. bool Invalid = false;
  2758. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2759. if (Invalid)
  2760. return ExprError();
  2761. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2762. if (Literal.hadError)
  2763. return ExprError();
  2764. if (Literal.hasUDSuffix()) {
  2765. // We're building a user-defined literal.
  2766. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2767. SourceLocation UDSuffixLoc =
  2768. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2769. // Make sure we're allowed user-defined literals here.
  2770. if (!UDLScope)
  2771. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2772. QualType CookedTy;
  2773. if (Literal.isFloatingLiteral()) {
  2774. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2775. // long double, the literal is treated as a call of the form
  2776. // operator "" X (f L)
  2777. CookedTy = Context.LongDoubleTy;
  2778. } else {
  2779. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2780. // unsigned long long, the literal is treated as a call of the form
  2781. // operator "" X (n ULL)
  2782. CookedTy = Context.UnsignedLongLongTy;
  2783. }
  2784. DeclarationName OpName =
  2785. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2786. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2787. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2788. SourceLocation TokLoc = Tok.getLocation();
  2789. // Perform literal operator lookup to determine if we're building a raw
  2790. // literal or a cooked one.
  2791. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2792. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2793. /*AllowRaw*/true, /*AllowTemplate*/true,
  2794. /*AllowStringTemplate*/false)) {
  2795. case LOLR_Error:
  2796. return ExprError();
  2797. case LOLR_Cooked: {
  2798. Expr *Lit;
  2799. if (Literal.isFloatingLiteral()) {
  2800. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2801. } else {
  2802. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2803. if (Literal.GetIntegerValue(ResultVal))
  2804. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2805. << /* Unsigned */ 1;
  2806. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2807. Tok.getLocation());
  2808. }
  2809. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2810. }
  2811. case LOLR_Raw: {
  2812. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2813. // literal is treated as a call of the form
  2814. // operator "" X ("n")
  2815. unsigned Length = Literal.getUDSuffixOffset();
  2816. QualType StrTy = Context.getConstantArrayType(
  2817. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2818. ArrayType::Normal, 0);
  2819. Expr *Lit = StringLiteral::Create(
  2820. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2821. /*Pascal*/false, StrTy, &TokLoc, 1);
  2822. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2823. }
  2824. case LOLR_Template: {
  2825. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2826. // template), L is treated as a call fo the form
  2827. // operator "" X <'c1', 'c2', ... 'ck'>()
  2828. // where n is the source character sequence c1 c2 ... ck.
  2829. TemplateArgumentListInfo ExplicitArgs;
  2830. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2831. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2832. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2833. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2834. Value = TokSpelling[I];
  2835. TemplateArgument Arg(Context, Value, Context.CharTy);
  2836. TemplateArgumentLocInfo ArgInfo;
  2837. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2838. }
  2839. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2840. &ExplicitArgs);
  2841. }
  2842. case LOLR_StringTemplate:
  2843. llvm_unreachable("unexpected literal operator lookup result");
  2844. }
  2845. }
  2846. Expr *Res;
  2847. if (Literal.isFloatingLiteral()) {
  2848. QualType Ty;
  2849. if (Literal.isFloat)
  2850. Ty = Context.FloatTy;
  2851. else if (!Literal.isLong)
  2852. Ty = Context.DoubleTy;
  2853. else
  2854. Ty = Context.LongDoubleTy;
  2855. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2856. if (Ty == Context.DoubleTy) {
  2857. if (getLangOpts().SinglePrecisionConstants) {
  2858. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2859. } else if (getLangOpts().OpenCL &&
  2860. !((getLangOpts().OpenCLVersion >= 120) ||
  2861. getOpenCLOptions().cl_khr_fp64)) {
  2862. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2863. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2864. }
  2865. }
  2866. } else if (!Literal.isIntegerLiteral()) {
  2867. return ExprError();
  2868. } else {
  2869. QualType Ty;
  2870. // 'long long' is a C99 or C++11 feature.
  2871. if (!getLangOpts().C99 && Literal.isLongLong) {
  2872. if (getLangOpts().CPlusPlus)
  2873. Diag(Tok.getLocation(),
  2874. getLangOpts().CPlusPlus11 ?
  2875. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  2876. else
  2877. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  2878. }
  2879. // Get the value in the widest-possible width.
  2880. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  2881. // The microsoft literal suffix extensions support 128-bit literals, which
  2882. // may be wider than [u]intmax_t.
  2883. // FIXME: Actually, they don't. We seem to have accidentally invented the
  2884. // i128 suffix.
  2885. if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
  2886. Context.getTargetInfo().hasInt128Type())
  2887. MaxWidth = 128;
  2888. llvm::APInt ResultVal(MaxWidth, 0);
  2889. if (Literal.GetIntegerValue(ResultVal)) {
  2890. // If this value didn't fit into uintmax_t, error and force to ull.
  2891. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2892. << /* Unsigned */ 1;
  2893. Ty = Context.UnsignedLongLongTy;
  2894. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  2895. "long long is not intmax_t?");
  2896. } else {
  2897. // If this value fits into a ULL, try to figure out what else it fits into
  2898. // according to the rules of C99 6.4.4.1p5.
  2899. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  2900. // be an unsigned int.
  2901. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  2902. // Check from smallest to largest, picking the smallest type we can.
  2903. unsigned Width = 0;
  2904. // Microsoft specific integer suffixes are explicitly sized.
  2905. if (Literal.MicrosoftInteger) {
  2906. if (Literal.MicrosoftInteger > MaxWidth) {
  2907. // If this target doesn't support __int128, error and force to ull.
  2908. Diag(Tok.getLocation(), diag::err_int128_unsupported);
  2909. Width = MaxWidth;
  2910. Ty = Context.getIntMaxType();
  2911. } else {
  2912. Width = Literal.MicrosoftInteger;
  2913. Ty = Context.getIntTypeForBitwidth(Width,
  2914. /*Signed=*/!Literal.isUnsigned);
  2915. }
  2916. }
  2917. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  2918. // Are int/unsigned possibilities?
  2919. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2920. // Does it fit in a unsigned int?
  2921. if (ResultVal.isIntN(IntSize)) {
  2922. // Does it fit in a signed int?
  2923. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  2924. Ty = Context.IntTy;
  2925. else if (AllowUnsigned)
  2926. Ty = Context.UnsignedIntTy;
  2927. Width = IntSize;
  2928. }
  2929. }
  2930. // Are long/unsigned long possibilities?
  2931. if (Ty.isNull() && !Literal.isLongLong) {
  2932. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  2933. // Does it fit in a unsigned long?
  2934. if (ResultVal.isIntN(LongSize)) {
  2935. // Does it fit in a signed long?
  2936. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  2937. Ty = Context.LongTy;
  2938. else if (AllowUnsigned)
  2939. Ty = Context.UnsignedLongTy;
  2940. Width = LongSize;
  2941. }
  2942. }
  2943. // Check long long if needed.
  2944. if (Ty.isNull()) {
  2945. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  2946. // Does it fit in a unsigned long long?
  2947. if (ResultVal.isIntN(LongLongSize)) {
  2948. // Does it fit in a signed long long?
  2949. // To be compatible with MSVC, hex integer literals ending with the
  2950. // LL or i64 suffix are always signed in Microsoft mode.
  2951. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  2952. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  2953. Ty = Context.LongLongTy;
  2954. else if (AllowUnsigned)
  2955. Ty = Context.UnsignedLongLongTy;
  2956. Width = LongLongSize;
  2957. }
  2958. }
  2959. // If we still couldn't decide a type, we probably have something that
  2960. // does not fit in a signed long long, but has no U suffix.
  2961. if (Ty.isNull()) {
  2962. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  2963. Ty = Context.UnsignedLongLongTy;
  2964. Width = Context.getTargetInfo().getLongLongWidth();
  2965. }
  2966. if (ResultVal.getBitWidth() != Width)
  2967. ResultVal = ResultVal.trunc(Width);
  2968. }
  2969. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  2970. }
  2971. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  2972. if (Literal.isImaginary)
  2973. Res = new (Context) ImaginaryLiteral(Res,
  2974. Context.getComplexType(Res->getType()));
  2975. return Res;
  2976. }
  2977. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  2978. assert(E && "ActOnParenExpr() missing expr");
  2979. return new (Context) ParenExpr(L, R, E);
  2980. }
  2981. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  2982. SourceLocation Loc,
  2983. SourceRange ArgRange) {
  2984. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  2985. // scalar or vector data type argument..."
  2986. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  2987. // type (C99 6.2.5p18) or void.
  2988. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  2989. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  2990. << T << ArgRange;
  2991. return true;
  2992. }
  2993. assert((T->isVoidType() || !T->isIncompleteType()) &&
  2994. "Scalar types should always be complete");
  2995. return false;
  2996. }
  2997. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  2998. SourceLocation Loc,
  2999. SourceRange ArgRange,
  3000. UnaryExprOrTypeTrait TraitKind) {
  3001. // Invalid types must be hard errors for SFINAE in C++.
  3002. if (S.LangOpts.CPlusPlus)
  3003. return true;
  3004. // C99 6.5.3.4p1:
  3005. if (T->isFunctionType() &&
  3006. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3007. // sizeof(function)/alignof(function) is allowed as an extension.
  3008. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3009. << TraitKind << ArgRange;
  3010. return false;
  3011. }
  3012. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3013. // this is an error (OpenCL v1.1 s6.3.k)
  3014. if (T->isVoidType()) {
  3015. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3016. : diag::ext_sizeof_alignof_void_type;
  3017. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3018. return false;
  3019. }
  3020. return true;
  3021. }
  3022. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3023. SourceLocation Loc,
  3024. SourceRange ArgRange,
  3025. UnaryExprOrTypeTrait TraitKind) {
  3026. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3027. // runtime doesn't allow it.
  3028. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3029. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3030. << T << (TraitKind == UETT_SizeOf)
  3031. << ArgRange;
  3032. return true;
  3033. }
  3034. return false;
  3035. }
  3036. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3037. /// pointer type is equal to T) and emit a warning if it is.
  3038. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3039. Expr *E) {
  3040. // Don't warn if the operation changed the type.
  3041. if (T != E->getType())
  3042. return;
  3043. // Now look for array decays.
  3044. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3045. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3046. return;
  3047. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3048. << ICE->getType()
  3049. << ICE->getSubExpr()->getType();
  3050. }
  3051. /// \brief Check the constraints on expression operands to unary type expression
  3052. /// and type traits.
  3053. ///
  3054. /// Completes any types necessary and validates the constraints on the operand
  3055. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3056. /// the expression as it completes the type for that expression through template
  3057. /// instantiation, etc.
  3058. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3059. UnaryExprOrTypeTrait ExprKind) {
  3060. QualType ExprTy = E->getType();
  3061. assert(!ExprTy->isReferenceType());
  3062. if (ExprKind == UETT_VecStep)
  3063. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3064. E->getSourceRange());
  3065. // Whitelist some types as extensions
  3066. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3067. E->getSourceRange(), ExprKind))
  3068. return false;
  3069. // 'alignof' applied to an expression only requires the base element type of
  3070. // the expression to be complete. 'sizeof' requires the expression's type to
  3071. // be complete (and will attempt to complete it if it's an array of unknown
  3072. // bound).
  3073. if (ExprKind == UETT_AlignOf) {
  3074. if (RequireCompleteType(E->getExprLoc(),
  3075. Context.getBaseElementType(E->getType()),
  3076. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3077. E->getSourceRange()))
  3078. return true;
  3079. } else {
  3080. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3081. ExprKind, E->getSourceRange()))
  3082. return true;
  3083. }
  3084. // Completing the expression's type may have changed it.
  3085. ExprTy = E->getType();
  3086. assert(!ExprTy->isReferenceType());
  3087. if (ExprTy->isFunctionType()) {
  3088. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3089. << ExprKind << E->getSourceRange();
  3090. return true;
  3091. }
  3092. // The operand for sizeof and alignof is in an unevaluated expression context,
  3093. // so side effects could result in unintended consequences.
  3094. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3095. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3096. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3097. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3098. E->getSourceRange(), ExprKind))
  3099. return true;
  3100. if (ExprKind == UETT_SizeOf) {
  3101. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3102. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3103. QualType OType = PVD->getOriginalType();
  3104. QualType Type = PVD->getType();
  3105. if (Type->isPointerType() && OType->isArrayType()) {
  3106. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3107. << Type << OType;
  3108. Diag(PVD->getLocation(), diag::note_declared_at);
  3109. }
  3110. }
  3111. }
  3112. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3113. // decays into a pointer and returns an unintended result. This is most
  3114. // likely a typo for "sizeof(array) op x".
  3115. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3116. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3117. BO->getLHS());
  3118. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3119. BO->getRHS());
  3120. }
  3121. }
  3122. return false;
  3123. }
  3124. /// \brief Check the constraints on operands to unary expression and type
  3125. /// traits.
  3126. ///
  3127. /// This will complete any types necessary, and validate the various constraints
  3128. /// on those operands.
  3129. ///
  3130. /// The UsualUnaryConversions() function is *not* called by this routine.
  3131. /// C99 6.3.2.1p[2-4] all state:
  3132. /// Except when it is the operand of the sizeof operator ...
  3133. ///
  3134. /// C++ [expr.sizeof]p4
  3135. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3136. /// standard conversions are not applied to the operand of sizeof.
  3137. ///
  3138. /// This policy is followed for all of the unary trait expressions.
  3139. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3140. SourceLocation OpLoc,
  3141. SourceRange ExprRange,
  3142. UnaryExprOrTypeTrait ExprKind) {
  3143. if (ExprType->isDependentType())
  3144. return false;
  3145. // C++ [expr.sizeof]p2:
  3146. // When applied to a reference or a reference type, the result
  3147. // is the size of the referenced type.
  3148. // C++11 [expr.alignof]p3:
  3149. // When alignof is applied to a reference type, the result
  3150. // shall be the alignment of the referenced type.
  3151. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3152. ExprType = Ref->getPointeeType();
  3153. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3154. // When alignof or _Alignof is applied to an array type, the result
  3155. // is the alignment of the element type.
  3156. if (ExprKind == UETT_AlignOf)
  3157. ExprType = Context.getBaseElementType(ExprType);
  3158. if (ExprKind == UETT_VecStep)
  3159. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3160. // Whitelist some types as extensions
  3161. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3162. ExprKind))
  3163. return false;
  3164. if (RequireCompleteType(OpLoc, ExprType,
  3165. diag::err_sizeof_alignof_incomplete_type,
  3166. ExprKind, ExprRange))
  3167. return true;
  3168. if (ExprType->isFunctionType()) {
  3169. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3170. << ExprKind << ExprRange;
  3171. return true;
  3172. }
  3173. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3174. ExprKind))
  3175. return true;
  3176. return false;
  3177. }
  3178. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3179. E = E->IgnoreParens();
  3180. // Cannot know anything else if the expression is dependent.
  3181. if (E->isTypeDependent())
  3182. return false;
  3183. if (E->getObjectKind() == OK_BitField) {
  3184. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  3185. << 1 << E->getSourceRange();
  3186. return true;
  3187. }
  3188. ValueDecl *D = nullptr;
  3189. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3190. D = DRE->getDecl();
  3191. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3192. D = ME->getMemberDecl();
  3193. }
  3194. // If it's a field, require the containing struct to have a
  3195. // complete definition so that we can compute the layout.
  3196. //
  3197. // This can happen in C++11 onwards, either by naming the member
  3198. // in a way that is not transformed into a member access expression
  3199. // (in an unevaluated operand, for instance), or by naming the member
  3200. // in a trailing-return-type.
  3201. //
  3202. // For the record, since __alignof__ on expressions is a GCC
  3203. // extension, GCC seems to permit this but always gives the
  3204. // nonsensical answer 0.
  3205. //
  3206. // We don't really need the layout here --- we could instead just
  3207. // directly check for all the appropriate alignment-lowing
  3208. // attributes --- but that would require duplicating a lot of
  3209. // logic that just isn't worth duplicating for such a marginal
  3210. // use-case.
  3211. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3212. // Fast path this check, since we at least know the record has a
  3213. // definition if we can find a member of it.
  3214. if (!FD->getParent()->isCompleteDefinition()) {
  3215. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3216. << E->getSourceRange();
  3217. return true;
  3218. }
  3219. // Otherwise, if it's a field, and the field doesn't have
  3220. // reference type, then it must have a complete type (or be a
  3221. // flexible array member, which we explicitly want to
  3222. // white-list anyway), which makes the following checks trivial.
  3223. if (!FD->getType()->isReferenceType())
  3224. return false;
  3225. }
  3226. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3227. }
  3228. bool Sema::CheckVecStepExpr(Expr *E) {
  3229. E = E->IgnoreParens();
  3230. // Cannot know anything else if the expression is dependent.
  3231. if (E->isTypeDependent())
  3232. return false;
  3233. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3234. }
  3235. /// \brief Build a sizeof or alignof expression given a type operand.
  3236. ExprResult
  3237. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3238. SourceLocation OpLoc,
  3239. UnaryExprOrTypeTrait ExprKind,
  3240. SourceRange R) {
  3241. if (!TInfo)
  3242. return ExprError();
  3243. QualType T = TInfo->getType();
  3244. if (!T->isDependentType() &&
  3245. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3246. return ExprError();
  3247. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3248. return new (Context) UnaryExprOrTypeTraitExpr(
  3249. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3250. }
  3251. /// \brief Build a sizeof or alignof expression given an expression
  3252. /// operand.
  3253. ExprResult
  3254. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3255. UnaryExprOrTypeTrait ExprKind) {
  3256. ExprResult PE = CheckPlaceholderExpr(E);
  3257. if (PE.isInvalid())
  3258. return ExprError();
  3259. E = PE.get();
  3260. // Verify that the operand is valid.
  3261. bool isInvalid = false;
  3262. if (E->isTypeDependent()) {
  3263. // Delay type-checking for type-dependent expressions.
  3264. } else if (ExprKind == UETT_AlignOf) {
  3265. isInvalid = CheckAlignOfExpr(*this, E);
  3266. } else if (ExprKind == UETT_VecStep) {
  3267. isInvalid = CheckVecStepExpr(E);
  3268. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3269. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  3270. isInvalid = true;
  3271. } else {
  3272. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3273. }
  3274. if (isInvalid)
  3275. return ExprError();
  3276. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3277. PE = TransformToPotentiallyEvaluated(E);
  3278. if (PE.isInvalid()) return ExprError();
  3279. E = PE.get();
  3280. }
  3281. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3282. return new (Context) UnaryExprOrTypeTraitExpr(
  3283. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3284. }
  3285. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3286. /// expr and the same for @c alignof and @c __alignof
  3287. /// Note that the ArgRange is invalid if isType is false.
  3288. ExprResult
  3289. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3290. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3291. void *TyOrEx, const SourceRange &ArgRange) {
  3292. // If error parsing type, ignore.
  3293. if (!TyOrEx) return ExprError();
  3294. if (IsType) {
  3295. TypeSourceInfo *TInfo;
  3296. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3297. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3298. }
  3299. Expr *ArgEx = (Expr *)TyOrEx;
  3300. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3301. return Result;
  3302. }
  3303. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3304. bool IsReal) {
  3305. if (V.get()->isTypeDependent())
  3306. return S.Context.DependentTy;
  3307. // _Real and _Imag are only l-values for normal l-values.
  3308. if (V.get()->getObjectKind() != OK_Ordinary) {
  3309. V = S.DefaultLvalueConversion(V.get());
  3310. if (V.isInvalid())
  3311. return QualType();
  3312. }
  3313. // These operators return the element type of a complex type.
  3314. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3315. return CT->getElementType();
  3316. // Otherwise they pass through real integer and floating point types here.
  3317. if (V.get()->getType()->isArithmeticType())
  3318. return V.get()->getType();
  3319. // Test for placeholders.
  3320. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3321. if (PR.isInvalid()) return QualType();
  3322. if (PR.get() != V.get()) {
  3323. V = PR;
  3324. return CheckRealImagOperand(S, V, Loc, IsReal);
  3325. }
  3326. // Reject anything else.
  3327. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3328. << (IsReal ? "__real" : "__imag");
  3329. return QualType();
  3330. }
  3331. ExprResult
  3332. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3333. tok::TokenKind Kind, Expr *Input) {
  3334. UnaryOperatorKind Opc;
  3335. switch (Kind) {
  3336. default: llvm_unreachable("Unknown unary op!");
  3337. case tok::plusplus: Opc = UO_PostInc; break;
  3338. case tok::minusminus: Opc = UO_PostDec; break;
  3339. }
  3340. // Since this might is a postfix expression, get rid of ParenListExprs.
  3341. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3342. if (Result.isInvalid()) return ExprError();
  3343. Input = Result.get();
  3344. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3345. }
  3346. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3347. ///
  3348. /// \return true on error
  3349. static bool checkArithmeticOnObjCPointer(Sema &S,
  3350. SourceLocation opLoc,
  3351. Expr *op) {
  3352. assert(op->getType()->isObjCObjectPointerType());
  3353. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3354. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3355. return false;
  3356. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3357. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3358. << op->getSourceRange();
  3359. return true;
  3360. }
  3361. ExprResult
  3362. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3363. Expr *idx, SourceLocation rbLoc) {
  3364. // Since this might be a postfix expression, get rid of ParenListExprs.
  3365. if (isa<ParenListExpr>(base)) {
  3366. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3367. if (result.isInvalid()) return ExprError();
  3368. base = result.get();
  3369. }
  3370. // Handle any non-overload placeholder types in the base and index
  3371. // expressions. We can't handle overloads here because the other
  3372. // operand might be an overloadable type, in which case the overload
  3373. // resolution for the operator overload should get the first crack
  3374. // at the overload.
  3375. if (base->getType()->isNonOverloadPlaceholderType()) {
  3376. ExprResult result = CheckPlaceholderExpr(base);
  3377. if (result.isInvalid()) return ExprError();
  3378. base = result.get();
  3379. }
  3380. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3381. ExprResult result = CheckPlaceholderExpr(idx);
  3382. if (result.isInvalid()) return ExprError();
  3383. idx = result.get();
  3384. }
  3385. // Build an unanalyzed expression if either operand is type-dependent.
  3386. if (getLangOpts().CPlusPlus &&
  3387. (base->isTypeDependent() || idx->isTypeDependent())) {
  3388. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3389. VK_LValue, OK_Ordinary, rbLoc);
  3390. }
  3391. // Use C++ overloaded-operator rules if either operand has record
  3392. // type. The spec says to do this if either type is *overloadable*,
  3393. // but enum types can't declare subscript operators or conversion
  3394. // operators, so there's nothing interesting for overload resolution
  3395. // to do if there aren't any record types involved.
  3396. //
  3397. // ObjC pointers have their own subscripting logic that is not tied
  3398. // to overload resolution and so should not take this path.
  3399. if (getLangOpts().CPlusPlus &&
  3400. (base->getType()->isRecordType() ||
  3401. (!base->getType()->isObjCObjectPointerType() &&
  3402. idx->getType()->isRecordType()))) {
  3403. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3404. }
  3405. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3406. }
  3407. ExprResult
  3408. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3409. Expr *Idx, SourceLocation RLoc) {
  3410. Expr *LHSExp = Base;
  3411. Expr *RHSExp = Idx;
  3412. // Perform default conversions.
  3413. if (!LHSExp->getType()->getAs<VectorType>()) {
  3414. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3415. if (Result.isInvalid())
  3416. return ExprError();
  3417. LHSExp = Result.get();
  3418. }
  3419. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3420. if (Result.isInvalid())
  3421. return ExprError();
  3422. RHSExp = Result.get();
  3423. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3424. ExprValueKind VK = VK_LValue;
  3425. ExprObjectKind OK = OK_Ordinary;
  3426. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3427. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3428. // in the subscript position. As a result, we need to derive the array base
  3429. // and index from the expression types.
  3430. Expr *BaseExpr, *IndexExpr;
  3431. QualType ResultType;
  3432. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3433. BaseExpr = LHSExp;
  3434. IndexExpr = RHSExp;
  3435. ResultType = Context.DependentTy;
  3436. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3437. BaseExpr = LHSExp;
  3438. IndexExpr = RHSExp;
  3439. ResultType = PTy->getPointeeType();
  3440. } else if (const ObjCObjectPointerType *PTy =
  3441. LHSTy->getAs<ObjCObjectPointerType>()) {
  3442. BaseExpr = LHSExp;
  3443. IndexExpr = RHSExp;
  3444. // Use custom logic if this should be the pseudo-object subscript
  3445. // expression.
  3446. if (!LangOpts.isSubscriptPointerArithmetic())
  3447. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3448. nullptr);
  3449. ResultType = PTy->getPointeeType();
  3450. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3451. // Handle the uncommon case of "123[Ptr]".
  3452. BaseExpr = RHSExp;
  3453. IndexExpr = LHSExp;
  3454. ResultType = PTy->getPointeeType();
  3455. } else if (const ObjCObjectPointerType *PTy =
  3456. RHSTy->getAs<ObjCObjectPointerType>()) {
  3457. // Handle the uncommon case of "123[Ptr]".
  3458. BaseExpr = RHSExp;
  3459. IndexExpr = LHSExp;
  3460. ResultType = PTy->getPointeeType();
  3461. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3462. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3463. << ResultType << BaseExpr->getSourceRange();
  3464. return ExprError();
  3465. }
  3466. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3467. BaseExpr = LHSExp; // vectors: V[123]
  3468. IndexExpr = RHSExp;
  3469. VK = LHSExp->getValueKind();
  3470. if (VK != VK_RValue)
  3471. OK = OK_VectorComponent;
  3472. // FIXME: need to deal with const...
  3473. ResultType = VTy->getElementType();
  3474. } else if (LHSTy->isArrayType()) {
  3475. // If we see an array that wasn't promoted by
  3476. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3477. // wasn't promoted because of the C90 rule that doesn't
  3478. // allow promoting non-lvalue arrays. Warn, then
  3479. // force the promotion here.
  3480. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3481. LHSExp->getSourceRange();
  3482. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3483. CK_ArrayToPointerDecay).get();
  3484. LHSTy = LHSExp->getType();
  3485. BaseExpr = LHSExp;
  3486. IndexExpr = RHSExp;
  3487. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3488. } else if (RHSTy->isArrayType()) {
  3489. // Same as previous, except for 123[f().a] case
  3490. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3491. RHSExp->getSourceRange();
  3492. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3493. CK_ArrayToPointerDecay).get();
  3494. RHSTy = RHSExp->getType();
  3495. BaseExpr = RHSExp;
  3496. IndexExpr = LHSExp;
  3497. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3498. } else {
  3499. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  3500. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3501. }
  3502. // C99 6.5.2.1p1
  3503. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3504. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3505. << IndexExpr->getSourceRange());
  3506. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3507. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3508. && !IndexExpr->isTypeDependent())
  3509. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3510. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3511. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3512. // type. Note that Functions are not objects, and that (in C99 parlance)
  3513. // incomplete types are not object types.
  3514. if (ResultType->isFunctionType()) {
  3515. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3516. << ResultType << BaseExpr->getSourceRange();
  3517. return ExprError();
  3518. }
  3519. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3520. // GNU extension: subscripting on pointer to void
  3521. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3522. << BaseExpr->getSourceRange();
  3523. // C forbids expressions of unqualified void type from being l-values.
  3524. // See IsCForbiddenLValueType.
  3525. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3526. } else if (!ResultType->isDependentType() &&
  3527. RequireCompleteType(LLoc, ResultType,
  3528. diag::err_subscript_incomplete_type, BaseExpr))
  3529. return ExprError();
  3530. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3531. !ResultType.isCForbiddenLValueType());
  3532. return new (Context)
  3533. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3534. }
  3535. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3536. FunctionDecl *FD,
  3537. ParmVarDecl *Param) {
  3538. if (Param->hasUnparsedDefaultArg()) {
  3539. Diag(CallLoc,
  3540. diag::err_use_of_default_argument_to_function_declared_later) <<
  3541. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3542. Diag(UnparsedDefaultArgLocs[Param],
  3543. diag::note_default_argument_declared_here);
  3544. return ExprError();
  3545. }
  3546. if (Param->hasUninstantiatedDefaultArg()) {
  3547. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3548. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3549. Param);
  3550. // Instantiate the expression.
  3551. MultiLevelTemplateArgumentList MutiLevelArgList
  3552. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3553. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3554. MutiLevelArgList.getInnermost());
  3555. if (Inst.isInvalid())
  3556. return ExprError();
  3557. ExprResult Result;
  3558. {
  3559. // C++ [dcl.fct.default]p5:
  3560. // The names in the [default argument] expression are bound, and
  3561. // the semantic constraints are checked, at the point where the
  3562. // default argument expression appears.
  3563. ContextRAII SavedContext(*this, FD);
  3564. LocalInstantiationScope Local(*this);
  3565. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3566. }
  3567. if (Result.isInvalid())
  3568. return ExprError();
  3569. // Check the expression as an initializer for the parameter.
  3570. InitializedEntity Entity
  3571. = InitializedEntity::InitializeParameter(Context, Param);
  3572. InitializationKind Kind
  3573. = InitializationKind::CreateCopy(Param->getLocation(),
  3574. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3575. Expr *ResultE = Result.getAs<Expr>();
  3576. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3577. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3578. if (Result.isInvalid())
  3579. return ExprError();
  3580. Expr *Arg = Result.getAs<Expr>();
  3581. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3582. // Build the default argument expression.
  3583. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3584. }
  3585. // If the default expression creates temporaries, we need to
  3586. // push them to the current stack of expression temporaries so they'll
  3587. // be properly destroyed.
  3588. // FIXME: We should really be rebuilding the default argument with new
  3589. // bound temporaries; see the comment in PR5810.
  3590. // We don't need to do that with block decls, though, because
  3591. // blocks in default argument expression can never capture anything.
  3592. if (isa<ExprWithCleanups>(Param->getInit())) {
  3593. // Set the "needs cleanups" bit regardless of whether there are
  3594. // any explicit objects.
  3595. ExprNeedsCleanups = true;
  3596. // Append all the objects to the cleanup list. Right now, this
  3597. // should always be a no-op, because blocks in default argument
  3598. // expressions should never be able to capture anything.
  3599. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3600. "default argument expression has capturing blocks?");
  3601. }
  3602. // We already type-checked the argument, so we know it works.
  3603. // Just mark all of the declarations in this potentially-evaluated expression
  3604. // as being "referenced".
  3605. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3606. /*SkipLocalVariables=*/true);
  3607. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3608. }
  3609. Sema::VariadicCallType
  3610. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3611. Expr *Fn) {
  3612. if (Proto && Proto->isVariadic()) {
  3613. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3614. return VariadicConstructor;
  3615. else if (Fn && Fn->getType()->isBlockPointerType())
  3616. return VariadicBlock;
  3617. else if (FDecl) {
  3618. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3619. if (Method->isInstance())
  3620. return VariadicMethod;
  3621. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3622. return VariadicMethod;
  3623. return VariadicFunction;
  3624. }
  3625. return VariadicDoesNotApply;
  3626. }
  3627. namespace {
  3628. class FunctionCallCCC : public FunctionCallFilterCCC {
  3629. public:
  3630. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3631. unsigned NumArgs, MemberExpr *ME)
  3632. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3633. FunctionName(FuncName) {}
  3634. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3635. if (!candidate.getCorrectionSpecifier() ||
  3636. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3637. return false;
  3638. }
  3639. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3640. }
  3641. private:
  3642. const IdentifierInfo *const FunctionName;
  3643. };
  3644. }
  3645. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3646. FunctionDecl *FDecl,
  3647. ArrayRef<Expr *> Args) {
  3648. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3649. DeclarationName FuncName = FDecl->getDeclName();
  3650. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3651. if (TypoCorrection Corrected = S.CorrectTypo(
  3652. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3653. S.getScopeForContext(S.CurContext), nullptr,
  3654. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3655. Args.size(), ME),
  3656. Sema::CTK_ErrorRecovery)) {
  3657. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3658. if (Corrected.isOverloaded()) {
  3659. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3660. OverloadCandidateSet::iterator Best;
  3661. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3662. CDEnd = Corrected.end();
  3663. CD != CDEnd; ++CD) {
  3664. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3665. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3666. OCS);
  3667. }
  3668. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3669. case OR_Success:
  3670. ND = Best->Function;
  3671. Corrected.setCorrectionDecl(ND);
  3672. break;
  3673. default:
  3674. break;
  3675. }
  3676. }
  3677. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3678. return Corrected;
  3679. }
  3680. }
  3681. }
  3682. return TypoCorrection();
  3683. }
  3684. /// ConvertArgumentsForCall - Converts the arguments specified in
  3685. /// Args/NumArgs to the parameter types of the function FDecl with
  3686. /// function prototype Proto. Call is the call expression itself, and
  3687. /// Fn is the function expression. For a C++ member function, this
  3688. /// routine does not attempt to convert the object argument. Returns
  3689. /// true if the call is ill-formed.
  3690. bool
  3691. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3692. FunctionDecl *FDecl,
  3693. const FunctionProtoType *Proto,
  3694. ArrayRef<Expr *> Args,
  3695. SourceLocation RParenLoc,
  3696. bool IsExecConfig) {
  3697. // Bail out early if calling a builtin with custom typechecking.
  3698. // We don't need to do this in the
  3699. if (FDecl)
  3700. if (unsigned ID = FDecl->getBuiltinID())
  3701. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3702. return false;
  3703. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3704. // assignment, to the types of the corresponding parameter, ...
  3705. unsigned NumParams = Proto->getNumParams();
  3706. bool Invalid = false;
  3707. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3708. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3709. ? 1 /* block */
  3710. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3711. : 0 /* function */);
  3712. // If too few arguments are available (and we don't have default
  3713. // arguments for the remaining parameters), don't make the call.
  3714. if (Args.size() < NumParams) {
  3715. if (Args.size() < MinArgs) {
  3716. TypoCorrection TC;
  3717. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3718. unsigned diag_id =
  3719. MinArgs == NumParams && !Proto->isVariadic()
  3720. ? diag::err_typecheck_call_too_few_args_suggest
  3721. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3722. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3723. << static_cast<unsigned>(Args.size())
  3724. << TC.getCorrectionRange());
  3725. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3726. Diag(RParenLoc,
  3727. MinArgs == NumParams && !Proto->isVariadic()
  3728. ? diag::err_typecheck_call_too_few_args_one
  3729. : diag::err_typecheck_call_too_few_args_at_least_one)
  3730. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3731. else
  3732. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3733. ? diag::err_typecheck_call_too_few_args
  3734. : diag::err_typecheck_call_too_few_args_at_least)
  3735. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3736. << Fn->getSourceRange();
  3737. // Emit the location of the prototype.
  3738. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3739. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3740. << FDecl;
  3741. return true;
  3742. }
  3743. Call->setNumArgs(Context, NumParams);
  3744. }
  3745. // If too many are passed and not variadic, error on the extras and drop
  3746. // them.
  3747. if (Args.size() > NumParams) {
  3748. if (!Proto->isVariadic()) {
  3749. TypoCorrection TC;
  3750. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3751. unsigned diag_id =
  3752. MinArgs == NumParams && !Proto->isVariadic()
  3753. ? diag::err_typecheck_call_too_many_args_suggest
  3754. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  3755. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  3756. << static_cast<unsigned>(Args.size())
  3757. << TC.getCorrectionRange());
  3758. } else if (NumParams == 1 && FDecl &&
  3759. FDecl->getParamDecl(0)->getDeclName())
  3760. Diag(Args[NumParams]->getLocStart(),
  3761. MinArgs == NumParams
  3762. ? diag::err_typecheck_call_too_many_args_one
  3763. : diag::err_typecheck_call_too_many_args_at_most_one)
  3764. << FnKind << FDecl->getParamDecl(0)
  3765. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  3766. << SourceRange(Args[NumParams]->getLocStart(),
  3767. Args.back()->getLocEnd());
  3768. else
  3769. Diag(Args[NumParams]->getLocStart(),
  3770. MinArgs == NumParams
  3771. ? diag::err_typecheck_call_too_many_args
  3772. : diag::err_typecheck_call_too_many_args_at_most)
  3773. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  3774. << Fn->getSourceRange()
  3775. << SourceRange(Args[NumParams]->getLocStart(),
  3776. Args.back()->getLocEnd());
  3777. // Emit the location of the prototype.
  3778. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3779. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3780. << FDecl;
  3781. // This deletes the extra arguments.
  3782. Call->setNumArgs(Context, NumParams);
  3783. return true;
  3784. }
  3785. }
  3786. SmallVector<Expr *, 8> AllArgs;
  3787. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  3788. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  3789. Proto, 0, Args, AllArgs, CallType);
  3790. if (Invalid)
  3791. return true;
  3792. unsigned TotalNumArgs = AllArgs.size();
  3793. for (unsigned i = 0; i < TotalNumArgs; ++i)
  3794. Call->setArg(i, AllArgs[i]);
  3795. return false;
  3796. }
  3797. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  3798. const FunctionProtoType *Proto,
  3799. unsigned FirstParam, ArrayRef<Expr *> Args,
  3800. SmallVectorImpl<Expr *> &AllArgs,
  3801. VariadicCallType CallType, bool AllowExplicit,
  3802. bool IsListInitialization) {
  3803. unsigned NumParams = Proto->getNumParams();
  3804. bool Invalid = false;
  3805. unsigned ArgIx = 0;
  3806. // Continue to check argument types (even if we have too few/many args).
  3807. for (unsigned i = FirstParam; i < NumParams; i++) {
  3808. QualType ProtoArgType = Proto->getParamType(i);
  3809. Expr *Arg;
  3810. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  3811. if (ArgIx < Args.size()) {
  3812. Arg = Args[ArgIx++];
  3813. if (RequireCompleteType(Arg->getLocStart(),
  3814. ProtoArgType,
  3815. diag::err_call_incomplete_argument, Arg))
  3816. return true;
  3817. // Strip the unbridged-cast placeholder expression off, if applicable.
  3818. bool CFAudited = false;
  3819. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  3820. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  3821. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  3822. Arg = stripARCUnbridgedCast(Arg);
  3823. else if (getLangOpts().ObjCAutoRefCount &&
  3824. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  3825. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  3826. CFAudited = true;
  3827. InitializedEntity Entity =
  3828. Param ? InitializedEntity::InitializeParameter(Context, Param,
  3829. ProtoArgType)
  3830. : InitializedEntity::InitializeParameter(
  3831. Context, ProtoArgType, Proto->isParamConsumed(i));
  3832. // Remember that parameter belongs to a CF audited API.
  3833. if (CFAudited)
  3834. Entity.setParameterCFAudited();
  3835. ExprResult ArgE = PerformCopyInitialization(
  3836. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  3837. if (ArgE.isInvalid())
  3838. return true;
  3839. Arg = ArgE.getAs<Expr>();
  3840. } else {
  3841. assert(Param && "can't use default arguments without a known callee");
  3842. ExprResult ArgExpr =
  3843. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  3844. if (ArgExpr.isInvalid())
  3845. return true;
  3846. Arg = ArgExpr.getAs<Expr>();
  3847. }
  3848. // Check for array bounds violations for each argument to the call. This
  3849. // check only triggers warnings when the argument isn't a more complex Expr
  3850. // with its own checking, such as a BinaryOperator.
  3851. CheckArrayAccess(Arg);
  3852. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  3853. CheckStaticArrayArgument(CallLoc, Param, Arg);
  3854. AllArgs.push_back(Arg);
  3855. }
  3856. // If this is a variadic call, handle args passed through "...".
  3857. if (CallType != VariadicDoesNotApply) {
  3858. // Assume that extern "C" functions with variadic arguments that
  3859. // return __unknown_anytype aren't *really* variadic.
  3860. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  3861. FDecl->isExternC()) {
  3862. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  3863. QualType paramType; // ignored
  3864. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  3865. Invalid |= arg.isInvalid();
  3866. AllArgs.push_back(arg.get());
  3867. }
  3868. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  3869. } else {
  3870. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  3871. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  3872. FDecl);
  3873. Invalid |= Arg.isInvalid();
  3874. AllArgs.push_back(Arg.get());
  3875. }
  3876. }
  3877. // Check for array bounds violations.
  3878. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  3879. CheckArrayAccess(Args[i]);
  3880. }
  3881. return Invalid;
  3882. }
  3883. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  3884. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  3885. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  3886. TL = DTL.getOriginalLoc();
  3887. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  3888. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  3889. << ATL.getLocalSourceRange();
  3890. }
  3891. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  3892. /// array parameter, check that it is non-null, and that if it is formed by
  3893. /// array-to-pointer decay, the underlying array is sufficiently large.
  3894. ///
  3895. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  3896. /// array type derivation, then for each call to the function, the value of the
  3897. /// corresponding actual argument shall provide access to the first element of
  3898. /// an array with at least as many elements as specified by the size expression.
  3899. void
  3900. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  3901. ParmVarDecl *Param,
  3902. const Expr *ArgExpr) {
  3903. // Static array parameters are not supported in C++.
  3904. if (!Param || getLangOpts().CPlusPlus)
  3905. return;
  3906. QualType OrigTy = Param->getOriginalType();
  3907. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  3908. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  3909. return;
  3910. if (ArgExpr->isNullPointerConstant(Context,
  3911. Expr::NPC_NeverValueDependent)) {
  3912. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  3913. DiagnoseCalleeStaticArrayParam(*this, Param);
  3914. return;
  3915. }
  3916. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  3917. if (!CAT)
  3918. return;
  3919. const ConstantArrayType *ArgCAT =
  3920. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  3921. if (!ArgCAT)
  3922. return;
  3923. if (ArgCAT->getSize().ult(CAT->getSize())) {
  3924. Diag(CallLoc, diag::warn_static_array_too_small)
  3925. << ArgExpr->getSourceRange()
  3926. << (unsigned) ArgCAT->getSize().getZExtValue()
  3927. << (unsigned) CAT->getSize().getZExtValue();
  3928. DiagnoseCalleeStaticArrayParam(*this, Param);
  3929. }
  3930. }
  3931. /// Given a function expression of unknown-any type, try to rebuild it
  3932. /// to have a function type.
  3933. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  3934. /// Is the given type a placeholder that we need to lower out
  3935. /// immediately during argument processing?
  3936. static bool isPlaceholderToRemoveAsArg(QualType type) {
  3937. // Placeholders are never sugared.
  3938. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  3939. if (!placeholder) return false;
  3940. switch (placeholder->getKind()) {
  3941. // Ignore all the non-placeholder types.
  3942. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  3943. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  3944. #include "clang/AST/BuiltinTypes.def"
  3945. return false;
  3946. // We cannot lower out overload sets; they might validly be resolved
  3947. // by the call machinery.
  3948. case BuiltinType::Overload:
  3949. return false;
  3950. // Unbridged casts in ARC can be handled in some call positions and
  3951. // should be left in place.
  3952. case BuiltinType::ARCUnbridgedCast:
  3953. return false;
  3954. // Pseudo-objects should be converted as soon as possible.
  3955. case BuiltinType::PseudoObject:
  3956. return true;
  3957. // The debugger mode could theoretically but currently does not try
  3958. // to resolve unknown-typed arguments based on known parameter types.
  3959. case BuiltinType::UnknownAny:
  3960. return true;
  3961. // These are always invalid as call arguments and should be reported.
  3962. case BuiltinType::BoundMember:
  3963. case BuiltinType::BuiltinFn:
  3964. return true;
  3965. }
  3966. llvm_unreachable("bad builtin type kind");
  3967. }
  3968. /// Check an argument list for placeholders that we won't try to
  3969. /// handle later.
  3970. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  3971. // Apply this processing to all the arguments at once instead of
  3972. // dying at the first failure.
  3973. bool hasInvalid = false;
  3974. for (size_t i = 0, e = args.size(); i != e; i++) {
  3975. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  3976. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  3977. if (result.isInvalid()) hasInvalid = true;
  3978. else args[i] = result.get();
  3979. } else if (hasInvalid) {
  3980. (void)S.CorrectDelayedTyposInExpr(args[i]);
  3981. }
  3982. }
  3983. return hasInvalid;
  3984. }
  3985. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  3986. /// This provides the location of the left/right parens and a list of comma
  3987. /// locations.
  3988. ExprResult
  3989. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  3990. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  3991. Expr *ExecConfig, bool IsExecConfig) {
  3992. // Since this might be a postfix expression, get rid of ParenListExprs.
  3993. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  3994. if (Result.isInvalid()) return ExprError();
  3995. Fn = Result.get();
  3996. if (checkArgsForPlaceholders(*this, ArgExprs))
  3997. return ExprError();
  3998. if (getLangOpts().CPlusPlus) {
  3999. // If this is a pseudo-destructor expression, build the call immediately.
  4000. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4001. if (!ArgExprs.empty()) {
  4002. // Pseudo-destructor calls should not have any arguments.
  4003. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4004. << FixItHint::CreateRemoval(
  4005. SourceRange(ArgExprs[0]->getLocStart(),
  4006. ArgExprs.back()->getLocEnd()));
  4007. }
  4008. return new (Context)
  4009. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4010. }
  4011. if (Fn->getType() == Context.PseudoObjectTy) {
  4012. ExprResult result = CheckPlaceholderExpr(Fn);
  4013. if (result.isInvalid()) return ExprError();
  4014. Fn = result.get();
  4015. }
  4016. // Determine whether this is a dependent call inside a C++ template,
  4017. // in which case we won't do any semantic analysis now.
  4018. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4019. // Fn.
  4020. bool Dependent = false;
  4021. if (Fn->isTypeDependent())
  4022. Dependent = true;
  4023. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4024. Dependent = true;
  4025. if (Dependent) {
  4026. if (ExecConfig) {
  4027. return new (Context) CUDAKernelCallExpr(
  4028. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4029. Context.DependentTy, VK_RValue, RParenLoc);
  4030. } else {
  4031. return new (Context) CallExpr(
  4032. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4033. }
  4034. }
  4035. // Determine whether this is a call to an object (C++ [over.call.object]).
  4036. if (Fn->getType()->isRecordType())
  4037. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4038. RParenLoc);
  4039. if (Fn->getType() == Context.UnknownAnyTy) {
  4040. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4041. if (result.isInvalid()) return ExprError();
  4042. Fn = result.get();
  4043. }
  4044. if (Fn->getType() == Context.BoundMemberTy) {
  4045. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4046. }
  4047. }
  4048. // Check for overloaded calls. This can happen even in C due to extensions.
  4049. if (Fn->getType() == Context.OverloadTy) {
  4050. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4051. // We aren't supposed to apply this logic for if there's an '&' involved.
  4052. if (!find.HasFormOfMemberPointer) {
  4053. OverloadExpr *ovl = find.Expression;
  4054. if (isa<UnresolvedLookupExpr>(ovl)) {
  4055. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4056. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4057. RParenLoc, ExecConfig);
  4058. } else {
  4059. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4060. RParenLoc);
  4061. }
  4062. }
  4063. }
  4064. // If we're directly calling a function, get the appropriate declaration.
  4065. if (Fn->getType() == Context.UnknownAnyTy) {
  4066. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4067. if (result.isInvalid()) return ExprError();
  4068. Fn = result.get();
  4069. }
  4070. Expr *NakedFn = Fn->IgnoreParens();
  4071. NamedDecl *NDecl = nullptr;
  4072. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4073. if (UnOp->getOpcode() == UO_AddrOf)
  4074. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4075. if (isa<DeclRefExpr>(NakedFn))
  4076. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4077. else if (isa<MemberExpr>(NakedFn))
  4078. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4079. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4080. if (FD->hasAttr<EnableIfAttr>()) {
  4081. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4082. Diag(Fn->getLocStart(),
  4083. isa<CXXMethodDecl>(FD) ?
  4084. diag::err_ovl_no_viable_member_function_in_call :
  4085. diag::err_ovl_no_viable_function_in_call)
  4086. << FD << FD->getSourceRange();
  4087. Diag(FD->getLocation(),
  4088. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4089. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4090. }
  4091. }
  4092. }
  4093. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4094. ExecConfig, IsExecConfig);
  4095. }
  4096. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4097. ///
  4098. /// __builtin_astype( value, dst type )
  4099. ///
  4100. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4101. SourceLocation BuiltinLoc,
  4102. SourceLocation RParenLoc) {
  4103. ExprValueKind VK = VK_RValue;
  4104. ExprObjectKind OK = OK_Ordinary;
  4105. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4106. QualType SrcTy = E->getType();
  4107. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4108. return ExprError(Diag(BuiltinLoc,
  4109. diag::err_invalid_astype_of_different_size)
  4110. << DstTy
  4111. << SrcTy
  4112. << E->getSourceRange());
  4113. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4114. }
  4115. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4116. /// provided arguments.
  4117. ///
  4118. /// __builtin_convertvector( value, dst type )
  4119. ///
  4120. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4121. SourceLocation BuiltinLoc,
  4122. SourceLocation RParenLoc) {
  4123. TypeSourceInfo *TInfo;
  4124. GetTypeFromParser(ParsedDestTy, &TInfo);
  4125. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4126. }
  4127. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4128. /// i.e. an expression not of \p OverloadTy. The expression should
  4129. /// unary-convert to an expression of function-pointer or
  4130. /// block-pointer type.
  4131. ///
  4132. /// \param NDecl the declaration being called, if available
  4133. ExprResult
  4134. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4135. SourceLocation LParenLoc,
  4136. ArrayRef<Expr *> Args,
  4137. SourceLocation RParenLoc,
  4138. Expr *Config, bool IsExecConfig) {
  4139. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4140. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4141. // Promote the function operand.
  4142. // We special-case function promotion here because we only allow promoting
  4143. // builtin functions to function pointers in the callee of a call.
  4144. ExprResult Result;
  4145. if (BuiltinID &&
  4146. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4147. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4148. CK_BuiltinFnToFnPtr).get();
  4149. } else {
  4150. Result = CallExprUnaryConversions(Fn);
  4151. }
  4152. if (Result.isInvalid())
  4153. return ExprError();
  4154. Fn = Result.get();
  4155. // Make the call expr early, before semantic checks. This guarantees cleanup
  4156. // of arguments and function on error.
  4157. CallExpr *TheCall;
  4158. if (Config)
  4159. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4160. cast<CallExpr>(Config), Args,
  4161. Context.BoolTy, VK_RValue,
  4162. RParenLoc);
  4163. else
  4164. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4165. VK_RValue, RParenLoc);
  4166. // Bail out early if calling a builtin with custom typechecking.
  4167. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4168. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4169. retry:
  4170. const FunctionType *FuncT;
  4171. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4172. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4173. // have type pointer to function".
  4174. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4175. if (!FuncT)
  4176. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4177. << Fn->getType() << Fn->getSourceRange());
  4178. } else if (const BlockPointerType *BPT =
  4179. Fn->getType()->getAs<BlockPointerType>()) {
  4180. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4181. } else {
  4182. // Handle calls to expressions of unknown-any type.
  4183. if (Fn->getType() == Context.UnknownAnyTy) {
  4184. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4185. if (rewrite.isInvalid()) return ExprError();
  4186. Fn = rewrite.get();
  4187. TheCall->setCallee(Fn);
  4188. goto retry;
  4189. }
  4190. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4191. << Fn->getType() << Fn->getSourceRange());
  4192. }
  4193. if (getLangOpts().CUDA) {
  4194. if (Config) {
  4195. // CUDA: Kernel calls must be to global functions
  4196. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4197. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4198. << FDecl->getName() << Fn->getSourceRange());
  4199. // CUDA: Kernel function must have 'void' return type
  4200. if (!FuncT->getReturnType()->isVoidType())
  4201. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4202. << Fn->getType() << Fn->getSourceRange());
  4203. } else {
  4204. // CUDA: Calls to global functions must be configured
  4205. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4206. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4207. << FDecl->getName() << Fn->getSourceRange());
  4208. }
  4209. }
  4210. // Check for a valid return type
  4211. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4212. FDecl))
  4213. return ExprError();
  4214. // We know the result type of the call, set it.
  4215. TheCall->setType(FuncT->getCallResultType(Context));
  4216. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4217. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4218. if (Proto) {
  4219. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4220. IsExecConfig))
  4221. return ExprError();
  4222. } else {
  4223. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4224. if (FDecl) {
  4225. // Check if we have too few/too many template arguments, based
  4226. // on our knowledge of the function definition.
  4227. const FunctionDecl *Def = nullptr;
  4228. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4229. Proto = Def->getType()->getAs<FunctionProtoType>();
  4230. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4231. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4232. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4233. }
  4234. // If the function we're calling isn't a function prototype, but we have
  4235. // a function prototype from a prior declaratiom, use that prototype.
  4236. if (!FDecl->hasPrototype())
  4237. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4238. }
  4239. // Promote the arguments (C99 6.5.2.2p6).
  4240. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4241. Expr *Arg = Args[i];
  4242. if (Proto && i < Proto->getNumParams()) {
  4243. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4244. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4245. ExprResult ArgE =
  4246. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4247. if (ArgE.isInvalid())
  4248. return true;
  4249. Arg = ArgE.getAs<Expr>();
  4250. } else {
  4251. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4252. if (ArgE.isInvalid())
  4253. return true;
  4254. Arg = ArgE.getAs<Expr>();
  4255. }
  4256. if (RequireCompleteType(Arg->getLocStart(),
  4257. Arg->getType(),
  4258. diag::err_call_incomplete_argument, Arg))
  4259. return ExprError();
  4260. TheCall->setArg(i, Arg);
  4261. }
  4262. }
  4263. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4264. if (!Method->isStatic())
  4265. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4266. << Fn->getSourceRange());
  4267. // Check for sentinels
  4268. if (NDecl)
  4269. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4270. // Do special checking on direct calls to functions.
  4271. if (FDecl) {
  4272. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4273. return ExprError();
  4274. if (BuiltinID)
  4275. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4276. } else if (NDecl) {
  4277. if (CheckPointerCall(NDecl, TheCall, Proto))
  4278. return ExprError();
  4279. } else {
  4280. if (CheckOtherCall(TheCall, Proto))
  4281. return ExprError();
  4282. }
  4283. return MaybeBindToTemporary(TheCall);
  4284. }
  4285. ExprResult
  4286. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4287. SourceLocation RParenLoc, Expr *InitExpr) {
  4288. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4289. // FIXME: put back this assert when initializers are worked out.
  4290. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
  4291. TypeSourceInfo *TInfo;
  4292. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4293. if (!TInfo)
  4294. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4295. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4296. }
  4297. ExprResult
  4298. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4299. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4300. QualType literalType = TInfo->getType();
  4301. if (literalType->isArrayType()) {
  4302. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4303. diag::err_illegal_decl_array_incomplete_type,
  4304. SourceRange(LParenLoc,
  4305. LiteralExpr->getSourceRange().getEnd())))
  4306. return ExprError();
  4307. if (literalType->isVariableArrayType())
  4308. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4309. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4310. } else if (!literalType->isDependentType() &&
  4311. RequireCompleteType(LParenLoc, literalType,
  4312. diag::err_typecheck_decl_incomplete_type,
  4313. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4314. return ExprError();
  4315. InitializedEntity Entity
  4316. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4317. InitializationKind Kind
  4318. = InitializationKind::CreateCStyleCast(LParenLoc,
  4319. SourceRange(LParenLoc, RParenLoc),
  4320. /*InitList=*/true);
  4321. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4322. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4323. &literalType);
  4324. if (Result.isInvalid())
  4325. return ExprError();
  4326. LiteralExpr = Result.get();
  4327. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4328. if (isFileScope &&
  4329. !LiteralExpr->isTypeDependent() &&
  4330. !LiteralExpr->isValueDependent() &&
  4331. !literalType->isDependentType()) { // 6.5.2.5p3
  4332. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4333. return ExprError();
  4334. }
  4335. // In C, compound literals are l-values for some reason.
  4336. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4337. return MaybeBindToTemporary(
  4338. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4339. VK, LiteralExpr, isFileScope));
  4340. }
  4341. ExprResult
  4342. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4343. SourceLocation RBraceLoc) {
  4344. // Immediately handle non-overload placeholders. Overloads can be
  4345. // resolved contextually, but everything else here can't.
  4346. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4347. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4348. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4349. // Ignore failures; dropping the entire initializer list because
  4350. // of one failure would be terrible for indexing/etc.
  4351. if (result.isInvalid()) continue;
  4352. InitArgList[I] = result.get();
  4353. }
  4354. }
  4355. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4356. // CheckInitializer() - it requires knowledge of the object being intialized.
  4357. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4358. RBraceLoc);
  4359. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4360. return E;
  4361. }
  4362. /// Do an explicit extend of the given block pointer if we're in ARC.
  4363. static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
  4364. assert(E.get()->getType()->isBlockPointerType());
  4365. assert(E.get()->isRValue());
  4366. // Only do this in an r-value context.
  4367. if (!S.getLangOpts().ObjCAutoRefCount) return;
  4368. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
  4369. CK_ARCExtendBlockObject, E.get(),
  4370. /*base path*/ nullptr, VK_RValue);
  4371. S.ExprNeedsCleanups = true;
  4372. }
  4373. /// Prepare a conversion of the given expression to an ObjC object
  4374. /// pointer type.
  4375. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4376. QualType type = E.get()->getType();
  4377. if (type->isObjCObjectPointerType()) {
  4378. return CK_BitCast;
  4379. } else if (type->isBlockPointerType()) {
  4380. maybeExtendBlockObject(*this, E);
  4381. return CK_BlockPointerToObjCPointerCast;
  4382. } else {
  4383. assert(type->isPointerType());
  4384. return CK_CPointerToObjCPointerCast;
  4385. }
  4386. }
  4387. /// Prepares for a scalar cast, performing all the necessary stages
  4388. /// except the final cast and returning the kind required.
  4389. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4390. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4391. // Also, callers should have filtered out the invalid cases with
  4392. // pointers. Everything else should be possible.
  4393. QualType SrcTy = Src.get()->getType();
  4394. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4395. return CK_NoOp;
  4396. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4397. case Type::STK_MemberPointer:
  4398. llvm_unreachable("member pointer type in C");
  4399. case Type::STK_CPointer:
  4400. case Type::STK_BlockPointer:
  4401. case Type::STK_ObjCObjectPointer:
  4402. switch (DestTy->getScalarTypeKind()) {
  4403. case Type::STK_CPointer: {
  4404. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4405. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4406. if (SrcAS != DestAS)
  4407. return CK_AddressSpaceConversion;
  4408. return CK_BitCast;
  4409. }
  4410. case Type::STK_BlockPointer:
  4411. return (SrcKind == Type::STK_BlockPointer
  4412. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4413. case Type::STK_ObjCObjectPointer:
  4414. if (SrcKind == Type::STK_ObjCObjectPointer)
  4415. return CK_BitCast;
  4416. if (SrcKind == Type::STK_CPointer)
  4417. return CK_CPointerToObjCPointerCast;
  4418. maybeExtendBlockObject(*this, Src);
  4419. return CK_BlockPointerToObjCPointerCast;
  4420. case Type::STK_Bool:
  4421. return CK_PointerToBoolean;
  4422. case Type::STK_Integral:
  4423. return CK_PointerToIntegral;
  4424. case Type::STK_Floating:
  4425. case Type::STK_FloatingComplex:
  4426. case Type::STK_IntegralComplex:
  4427. case Type::STK_MemberPointer:
  4428. llvm_unreachable("illegal cast from pointer");
  4429. }
  4430. llvm_unreachable("Should have returned before this");
  4431. case Type::STK_Bool: // casting from bool is like casting from an integer
  4432. case Type::STK_Integral:
  4433. switch (DestTy->getScalarTypeKind()) {
  4434. case Type::STK_CPointer:
  4435. case Type::STK_ObjCObjectPointer:
  4436. case Type::STK_BlockPointer:
  4437. if (Src.get()->isNullPointerConstant(Context,
  4438. Expr::NPC_ValueDependentIsNull))
  4439. return CK_NullToPointer;
  4440. return CK_IntegralToPointer;
  4441. case Type::STK_Bool:
  4442. return CK_IntegralToBoolean;
  4443. case Type::STK_Integral:
  4444. return CK_IntegralCast;
  4445. case Type::STK_Floating:
  4446. return CK_IntegralToFloating;
  4447. case Type::STK_IntegralComplex:
  4448. Src = ImpCastExprToType(Src.get(),
  4449. DestTy->castAs<ComplexType>()->getElementType(),
  4450. CK_IntegralCast);
  4451. return CK_IntegralRealToComplex;
  4452. case Type::STK_FloatingComplex:
  4453. Src = ImpCastExprToType(Src.get(),
  4454. DestTy->castAs<ComplexType>()->getElementType(),
  4455. CK_IntegralToFloating);
  4456. return CK_FloatingRealToComplex;
  4457. case Type::STK_MemberPointer:
  4458. llvm_unreachable("member pointer type in C");
  4459. }
  4460. llvm_unreachable("Should have returned before this");
  4461. case Type::STK_Floating:
  4462. switch (DestTy->getScalarTypeKind()) {
  4463. case Type::STK_Floating:
  4464. return CK_FloatingCast;
  4465. case Type::STK_Bool:
  4466. return CK_FloatingToBoolean;
  4467. case Type::STK_Integral:
  4468. return CK_FloatingToIntegral;
  4469. case Type::STK_FloatingComplex:
  4470. Src = ImpCastExprToType(Src.get(),
  4471. DestTy->castAs<ComplexType>()->getElementType(),
  4472. CK_FloatingCast);
  4473. return CK_FloatingRealToComplex;
  4474. case Type::STK_IntegralComplex:
  4475. Src = ImpCastExprToType(Src.get(),
  4476. DestTy->castAs<ComplexType>()->getElementType(),
  4477. CK_FloatingToIntegral);
  4478. return CK_IntegralRealToComplex;
  4479. case Type::STK_CPointer:
  4480. case Type::STK_ObjCObjectPointer:
  4481. case Type::STK_BlockPointer:
  4482. llvm_unreachable("valid float->pointer cast?");
  4483. case Type::STK_MemberPointer:
  4484. llvm_unreachable("member pointer type in C");
  4485. }
  4486. llvm_unreachable("Should have returned before this");
  4487. case Type::STK_FloatingComplex:
  4488. switch (DestTy->getScalarTypeKind()) {
  4489. case Type::STK_FloatingComplex:
  4490. return CK_FloatingComplexCast;
  4491. case Type::STK_IntegralComplex:
  4492. return CK_FloatingComplexToIntegralComplex;
  4493. case Type::STK_Floating: {
  4494. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4495. if (Context.hasSameType(ET, DestTy))
  4496. return CK_FloatingComplexToReal;
  4497. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4498. return CK_FloatingCast;
  4499. }
  4500. case Type::STK_Bool:
  4501. return CK_FloatingComplexToBoolean;
  4502. case Type::STK_Integral:
  4503. Src = ImpCastExprToType(Src.get(),
  4504. SrcTy->castAs<ComplexType>()->getElementType(),
  4505. CK_FloatingComplexToReal);
  4506. return CK_FloatingToIntegral;
  4507. case Type::STK_CPointer:
  4508. case Type::STK_ObjCObjectPointer:
  4509. case Type::STK_BlockPointer:
  4510. llvm_unreachable("valid complex float->pointer cast?");
  4511. case Type::STK_MemberPointer:
  4512. llvm_unreachable("member pointer type in C");
  4513. }
  4514. llvm_unreachable("Should have returned before this");
  4515. case Type::STK_IntegralComplex:
  4516. switch (DestTy->getScalarTypeKind()) {
  4517. case Type::STK_FloatingComplex:
  4518. return CK_IntegralComplexToFloatingComplex;
  4519. case Type::STK_IntegralComplex:
  4520. return CK_IntegralComplexCast;
  4521. case Type::STK_Integral: {
  4522. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4523. if (Context.hasSameType(ET, DestTy))
  4524. return CK_IntegralComplexToReal;
  4525. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4526. return CK_IntegralCast;
  4527. }
  4528. case Type::STK_Bool:
  4529. return CK_IntegralComplexToBoolean;
  4530. case Type::STK_Floating:
  4531. Src = ImpCastExprToType(Src.get(),
  4532. SrcTy->castAs<ComplexType>()->getElementType(),
  4533. CK_IntegralComplexToReal);
  4534. return CK_IntegralToFloating;
  4535. case Type::STK_CPointer:
  4536. case Type::STK_ObjCObjectPointer:
  4537. case Type::STK_BlockPointer:
  4538. llvm_unreachable("valid complex int->pointer cast?");
  4539. case Type::STK_MemberPointer:
  4540. llvm_unreachable("member pointer type in C");
  4541. }
  4542. llvm_unreachable("Should have returned before this");
  4543. }
  4544. llvm_unreachable("Unhandled scalar cast");
  4545. }
  4546. static bool breakDownVectorType(QualType type, uint64_t &len,
  4547. QualType &eltType) {
  4548. // Vectors are simple.
  4549. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4550. len = vecType->getNumElements();
  4551. eltType = vecType->getElementType();
  4552. assert(eltType->isScalarType());
  4553. return true;
  4554. }
  4555. // We allow lax conversion to and from non-vector types, but only if
  4556. // they're real types (i.e. non-complex, non-pointer scalar types).
  4557. if (!type->isRealType()) return false;
  4558. len = 1;
  4559. eltType = type;
  4560. return true;
  4561. }
  4562. static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
  4563. uint64_t srcLen, destLen;
  4564. QualType srcElt, destElt;
  4565. if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
  4566. if (!breakDownVectorType(destTy, destLen, destElt)) return false;
  4567. // ASTContext::getTypeSize will return the size rounded up to a
  4568. // power of 2, so instead of using that, we need to use the raw
  4569. // element size multiplied by the element count.
  4570. uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
  4571. uint64_t destEltSize = S.Context.getTypeSize(destElt);
  4572. return (srcLen * srcEltSize == destLen * destEltSize);
  4573. }
  4574. /// Is this a legal conversion between two known vector types?
  4575. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4576. assert(destTy->isVectorType() || srcTy->isVectorType());
  4577. if (!Context.getLangOpts().LaxVectorConversions)
  4578. return false;
  4579. return VectorTypesMatch(*this, srcTy, destTy);
  4580. }
  4581. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4582. CastKind &Kind) {
  4583. assert(VectorTy->isVectorType() && "Not a vector type!");
  4584. if (Ty->isVectorType() || Ty->isIntegerType()) {
  4585. if (!VectorTypesMatch(*this, Ty, VectorTy))
  4586. return Diag(R.getBegin(),
  4587. Ty->isVectorType() ?
  4588. diag::err_invalid_conversion_between_vectors :
  4589. diag::err_invalid_conversion_between_vector_and_integer)
  4590. << VectorTy << Ty << R;
  4591. } else
  4592. return Diag(R.getBegin(),
  4593. diag::err_invalid_conversion_between_vector_and_scalar)
  4594. << VectorTy << Ty << R;
  4595. Kind = CK_BitCast;
  4596. return false;
  4597. }
  4598. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4599. Expr *CastExpr, CastKind &Kind) {
  4600. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4601. QualType SrcTy = CastExpr->getType();
  4602. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4603. // an ExtVectorType.
  4604. // In OpenCL, casts between vectors of different types are not allowed.
  4605. // (See OpenCL 6.2).
  4606. if (SrcTy->isVectorType()) {
  4607. if (!VectorTypesMatch(*this, SrcTy, DestTy)
  4608. || (getLangOpts().OpenCL &&
  4609. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4610. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4611. << DestTy << SrcTy << R;
  4612. return ExprError();
  4613. }
  4614. Kind = CK_BitCast;
  4615. return CastExpr;
  4616. }
  4617. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4618. // conversion will take place first from scalar to elt type, and then
  4619. // splat from elt type to vector.
  4620. if (SrcTy->isPointerType())
  4621. return Diag(R.getBegin(),
  4622. diag::err_invalid_conversion_between_vector_and_scalar)
  4623. << DestTy << SrcTy << R;
  4624. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4625. ExprResult CastExprRes = CastExpr;
  4626. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4627. if (CastExprRes.isInvalid())
  4628. return ExprError();
  4629. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4630. Kind = CK_VectorSplat;
  4631. return CastExpr;
  4632. }
  4633. ExprResult
  4634. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4635. Declarator &D, ParsedType &Ty,
  4636. SourceLocation RParenLoc, Expr *CastExpr) {
  4637. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4638. "ActOnCastExpr(): missing type or expr");
  4639. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4640. if (D.isInvalidType())
  4641. return ExprError();
  4642. if (getLangOpts().CPlusPlus) {
  4643. // Check that there are no default arguments (C++ only).
  4644. CheckExtraCXXDefaultArguments(D);
  4645. } else {
  4646. // Make sure any TypoExprs have been dealt with.
  4647. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4648. if (!Res.isUsable())
  4649. return ExprError();
  4650. CastExpr = Res.get();
  4651. }
  4652. checkUnusedDeclAttributes(D);
  4653. QualType castType = castTInfo->getType();
  4654. Ty = CreateParsedType(castType, castTInfo);
  4655. bool isVectorLiteral = false;
  4656. // Check for an altivec or OpenCL literal,
  4657. // i.e. all the elements are integer constants.
  4658. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  4659. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  4660. if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
  4661. && castType->isVectorType() && (PE || PLE)) {
  4662. if (PLE && PLE->getNumExprs() == 0) {
  4663. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  4664. return ExprError();
  4665. }
  4666. if (PE || PLE->getNumExprs() == 1) {
  4667. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  4668. if (!E->getType()->isVectorType())
  4669. isVectorLiteral = true;
  4670. }
  4671. else
  4672. isVectorLiteral = true;
  4673. }
  4674. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  4675. // then handle it as such.
  4676. if (isVectorLiteral)
  4677. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  4678. // If the Expr being casted is a ParenListExpr, handle it specially.
  4679. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  4680. // sequence of BinOp comma operators.
  4681. if (isa<ParenListExpr>(CastExpr)) {
  4682. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  4683. if (Result.isInvalid()) return ExprError();
  4684. CastExpr = Result.get();
  4685. }
  4686. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  4687. !getSourceManager().isInSystemMacro(LParenLoc))
  4688. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  4689. CheckTollFreeBridgeCast(castType, CastExpr);
  4690. CheckObjCBridgeRelatedCast(castType, CastExpr);
  4691. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  4692. }
  4693. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  4694. SourceLocation RParenLoc, Expr *E,
  4695. TypeSourceInfo *TInfo) {
  4696. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  4697. "Expected paren or paren list expression");
  4698. Expr **exprs;
  4699. unsigned numExprs;
  4700. Expr *subExpr;
  4701. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  4702. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  4703. LiteralLParenLoc = PE->getLParenLoc();
  4704. LiteralRParenLoc = PE->getRParenLoc();
  4705. exprs = PE->getExprs();
  4706. numExprs = PE->getNumExprs();
  4707. } else { // isa<ParenExpr> by assertion at function entrance
  4708. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  4709. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  4710. subExpr = cast<ParenExpr>(E)->getSubExpr();
  4711. exprs = &subExpr;
  4712. numExprs = 1;
  4713. }
  4714. QualType Ty = TInfo->getType();
  4715. assert(Ty->isVectorType() && "Expected vector type");
  4716. SmallVector<Expr *, 8> initExprs;
  4717. const VectorType *VTy = Ty->getAs<VectorType>();
  4718. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  4719. // '(...)' form of vector initialization in AltiVec: the number of
  4720. // initializers must be one or must match the size of the vector.
  4721. // If a single value is specified in the initializer then it will be
  4722. // replicated to all the components of the vector
  4723. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  4724. // The number of initializers must be one or must match the size of the
  4725. // vector. If a single value is specified in the initializer then it will
  4726. // be replicated to all the components of the vector
  4727. if (numExprs == 1) {
  4728. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  4729. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  4730. if (Literal.isInvalid())
  4731. return ExprError();
  4732. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  4733. PrepareScalarCast(Literal, ElemTy));
  4734. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  4735. }
  4736. else if (numExprs < numElems) {
  4737. Diag(E->getExprLoc(),
  4738. diag::err_incorrect_number_of_vector_initializers);
  4739. return ExprError();
  4740. }
  4741. else
  4742. initExprs.append(exprs, exprs + numExprs);
  4743. }
  4744. else {
  4745. // For OpenCL, when the number of initializers is a single value,
  4746. // it will be replicated to all components of the vector.
  4747. if (getLangOpts().OpenCL &&
  4748. VTy->getVectorKind() == VectorType::GenericVector &&
  4749. numExprs == 1) {
  4750. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  4751. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  4752. if (Literal.isInvalid())
  4753. return ExprError();
  4754. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  4755. PrepareScalarCast(Literal, ElemTy));
  4756. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  4757. }
  4758. initExprs.append(exprs, exprs + numExprs);
  4759. }
  4760. // FIXME: This means that pretty-printing the final AST will produce curly
  4761. // braces instead of the original commas.
  4762. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  4763. initExprs, LiteralRParenLoc);
  4764. initE->setType(Ty);
  4765. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  4766. }
  4767. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  4768. /// the ParenListExpr into a sequence of comma binary operators.
  4769. ExprResult
  4770. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  4771. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  4772. if (!E)
  4773. return OrigExpr;
  4774. ExprResult Result(E->getExpr(0));
  4775. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  4776. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  4777. E->getExpr(i));
  4778. if (Result.isInvalid()) return ExprError();
  4779. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  4780. }
  4781. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  4782. SourceLocation R,
  4783. MultiExprArg Val) {
  4784. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  4785. return expr;
  4786. }
  4787. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  4788. /// constant and the other is not a pointer. Returns true if a diagnostic is
  4789. /// emitted.
  4790. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  4791. SourceLocation QuestionLoc) {
  4792. Expr *NullExpr = LHSExpr;
  4793. Expr *NonPointerExpr = RHSExpr;
  4794. Expr::NullPointerConstantKind NullKind =
  4795. NullExpr->isNullPointerConstant(Context,
  4796. Expr::NPC_ValueDependentIsNotNull);
  4797. if (NullKind == Expr::NPCK_NotNull) {
  4798. NullExpr = RHSExpr;
  4799. NonPointerExpr = LHSExpr;
  4800. NullKind =
  4801. NullExpr->isNullPointerConstant(Context,
  4802. Expr::NPC_ValueDependentIsNotNull);
  4803. }
  4804. if (NullKind == Expr::NPCK_NotNull)
  4805. return false;
  4806. if (NullKind == Expr::NPCK_ZeroExpression)
  4807. return false;
  4808. if (NullKind == Expr::NPCK_ZeroLiteral) {
  4809. // In this case, check to make sure that we got here from a "NULL"
  4810. // string in the source code.
  4811. NullExpr = NullExpr->IgnoreParenImpCasts();
  4812. SourceLocation loc = NullExpr->getExprLoc();
  4813. if (!findMacroSpelling(loc, "NULL"))
  4814. return false;
  4815. }
  4816. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  4817. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  4818. << NonPointerExpr->getType() << DiagType
  4819. << NonPointerExpr->getSourceRange();
  4820. return true;
  4821. }
  4822. /// \brief Return false if the condition expression is valid, true otherwise.
  4823. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  4824. QualType CondTy = Cond->getType();
  4825. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  4826. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  4827. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  4828. << CondTy << Cond->getSourceRange();
  4829. return true;
  4830. }
  4831. // C99 6.5.15p2
  4832. if (CondTy->isScalarType()) return false;
  4833. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  4834. << CondTy << Cond->getSourceRange();
  4835. return true;
  4836. }
  4837. /// \brief Handle when one or both operands are void type.
  4838. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  4839. ExprResult &RHS) {
  4840. Expr *LHSExpr = LHS.get();
  4841. Expr *RHSExpr = RHS.get();
  4842. if (!LHSExpr->getType()->isVoidType())
  4843. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  4844. << RHSExpr->getSourceRange();
  4845. if (!RHSExpr->getType()->isVoidType())
  4846. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  4847. << LHSExpr->getSourceRange();
  4848. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  4849. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  4850. return S.Context.VoidTy;
  4851. }
  4852. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  4853. /// true otherwise.
  4854. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  4855. QualType PointerTy) {
  4856. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  4857. !NullExpr.get()->isNullPointerConstant(S.Context,
  4858. Expr::NPC_ValueDependentIsNull))
  4859. return true;
  4860. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  4861. return false;
  4862. }
  4863. /// \brief Checks compatibility between two pointers and return the resulting
  4864. /// type.
  4865. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  4866. ExprResult &RHS,
  4867. SourceLocation Loc) {
  4868. QualType LHSTy = LHS.get()->getType();
  4869. QualType RHSTy = RHS.get()->getType();
  4870. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  4871. // Two identical pointers types are always compatible.
  4872. return LHSTy;
  4873. }
  4874. QualType lhptee, rhptee;
  4875. // Get the pointee types.
  4876. bool IsBlockPointer = false;
  4877. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  4878. lhptee = LHSBTy->getPointeeType();
  4879. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  4880. IsBlockPointer = true;
  4881. } else {
  4882. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  4883. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  4884. }
  4885. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  4886. // differently qualified versions of compatible types, the result type is
  4887. // a pointer to an appropriately qualified version of the composite
  4888. // type.
  4889. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  4890. // clause doesn't make sense for our extensions. E.g. address space 2 should
  4891. // be incompatible with address space 3: they may live on different devices or
  4892. // anything.
  4893. Qualifiers lhQual = lhptee.getQualifiers();
  4894. Qualifiers rhQual = rhptee.getQualifiers();
  4895. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  4896. lhQual.removeCVRQualifiers();
  4897. rhQual.removeCVRQualifiers();
  4898. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  4899. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  4900. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  4901. if (CompositeTy.isNull()) {
  4902. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  4903. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  4904. << RHS.get()->getSourceRange();
  4905. // In this situation, we assume void* type. No especially good
  4906. // reason, but this is what gcc does, and we do have to pick
  4907. // to get a consistent AST.
  4908. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  4909. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  4910. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  4911. return incompatTy;
  4912. }
  4913. // The pointer types are compatible.
  4914. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  4915. if (IsBlockPointer)
  4916. ResultTy = S.Context.getBlockPointerType(ResultTy);
  4917. else
  4918. ResultTy = S.Context.getPointerType(ResultTy);
  4919. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  4920. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  4921. return ResultTy;
  4922. }
  4923. /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
  4924. /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
  4925. /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
  4926. static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
  4927. if (QT->isObjCIdType())
  4928. return true;
  4929. const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
  4930. if (!OPT)
  4931. return false;
  4932. if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
  4933. if (ID->getIdentifier() != &C.Idents.get("NSObject"))
  4934. return false;
  4935. ObjCProtocolDecl* PNSCopying =
  4936. S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
  4937. ObjCProtocolDecl* PNSObject =
  4938. S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
  4939. for (auto *Proto : OPT->quals()) {
  4940. if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
  4941. (PNSObject && declaresSameEntity(Proto, PNSObject)))
  4942. ;
  4943. else
  4944. return false;
  4945. }
  4946. return true;
  4947. }
  4948. /// \brief Return the resulting type when the operands are both block pointers.
  4949. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  4950. ExprResult &LHS,
  4951. ExprResult &RHS,
  4952. SourceLocation Loc) {
  4953. QualType LHSTy = LHS.get()->getType();
  4954. QualType RHSTy = RHS.get()->getType();
  4955. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  4956. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  4957. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  4958. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  4959. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  4960. return destType;
  4961. }
  4962. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  4963. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  4964. << RHS.get()->getSourceRange();
  4965. return QualType();
  4966. }
  4967. // We have 2 block pointer types.
  4968. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  4969. }
  4970. /// \brief Return the resulting type when the operands are both pointers.
  4971. static QualType
  4972. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  4973. ExprResult &RHS,
  4974. SourceLocation Loc) {
  4975. // get the pointer types
  4976. QualType LHSTy = LHS.get()->getType();
  4977. QualType RHSTy = RHS.get()->getType();
  4978. // get the "pointed to" types
  4979. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  4980. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  4981. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  4982. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  4983. // Figure out necessary qualifiers (C99 6.5.15p6)
  4984. QualType destPointee
  4985. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  4986. QualType destType = S.Context.getPointerType(destPointee);
  4987. // Add qualifiers if necessary.
  4988. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  4989. // Promote to void*.
  4990. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  4991. return destType;
  4992. }
  4993. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  4994. QualType destPointee
  4995. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  4996. QualType destType = S.Context.getPointerType(destPointee);
  4997. // Add qualifiers if necessary.
  4998. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  4999. // Promote to void*.
  5000. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5001. return destType;
  5002. }
  5003. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5004. }
  5005. /// \brief Return false if the first expression is not an integer and the second
  5006. /// expression is not a pointer, true otherwise.
  5007. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5008. Expr* PointerExpr, SourceLocation Loc,
  5009. bool IsIntFirstExpr) {
  5010. if (!PointerExpr->getType()->isPointerType() ||
  5011. !Int.get()->getType()->isIntegerType())
  5012. return false;
  5013. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5014. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5015. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5016. << Expr1->getType() << Expr2->getType()
  5017. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5018. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5019. CK_IntegralToPointer);
  5020. return true;
  5021. }
  5022. /// \brief Simple conversion between integer and floating point types.
  5023. ///
  5024. /// Used when handling the OpenCL conditional operator where the
  5025. /// condition is a vector while the other operands are scalar.
  5026. ///
  5027. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5028. /// types are either integer or floating type. Between the two
  5029. /// operands, the type with the higher rank is defined as the "result
  5030. /// type". The other operand needs to be promoted to the same type. No
  5031. /// other type promotion is allowed. We cannot use
  5032. /// UsualArithmeticConversions() for this purpose, since it always
  5033. /// promotes promotable types.
  5034. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5035. ExprResult &RHS,
  5036. SourceLocation QuestionLoc) {
  5037. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5038. if (LHS.isInvalid())
  5039. return QualType();
  5040. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5041. if (RHS.isInvalid())
  5042. return QualType();
  5043. // For conversion purposes, we ignore any qualifiers.
  5044. // For example, "const float" and "float" are equivalent.
  5045. QualType LHSType =
  5046. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5047. QualType RHSType =
  5048. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5049. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5050. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5051. << LHSType << LHS.get()->getSourceRange();
  5052. return QualType();
  5053. }
  5054. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5055. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5056. << RHSType << RHS.get()->getSourceRange();
  5057. return QualType();
  5058. }
  5059. // If both types are identical, no conversion is needed.
  5060. if (LHSType == RHSType)
  5061. return LHSType;
  5062. // Now handle "real" floating types (i.e. float, double, long double).
  5063. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5064. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5065. /*IsCompAssign = */ false);
  5066. // Finally, we have two differing integer types.
  5067. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5068. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5069. }
  5070. /// \brief Convert scalar operands to a vector that matches the
  5071. /// condition in length.
  5072. ///
  5073. /// Used when handling the OpenCL conditional operator where the
  5074. /// condition is a vector while the other operands are scalar.
  5075. ///
  5076. /// We first compute the "result type" for the scalar operands
  5077. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5078. /// into a vector of that type where the length matches the condition
  5079. /// vector type. s6.11.6 requires that the element types of the result
  5080. /// and the condition must have the same number of bits.
  5081. static QualType
  5082. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5083. QualType CondTy, SourceLocation QuestionLoc) {
  5084. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5085. if (ResTy.isNull()) return QualType();
  5086. const VectorType *CV = CondTy->getAs<VectorType>();
  5087. assert(CV);
  5088. // Determine the vector result type
  5089. unsigned NumElements = CV->getNumElements();
  5090. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5091. // Ensure that all types have the same number of bits
  5092. if (S.Context.getTypeSize(CV->getElementType())
  5093. != S.Context.getTypeSize(ResTy)) {
  5094. // Since VectorTy is created internally, it does not pretty print
  5095. // with an OpenCL name. Instead, we just print a description.
  5096. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5097. SmallString<64> Str;
  5098. llvm::raw_svector_ostream OS(Str);
  5099. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5100. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5101. << CondTy << OS.str();
  5102. return QualType();
  5103. }
  5104. // Convert operands to the vector result type
  5105. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5106. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5107. return VectorTy;
  5108. }
  5109. /// \brief Return false if this is a valid OpenCL condition vector
  5110. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5111. SourceLocation QuestionLoc) {
  5112. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5113. // integral type.
  5114. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5115. assert(CondTy);
  5116. QualType EleTy = CondTy->getElementType();
  5117. if (EleTy->isIntegerType()) return false;
  5118. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5119. << Cond->getType() << Cond->getSourceRange();
  5120. return true;
  5121. }
  5122. /// \brief Return false if the vector condition type and the vector
  5123. /// result type are compatible.
  5124. ///
  5125. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5126. /// number of elements, and their element types have the same number
  5127. /// of bits.
  5128. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5129. SourceLocation QuestionLoc) {
  5130. const VectorType *CV = CondTy->getAs<VectorType>();
  5131. const VectorType *RV = VecResTy->getAs<VectorType>();
  5132. assert(CV && RV);
  5133. if (CV->getNumElements() != RV->getNumElements()) {
  5134. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5135. << CondTy << VecResTy;
  5136. return true;
  5137. }
  5138. QualType CVE = CV->getElementType();
  5139. QualType RVE = RV->getElementType();
  5140. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5141. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5142. << CondTy << VecResTy;
  5143. return true;
  5144. }
  5145. return false;
  5146. }
  5147. /// \brief Return the resulting type for the conditional operator in
  5148. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5149. /// s6.3.i) when the condition is a vector type.
  5150. static QualType
  5151. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5152. ExprResult &LHS, ExprResult &RHS,
  5153. SourceLocation QuestionLoc) {
  5154. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5155. if (Cond.isInvalid())
  5156. return QualType();
  5157. QualType CondTy = Cond.get()->getType();
  5158. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5159. return QualType();
  5160. // If either operand is a vector then find the vector type of the
  5161. // result as specified in OpenCL v1.1 s6.3.i.
  5162. if (LHS.get()->getType()->isVectorType() ||
  5163. RHS.get()->getType()->isVectorType()) {
  5164. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5165. /*isCompAssign*/false);
  5166. if (VecResTy.isNull()) return QualType();
  5167. // The result type must match the condition type as specified in
  5168. // OpenCL v1.1 s6.11.6.
  5169. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5170. return QualType();
  5171. return VecResTy;
  5172. }
  5173. // Both operands are scalar.
  5174. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5175. }
  5176. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5177. /// In that case, LHS = cond.
  5178. /// C99 6.5.15
  5179. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5180. ExprResult &RHS, ExprValueKind &VK,
  5181. ExprObjectKind &OK,
  5182. SourceLocation QuestionLoc) {
  5183. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5184. if (!LHSResult.isUsable()) return QualType();
  5185. LHS = LHSResult;
  5186. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5187. if (!RHSResult.isUsable()) return QualType();
  5188. RHS = RHSResult;
  5189. // C++ is sufficiently different to merit its own checker.
  5190. if (getLangOpts().CPlusPlus)
  5191. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5192. VK = VK_RValue;
  5193. OK = OK_Ordinary;
  5194. // The OpenCL operator with a vector condition is sufficiently
  5195. // different to merit its own checker.
  5196. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5197. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5198. // First, check the condition.
  5199. Cond = UsualUnaryConversions(Cond.get());
  5200. if (Cond.isInvalid())
  5201. return QualType();
  5202. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5203. return QualType();
  5204. // Now check the two expressions.
  5205. if (LHS.get()->getType()->isVectorType() ||
  5206. RHS.get()->getType()->isVectorType())
  5207. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
  5208. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5209. if (LHS.isInvalid() || RHS.isInvalid())
  5210. return QualType();
  5211. QualType LHSTy = LHS.get()->getType();
  5212. QualType RHSTy = RHS.get()->getType();
  5213. // If both operands have arithmetic type, do the usual arithmetic conversions
  5214. // to find a common type: C99 6.5.15p3,5.
  5215. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5216. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5217. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5218. return ResTy;
  5219. }
  5220. // If both operands are the same structure or union type, the result is that
  5221. // type.
  5222. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5223. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5224. if (LHSRT->getDecl() == RHSRT->getDecl())
  5225. // "If both the operands have structure or union type, the result has
  5226. // that type." This implies that CV qualifiers are dropped.
  5227. return LHSTy.getUnqualifiedType();
  5228. // FIXME: Type of conditional expression must be complete in C mode.
  5229. }
  5230. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5231. // The following || allows only one side to be void (a GCC-ism).
  5232. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5233. return checkConditionalVoidType(*this, LHS, RHS);
  5234. }
  5235. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5236. // the type of the other operand."
  5237. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5238. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5239. // All objective-c pointer type analysis is done here.
  5240. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5241. QuestionLoc);
  5242. if (LHS.isInvalid() || RHS.isInvalid())
  5243. return QualType();
  5244. if (!compositeType.isNull())
  5245. return compositeType;
  5246. // Handle block pointer types.
  5247. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5248. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5249. QuestionLoc);
  5250. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5251. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5252. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5253. QuestionLoc);
  5254. // GCC compatibility: soften pointer/integer mismatch. Note that
  5255. // null pointers have been filtered out by this point.
  5256. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5257. /*isIntFirstExpr=*/true))
  5258. return RHSTy;
  5259. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5260. /*isIntFirstExpr=*/false))
  5261. return LHSTy;
  5262. // Emit a better diagnostic if one of the expressions is a null pointer
  5263. // constant and the other is not a pointer type. In this case, the user most
  5264. // likely forgot to take the address of the other expression.
  5265. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5266. return QualType();
  5267. // Otherwise, the operands are not compatible.
  5268. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5269. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5270. << RHS.get()->getSourceRange();
  5271. return QualType();
  5272. }
  5273. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5274. /// two objective-c pointer types of the two input expressions.
  5275. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5276. SourceLocation QuestionLoc) {
  5277. QualType LHSTy = LHS.get()->getType();
  5278. QualType RHSTy = RHS.get()->getType();
  5279. // Handle things like Class and struct objc_class*. Here we case the result
  5280. // to the pseudo-builtin, because that will be implicitly cast back to the
  5281. // redefinition type if an attempt is made to access its fields.
  5282. if (LHSTy->isObjCClassType() &&
  5283. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5284. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5285. return LHSTy;
  5286. }
  5287. if (RHSTy->isObjCClassType() &&
  5288. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5289. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5290. return RHSTy;
  5291. }
  5292. // And the same for struct objc_object* / id
  5293. if (LHSTy->isObjCIdType() &&
  5294. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5295. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5296. return LHSTy;
  5297. }
  5298. if (RHSTy->isObjCIdType() &&
  5299. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5300. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5301. return RHSTy;
  5302. }
  5303. // And the same for struct objc_selector* / SEL
  5304. if (Context.isObjCSelType(LHSTy) &&
  5305. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5306. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5307. return LHSTy;
  5308. }
  5309. if (Context.isObjCSelType(RHSTy) &&
  5310. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5311. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5312. return RHSTy;
  5313. }
  5314. // Check constraints for Objective-C object pointers types.
  5315. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5316. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5317. // Two identical object pointer types are always compatible.
  5318. return LHSTy;
  5319. }
  5320. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5321. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5322. QualType compositeType = LHSTy;
  5323. // If both operands are interfaces and either operand can be
  5324. // assigned to the other, use that type as the composite
  5325. // type. This allows
  5326. // xxx ? (A*) a : (B*) b
  5327. // where B is a subclass of A.
  5328. //
  5329. // Additionally, as for assignment, if either type is 'id'
  5330. // allow silent coercion. Finally, if the types are
  5331. // incompatible then make sure to use 'id' as the composite
  5332. // type so the result is acceptable for sending messages to.
  5333. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5334. // It could return the composite type.
  5335. if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5336. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5337. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5338. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5339. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5340. RHSTy->isObjCQualifiedIdType()) &&
  5341. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5342. // Need to handle "id<xx>" explicitly.
  5343. // GCC allows qualified id and any Objective-C type to devolve to
  5344. // id. Currently localizing to here until clear this should be
  5345. // part of ObjCQualifiedIdTypesAreCompatible.
  5346. compositeType = Context.getObjCIdType();
  5347. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5348. compositeType = Context.getObjCIdType();
  5349. } else if (!(compositeType =
  5350. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
  5351. ;
  5352. else {
  5353. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5354. << LHSTy << RHSTy
  5355. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5356. QualType incompatTy = Context.getObjCIdType();
  5357. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5358. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5359. return incompatTy;
  5360. }
  5361. // The object pointer types are compatible.
  5362. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5363. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5364. return compositeType;
  5365. }
  5366. // Check Objective-C object pointer types and 'void *'
  5367. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5368. if (getLangOpts().ObjCAutoRefCount) {
  5369. // ARC forbids the implicit conversion of object pointers to 'void *',
  5370. // so these types are not compatible.
  5371. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5372. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5373. LHS = RHS = true;
  5374. return QualType();
  5375. }
  5376. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5377. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5378. QualType destPointee
  5379. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5380. QualType destType = Context.getPointerType(destPointee);
  5381. // Add qualifiers if necessary.
  5382. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5383. // Promote to void*.
  5384. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5385. return destType;
  5386. }
  5387. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5388. if (getLangOpts().ObjCAutoRefCount) {
  5389. // ARC forbids the implicit conversion of object pointers to 'void *',
  5390. // so these types are not compatible.
  5391. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5392. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5393. LHS = RHS = true;
  5394. return QualType();
  5395. }
  5396. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5397. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5398. QualType destPointee
  5399. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5400. QualType destType = Context.getPointerType(destPointee);
  5401. // Add qualifiers if necessary.
  5402. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5403. // Promote to void*.
  5404. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5405. return destType;
  5406. }
  5407. return QualType();
  5408. }
  5409. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5410. /// ParenRange in parentheses.
  5411. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5412. const PartialDiagnostic &Note,
  5413. SourceRange ParenRange) {
  5414. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  5415. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5416. EndLoc.isValid()) {
  5417. Self.Diag(Loc, Note)
  5418. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5419. << FixItHint::CreateInsertion(EndLoc, ")");
  5420. } else {
  5421. // We can't display the parentheses, so just show the bare note.
  5422. Self.Diag(Loc, Note) << ParenRange;
  5423. }
  5424. }
  5425. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5426. return Opc >= BO_Mul && Opc <= BO_Shr;
  5427. }
  5428. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5429. /// expression, either using a built-in or overloaded operator,
  5430. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5431. /// expression.
  5432. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5433. Expr **RHSExprs) {
  5434. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5435. E = E->IgnoreImpCasts();
  5436. E = E->IgnoreConversionOperator();
  5437. E = E->IgnoreImpCasts();
  5438. // Built-in binary operator.
  5439. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5440. if (IsArithmeticOp(OP->getOpcode())) {
  5441. *Opcode = OP->getOpcode();
  5442. *RHSExprs = OP->getRHS();
  5443. return true;
  5444. }
  5445. }
  5446. // Overloaded operator.
  5447. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5448. if (Call->getNumArgs() != 2)
  5449. return false;
  5450. // Make sure this is really a binary operator that is safe to pass into
  5451. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5452. OverloadedOperatorKind OO = Call->getOperator();
  5453. if (OO < OO_Plus || OO > OO_Arrow ||
  5454. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5455. return false;
  5456. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5457. if (IsArithmeticOp(OpKind)) {
  5458. *Opcode = OpKind;
  5459. *RHSExprs = Call->getArg(1);
  5460. return true;
  5461. }
  5462. }
  5463. return false;
  5464. }
  5465. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5466. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5467. }
  5468. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5469. /// or is a logical expression such as (x==y) which has int type, but is
  5470. /// commonly interpreted as boolean.
  5471. static bool ExprLooksBoolean(Expr *E) {
  5472. E = E->IgnoreParenImpCasts();
  5473. if (E->getType()->isBooleanType())
  5474. return true;
  5475. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5476. return IsLogicOp(OP->getOpcode());
  5477. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5478. return OP->getOpcode() == UO_LNot;
  5479. if (E->getType()->isPointerType())
  5480. return true;
  5481. return false;
  5482. }
  5483. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5484. /// and binary operator are mixed in a way that suggests the programmer assumed
  5485. /// the conditional operator has higher precedence, for example:
  5486. /// "int x = a + someBinaryCondition ? 1 : 2".
  5487. static void DiagnoseConditionalPrecedence(Sema &Self,
  5488. SourceLocation OpLoc,
  5489. Expr *Condition,
  5490. Expr *LHSExpr,
  5491. Expr *RHSExpr) {
  5492. BinaryOperatorKind CondOpcode;
  5493. Expr *CondRHS;
  5494. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5495. return;
  5496. if (!ExprLooksBoolean(CondRHS))
  5497. return;
  5498. // The condition is an arithmetic binary expression, with a right-
  5499. // hand side that looks boolean, so warn.
  5500. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5501. << Condition->getSourceRange()
  5502. << BinaryOperator::getOpcodeStr(CondOpcode);
  5503. SuggestParentheses(Self, OpLoc,
  5504. Self.PDiag(diag::note_precedence_silence)
  5505. << BinaryOperator::getOpcodeStr(CondOpcode),
  5506. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5507. SuggestParentheses(Self, OpLoc,
  5508. Self.PDiag(diag::note_precedence_conditional_first),
  5509. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5510. }
  5511. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5512. /// in the case of a the GNU conditional expr extension.
  5513. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5514. SourceLocation ColonLoc,
  5515. Expr *CondExpr, Expr *LHSExpr,
  5516. Expr *RHSExpr) {
  5517. if (!getLangOpts().CPlusPlus) {
  5518. // C cannot handle TypoExpr nodes in the condition because it
  5519. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5520. // been dealt with before checking the operands.
  5521. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5522. if (!CondResult.isUsable()) return ExprError();
  5523. CondExpr = CondResult.get();
  5524. }
  5525. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5526. // was the condition.
  5527. OpaqueValueExpr *opaqueValue = nullptr;
  5528. Expr *commonExpr = nullptr;
  5529. if (!LHSExpr) {
  5530. commonExpr = CondExpr;
  5531. // Lower out placeholder types first. This is important so that we don't
  5532. // try to capture a placeholder. This happens in few cases in C++; such
  5533. // as Objective-C++'s dictionary subscripting syntax.
  5534. if (commonExpr->hasPlaceholderType()) {
  5535. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5536. if (!result.isUsable()) return ExprError();
  5537. commonExpr = result.get();
  5538. }
  5539. // We usually want to apply unary conversions *before* saving, except
  5540. // in the special case of a C++ l-value conditional.
  5541. if (!(getLangOpts().CPlusPlus
  5542. && !commonExpr->isTypeDependent()
  5543. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5544. && commonExpr->isGLValue()
  5545. && commonExpr->isOrdinaryOrBitFieldObject()
  5546. && RHSExpr->isOrdinaryOrBitFieldObject()
  5547. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5548. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5549. if (commonRes.isInvalid())
  5550. return ExprError();
  5551. commonExpr = commonRes.get();
  5552. }
  5553. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5554. commonExpr->getType(),
  5555. commonExpr->getValueKind(),
  5556. commonExpr->getObjectKind(),
  5557. commonExpr);
  5558. LHSExpr = CondExpr = opaqueValue;
  5559. }
  5560. ExprValueKind VK = VK_RValue;
  5561. ExprObjectKind OK = OK_Ordinary;
  5562. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5563. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5564. VK, OK, QuestionLoc);
  5565. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5566. RHS.isInvalid())
  5567. return ExprError();
  5568. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5569. RHS.get());
  5570. if (!commonExpr)
  5571. return new (Context)
  5572. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5573. RHS.get(), result, VK, OK);
  5574. return new (Context) BinaryConditionalOperator(
  5575. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5576. ColonLoc, result, VK, OK);
  5577. }
  5578. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5579. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5580. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5581. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5582. // FIXME: add a couple examples in this comment.
  5583. static Sema::AssignConvertType
  5584. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5585. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5586. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5587. // get the "pointed to" type (ignoring qualifiers at the top level)
  5588. const Type *lhptee, *rhptee;
  5589. Qualifiers lhq, rhq;
  5590. std::tie(lhptee, lhq) =
  5591. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5592. std::tie(rhptee, rhq) =
  5593. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5594. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5595. // C99 6.5.16.1p1: This following citation is common to constraints
  5596. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5597. // qualifiers of the type *pointed to* by the right;
  5598. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5599. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5600. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5601. // Ignore lifetime for further calculation.
  5602. lhq.removeObjCLifetime();
  5603. rhq.removeObjCLifetime();
  5604. }
  5605. if (!lhq.compatiblyIncludes(rhq)) {
  5606. // Treat address-space mismatches as fatal. TODO: address subspaces
  5607. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5608. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5609. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5610. // and from void*.
  5611. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5612. .compatiblyIncludes(
  5613. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5614. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5615. ; // keep old
  5616. // Treat lifetime mismatches as fatal.
  5617. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5618. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5619. // For GCC compatibility, other qualifier mismatches are treated
  5620. // as still compatible in C.
  5621. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5622. }
  5623. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5624. // incomplete type and the other is a pointer to a qualified or unqualified
  5625. // version of void...
  5626. if (lhptee->isVoidType()) {
  5627. if (rhptee->isIncompleteOrObjectType())
  5628. return ConvTy;
  5629. // As an extension, we allow cast to/from void* to function pointer.
  5630. assert(rhptee->isFunctionType());
  5631. return Sema::FunctionVoidPointer;
  5632. }
  5633. if (rhptee->isVoidType()) {
  5634. if (lhptee->isIncompleteOrObjectType())
  5635. return ConvTy;
  5636. // As an extension, we allow cast to/from void* to function pointer.
  5637. assert(lhptee->isFunctionType());
  5638. return Sema::FunctionVoidPointer;
  5639. }
  5640. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5641. // unqualified versions of compatible types, ...
  5642. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5643. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5644. // Check if the pointee types are compatible ignoring the sign.
  5645. // We explicitly check for char so that we catch "char" vs
  5646. // "unsigned char" on systems where "char" is unsigned.
  5647. if (lhptee->isCharType())
  5648. ltrans = S.Context.UnsignedCharTy;
  5649. else if (lhptee->hasSignedIntegerRepresentation())
  5650. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5651. if (rhptee->isCharType())
  5652. rtrans = S.Context.UnsignedCharTy;
  5653. else if (rhptee->hasSignedIntegerRepresentation())
  5654. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5655. if (ltrans == rtrans) {
  5656. // Types are compatible ignoring the sign. Qualifier incompatibility
  5657. // takes priority over sign incompatibility because the sign
  5658. // warning can be disabled.
  5659. if (ConvTy != Sema::Compatible)
  5660. return ConvTy;
  5661. return Sema::IncompatiblePointerSign;
  5662. }
  5663. // If we are a multi-level pointer, it's possible that our issue is simply
  5664. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5665. // the eventual target type is the same and the pointers have the same
  5666. // level of indirection, this must be the issue.
  5667. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5668. do {
  5669. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  5670. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  5671. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  5672. if (lhptee == rhptee)
  5673. return Sema::IncompatibleNestedPointerQualifiers;
  5674. }
  5675. // General pointer incompatibility takes priority over qualifiers.
  5676. return Sema::IncompatiblePointer;
  5677. }
  5678. if (!S.getLangOpts().CPlusPlus &&
  5679. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  5680. return Sema::IncompatiblePointer;
  5681. return ConvTy;
  5682. }
  5683. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  5684. /// block pointer types are compatible or whether a block and normal pointer
  5685. /// are compatible. It is more restrict than comparing two function pointer
  5686. // types.
  5687. static Sema::AssignConvertType
  5688. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  5689. QualType RHSType) {
  5690. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5691. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5692. QualType lhptee, rhptee;
  5693. // get the "pointed to" type (ignoring qualifiers at the top level)
  5694. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  5695. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  5696. // In C++, the types have to match exactly.
  5697. if (S.getLangOpts().CPlusPlus)
  5698. return Sema::IncompatibleBlockPointer;
  5699. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5700. // For blocks we enforce that qualifiers are identical.
  5701. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  5702. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5703. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  5704. return Sema::IncompatibleBlockPointer;
  5705. return ConvTy;
  5706. }
  5707. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  5708. /// for assignment compatibility.
  5709. static Sema::AssignConvertType
  5710. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  5711. QualType RHSType) {
  5712. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  5713. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  5714. if (LHSType->isObjCBuiltinType()) {
  5715. // Class is not compatible with ObjC object pointers.
  5716. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  5717. !RHSType->isObjCQualifiedClassType())
  5718. return Sema::IncompatiblePointer;
  5719. return Sema::Compatible;
  5720. }
  5721. if (RHSType->isObjCBuiltinType()) {
  5722. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  5723. !LHSType->isObjCQualifiedClassType())
  5724. return Sema::IncompatiblePointer;
  5725. return Sema::Compatible;
  5726. }
  5727. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5728. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5729. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  5730. // make an exception for id<P>
  5731. !LHSType->isObjCQualifiedIdType())
  5732. return Sema::CompatiblePointerDiscardsQualifiers;
  5733. if (S.Context.typesAreCompatible(LHSType, RHSType))
  5734. return Sema::Compatible;
  5735. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  5736. return Sema::IncompatibleObjCQualifiedId;
  5737. return Sema::IncompatiblePointer;
  5738. }
  5739. Sema::AssignConvertType
  5740. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  5741. QualType LHSType, QualType RHSType) {
  5742. // Fake up an opaque expression. We don't actually care about what
  5743. // cast operations are required, so if CheckAssignmentConstraints
  5744. // adds casts to this they'll be wasted, but fortunately that doesn't
  5745. // usually happen on valid code.
  5746. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  5747. ExprResult RHSPtr = &RHSExpr;
  5748. CastKind K = CK_Invalid;
  5749. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  5750. }
  5751. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  5752. /// has code to accommodate several GCC extensions when type checking
  5753. /// pointers. Here are some objectionable examples that GCC considers warnings:
  5754. ///
  5755. /// int a, *pint;
  5756. /// short *pshort;
  5757. /// struct foo *pfoo;
  5758. ///
  5759. /// pint = pshort; // warning: assignment from incompatible pointer type
  5760. /// a = pint; // warning: assignment makes integer from pointer without a cast
  5761. /// pint = a; // warning: assignment makes pointer from integer without a cast
  5762. /// pint = pfoo; // warning: assignment from incompatible pointer type
  5763. ///
  5764. /// As a result, the code for dealing with pointers is more complex than the
  5765. /// C99 spec dictates.
  5766. ///
  5767. /// Sets 'Kind' for any result kind except Incompatible.
  5768. Sema::AssignConvertType
  5769. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  5770. CastKind &Kind) {
  5771. QualType RHSType = RHS.get()->getType();
  5772. QualType OrigLHSType = LHSType;
  5773. // Get canonical types. We're not formatting these types, just comparing
  5774. // them.
  5775. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  5776. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  5777. // Common case: no conversion required.
  5778. if (LHSType == RHSType) {
  5779. Kind = CK_NoOp;
  5780. return Compatible;
  5781. }
  5782. // If we have an atomic type, try a non-atomic assignment, then just add an
  5783. // atomic qualification step.
  5784. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  5785. Sema::AssignConvertType result =
  5786. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  5787. if (result != Compatible)
  5788. return result;
  5789. if (Kind != CK_NoOp)
  5790. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  5791. Kind = CK_NonAtomicToAtomic;
  5792. return Compatible;
  5793. }
  5794. // If the left-hand side is a reference type, then we are in a
  5795. // (rare!) case where we've allowed the use of references in C,
  5796. // e.g., as a parameter type in a built-in function. In this case,
  5797. // just make sure that the type referenced is compatible with the
  5798. // right-hand side type. The caller is responsible for adjusting
  5799. // LHSType so that the resulting expression does not have reference
  5800. // type.
  5801. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  5802. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  5803. Kind = CK_LValueBitCast;
  5804. return Compatible;
  5805. }
  5806. return Incompatible;
  5807. }
  5808. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  5809. // to the same ExtVector type.
  5810. if (LHSType->isExtVectorType()) {
  5811. if (RHSType->isExtVectorType())
  5812. return Incompatible;
  5813. if (RHSType->isArithmeticType()) {
  5814. // CK_VectorSplat does T -> vector T, so first cast to the
  5815. // element type.
  5816. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  5817. if (elType != RHSType) {
  5818. Kind = PrepareScalarCast(RHS, elType);
  5819. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  5820. }
  5821. Kind = CK_VectorSplat;
  5822. return Compatible;
  5823. }
  5824. }
  5825. // Conversions to or from vector type.
  5826. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  5827. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  5828. // Allow assignments of an AltiVec vector type to an equivalent GCC
  5829. // vector type and vice versa
  5830. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  5831. Kind = CK_BitCast;
  5832. return Compatible;
  5833. }
  5834. // If we are allowing lax vector conversions, and LHS and RHS are both
  5835. // vectors, the total size only needs to be the same. This is a bitcast;
  5836. // no bits are changed but the result type is different.
  5837. if (isLaxVectorConversion(RHSType, LHSType)) {
  5838. Kind = CK_BitCast;
  5839. return IncompatibleVectors;
  5840. }
  5841. }
  5842. return Incompatible;
  5843. }
  5844. // Arithmetic conversions.
  5845. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  5846. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  5847. Kind = PrepareScalarCast(RHS, LHSType);
  5848. return Compatible;
  5849. }
  5850. // Conversions to normal pointers.
  5851. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  5852. // U* -> T*
  5853. if (isa<PointerType>(RHSType)) {
  5854. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  5855. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  5856. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  5857. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  5858. }
  5859. // int -> T*
  5860. if (RHSType->isIntegerType()) {
  5861. Kind = CK_IntegralToPointer; // FIXME: null?
  5862. return IntToPointer;
  5863. }
  5864. // C pointers are not compatible with ObjC object pointers,
  5865. // with two exceptions:
  5866. if (isa<ObjCObjectPointerType>(RHSType)) {
  5867. // - conversions to void*
  5868. if (LHSPointer->getPointeeType()->isVoidType()) {
  5869. Kind = CK_BitCast;
  5870. return Compatible;
  5871. }
  5872. // - conversions from 'Class' to the redefinition type
  5873. if (RHSType->isObjCClassType() &&
  5874. Context.hasSameType(LHSType,
  5875. Context.getObjCClassRedefinitionType())) {
  5876. Kind = CK_BitCast;
  5877. return Compatible;
  5878. }
  5879. Kind = CK_BitCast;
  5880. return IncompatiblePointer;
  5881. }
  5882. // U^ -> void*
  5883. if (RHSType->getAs<BlockPointerType>()) {
  5884. if (LHSPointer->getPointeeType()->isVoidType()) {
  5885. Kind = CK_BitCast;
  5886. return Compatible;
  5887. }
  5888. }
  5889. return Incompatible;
  5890. }
  5891. // Conversions to block pointers.
  5892. if (isa<BlockPointerType>(LHSType)) {
  5893. // U^ -> T^
  5894. if (RHSType->isBlockPointerType()) {
  5895. Kind = CK_BitCast;
  5896. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  5897. }
  5898. // int or null -> T^
  5899. if (RHSType->isIntegerType()) {
  5900. Kind = CK_IntegralToPointer; // FIXME: null
  5901. return IntToBlockPointer;
  5902. }
  5903. // id -> T^
  5904. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  5905. Kind = CK_AnyPointerToBlockPointerCast;
  5906. return Compatible;
  5907. }
  5908. // void* -> T^
  5909. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  5910. if (RHSPT->getPointeeType()->isVoidType()) {
  5911. Kind = CK_AnyPointerToBlockPointerCast;
  5912. return Compatible;
  5913. }
  5914. return Incompatible;
  5915. }
  5916. // Conversions to Objective-C pointers.
  5917. if (isa<ObjCObjectPointerType>(LHSType)) {
  5918. // A* -> B*
  5919. if (RHSType->isObjCObjectPointerType()) {
  5920. Kind = CK_BitCast;
  5921. Sema::AssignConvertType result =
  5922. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  5923. if (getLangOpts().ObjCAutoRefCount &&
  5924. result == Compatible &&
  5925. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  5926. result = IncompatibleObjCWeakRef;
  5927. return result;
  5928. }
  5929. // int or null -> A*
  5930. if (RHSType->isIntegerType()) {
  5931. Kind = CK_IntegralToPointer; // FIXME: null
  5932. return IntToPointer;
  5933. }
  5934. // In general, C pointers are not compatible with ObjC object pointers,
  5935. // with two exceptions:
  5936. if (isa<PointerType>(RHSType)) {
  5937. Kind = CK_CPointerToObjCPointerCast;
  5938. // - conversions from 'void*'
  5939. if (RHSType->isVoidPointerType()) {
  5940. return Compatible;
  5941. }
  5942. // - conversions to 'Class' from its redefinition type
  5943. if (LHSType->isObjCClassType() &&
  5944. Context.hasSameType(RHSType,
  5945. Context.getObjCClassRedefinitionType())) {
  5946. return Compatible;
  5947. }
  5948. return IncompatiblePointer;
  5949. }
  5950. // Only under strict condition T^ is compatible with an Objective-C pointer.
  5951. if (RHSType->isBlockPointerType() &&
  5952. isObjCPtrBlockCompatible(*this, Context, LHSType)) {
  5953. maybeExtendBlockObject(*this, RHS);
  5954. Kind = CK_BlockPointerToObjCPointerCast;
  5955. return Compatible;
  5956. }
  5957. return Incompatible;
  5958. }
  5959. // Conversions from pointers that are not covered by the above.
  5960. if (isa<PointerType>(RHSType)) {
  5961. // T* -> _Bool
  5962. if (LHSType == Context.BoolTy) {
  5963. Kind = CK_PointerToBoolean;
  5964. return Compatible;
  5965. }
  5966. // T* -> int
  5967. if (LHSType->isIntegerType()) {
  5968. Kind = CK_PointerToIntegral;
  5969. return PointerToInt;
  5970. }
  5971. return Incompatible;
  5972. }
  5973. // Conversions from Objective-C pointers that are not covered by the above.
  5974. if (isa<ObjCObjectPointerType>(RHSType)) {
  5975. // T* -> _Bool
  5976. if (LHSType == Context.BoolTy) {
  5977. Kind = CK_PointerToBoolean;
  5978. return Compatible;
  5979. }
  5980. // T* -> int
  5981. if (LHSType->isIntegerType()) {
  5982. Kind = CK_PointerToIntegral;
  5983. return PointerToInt;
  5984. }
  5985. return Incompatible;
  5986. }
  5987. // struct A -> struct B
  5988. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  5989. if (Context.typesAreCompatible(LHSType, RHSType)) {
  5990. Kind = CK_NoOp;
  5991. return Compatible;
  5992. }
  5993. }
  5994. return Incompatible;
  5995. }
  5996. /// \brief Constructs a transparent union from an expression that is
  5997. /// used to initialize the transparent union.
  5998. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  5999. ExprResult &EResult, QualType UnionType,
  6000. FieldDecl *Field) {
  6001. // Build an initializer list that designates the appropriate member
  6002. // of the transparent union.
  6003. Expr *E = EResult.get();
  6004. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6005. E, SourceLocation());
  6006. Initializer->setType(UnionType);
  6007. Initializer->setInitializedFieldInUnion(Field);
  6008. // Build a compound literal constructing a value of the transparent
  6009. // union type from this initializer list.
  6010. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6011. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6012. VK_RValue, Initializer, false);
  6013. }
  6014. Sema::AssignConvertType
  6015. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6016. ExprResult &RHS) {
  6017. QualType RHSType = RHS.get()->getType();
  6018. // If the ArgType is a Union type, we want to handle a potential
  6019. // transparent_union GCC extension.
  6020. const RecordType *UT = ArgType->getAsUnionType();
  6021. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6022. return Incompatible;
  6023. // The field to initialize within the transparent union.
  6024. RecordDecl *UD = UT->getDecl();
  6025. FieldDecl *InitField = nullptr;
  6026. // It's compatible if the expression matches any of the fields.
  6027. for (auto *it : UD->fields()) {
  6028. if (it->getType()->isPointerType()) {
  6029. // If the transparent union contains a pointer type, we allow:
  6030. // 1) void pointer
  6031. // 2) null pointer constant
  6032. if (RHSType->isPointerType())
  6033. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6034. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6035. InitField = it;
  6036. break;
  6037. }
  6038. if (RHS.get()->isNullPointerConstant(Context,
  6039. Expr::NPC_ValueDependentIsNull)) {
  6040. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6041. CK_NullToPointer);
  6042. InitField = it;
  6043. break;
  6044. }
  6045. }
  6046. CastKind Kind = CK_Invalid;
  6047. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6048. == Compatible) {
  6049. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6050. InitField = it;
  6051. break;
  6052. }
  6053. }
  6054. if (!InitField)
  6055. return Incompatible;
  6056. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6057. return Compatible;
  6058. }
  6059. Sema::AssignConvertType
  6060. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6061. bool Diagnose,
  6062. bool DiagnoseCFAudited) {
  6063. if (getLangOpts().CPlusPlus) {
  6064. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6065. // C++ 5.17p3: If the left operand is not of class type, the
  6066. // expression is implicitly converted (C++ 4) to the
  6067. // cv-unqualified type of the left operand.
  6068. ExprResult Res;
  6069. if (Diagnose) {
  6070. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6071. AA_Assigning);
  6072. } else {
  6073. ImplicitConversionSequence ICS =
  6074. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6075. /*SuppressUserConversions=*/false,
  6076. /*AllowExplicit=*/false,
  6077. /*InOverloadResolution=*/false,
  6078. /*CStyle=*/false,
  6079. /*AllowObjCWritebackConversion=*/false);
  6080. if (ICS.isFailure())
  6081. return Incompatible;
  6082. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6083. ICS, AA_Assigning);
  6084. }
  6085. if (Res.isInvalid())
  6086. return Incompatible;
  6087. Sema::AssignConvertType result = Compatible;
  6088. if (getLangOpts().ObjCAutoRefCount &&
  6089. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6090. RHS.get()->getType()))
  6091. result = IncompatibleObjCWeakRef;
  6092. RHS = Res;
  6093. return result;
  6094. }
  6095. // FIXME: Currently, we fall through and treat C++ classes like C
  6096. // structures.
  6097. // FIXME: We also fall through for atomics; not sure what should
  6098. // happen there, though.
  6099. }
  6100. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6101. // a null pointer constant.
  6102. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6103. LHSType->isBlockPointerType()) &&
  6104. RHS.get()->isNullPointerConstant(Context,
  6105. Expr::NPC_ValueDependentIsNull)) {
  6106. CastKind Kind;
  6107. CXXCastPath Path;
  6108. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6109. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6110. return Compatible;
  6111. }
  6112. // This check seems unnatural, however it is necessary to ensure the proper
  6113. // conversion of functions/arrays. If the conversion were done for all
  6114. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6115. // expressions that suppress this implicit conversion (&, sizeof).
  6116. //
  6117. // Suppress this for references: C++ 8.5.3p5.
  6118. if (!LHSType->isReferenceType()) {
  6119. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6120. if (RHS.isInvalid())
  6121. return Incompatible;
  6122. }
  6123. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6124. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6125. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6126. if (PDecl && !PDecl->hasDefinition()) {
  6127. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6128. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6129. }
  6130. }
  6131. CastKind Kind = CK_Invalid;
  6132. Sema::AssignConvertType result =
  6133. CheckAssignmentConstraints(LHSType, RHS, Kind);
  6134. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6135. // type of the assignment expression.
  6136. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6137. // so that we can use references in built-in functions even in C.
  6138. // The getNonReferenceType() call makes sure that the resulting expression
  6139. // does not have reference type.
  6140. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6141. QualType Ty = LHSType.getNonLValueExprType(Context);
  6142. Expr *E = RHS.get();
  6143. if (getLangOpts().ObjCAutoRefCount)
  6144. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6145. DiagnoseCFAudited);
  6146. if (getLangOpts().ObjC1 &&
  6147. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6148. LHSType, E->getType(), E) ||
  6149. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6150. RHS = E;
  6151. return Compatible;
  6152. }
  6153. RHS = ImpCastExprToType(E, Ty, Kind);
  6154. }
  6155. return result;
  6156. }
  6157. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6158. ExprResult &RHS) {
  6159. Diag(Loc, diag::err_typecheck_invalid_operands)
  6160. << LHS.get()->getType() << RHS.get()->getType()
  6161. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6162. return QualType();
  6163. }
  6164. /// Try to convert a value of non-vector type to a vector type by converting
  6165. /// the type to the element type of the vector and then performing a splat.
  6166. /// If the language is OpenCL, we only use conversions that promote scalar
  6167. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6168. /// for float->int.
  6169. ///
  6170. /// \param scalar - if non-null, actually perform the conversions
  6171. /// \return true if the operation fails (but without diagnosing the failure)
  6172. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6173. QualType scalarTy,
  6174. QualType vectorEltTy,
  6175. QualType vectorTy) {
  6176. // The conversion to apply to the scalar before splatting it,
  6177. // if necessary.
  6178. CastKind scalarCast = CK_Invalid;
  6179. if (vectorEltTy->isIntegralType(S.Context)) {
  6180. if (!scalarTy->isIntegralType(S.Context))
  6181. return true;
  6182. if (S.getLangOpts().OpenCL &&
  6183. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6184. return true;
  6185. scalarCast = CK_IntegralCast;
  6186. } else if (vectorEltTy->isRealFloatingType()) {
  6187. if (scalarTy->isRealFloatingType()) {
  6188. if (S.getLangOpts().OpenCL &&
  6189. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6190. return true;
  6191. scalarCast = CK_FloatingCast;
  6192. }
  6193. else if (scalarTy->isIntegralType(S.Context))
  6194. scalarCast = CK_IntegralToFloating;
  6195. else
  6196. return true;
  6197. } else {
  6198. return true;
  6199. }
  6200. // Adjust scalar if desired.
  6201. if (scalar) {
  6202. if (scalarCast != CK_Invalid)
  6203. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6204. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6205. }
  6206. return false;
  6207. }
  6208. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6209. SourceLocation Loc, bool IsCompAssign) {
  6210. if (!IsCompAssign) {
  6211. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6212. if (LHS.isInvalid())
  6213. return QualType();
  6214. }
  6215. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6216. if (RHS.isInvalid())
  6217. return QualType();
  6218. // For conversion purposes, we ignore any qualifiers.
  6219. // For example, "const float" and "float" are equivalent.
  6220. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6221. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6222. // If the vector types are identical, return.
  6223. if (Context.hasSameType(LHSType, RHSType))
  6224. return LHSType;
  6225. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6226. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6227. assert(LHSVecType || RHSVecType);
  6228. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6229. if (LHSVecType && RHSVecType &&
  6230. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6231. if (isa<ExtVectorType>(LHSVecType)) {
  6232. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6233. return LHSType;
  6234. }
  6235. if (!IsCompAssign)
  6236. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6237. return RHSType;
  6238. }
  6239. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6240. // the vector element type and splat.
  6241. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6242. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6243. LHSVecType->getElementType(), LHSType))
  6244. return LHSType;
  6245. }
  6246. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6247. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6248. LHSType, RHSVecType->getElementType(),
  6249. RHSType))
  6250. return RHSType;
  6251. }
  6252. // If we're allowing lax vector conversions, only the total (data) size
  6253. // needs to be the same.
  6254. // FIXME: Should we really be allowing this?
  6255. // FIXME: We really just pick the LHS type arbitrarily?
  6256. if (isLaxVectorConversion(RHSType, LHSType)) {
  6257. QualType resultType = LHSType;
  6258. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6259. return resultType;
  6260. }
  6261. // Okay, the expression is invalid.
  6262. // If there's a non-vector, non-real operand, diagnose that.
  6263. if ((!RHSVecType && !RHSType->isRealType()) ||
  6264. (!LHSVecType && !LHSType->isRealType())) {
  6265. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6266. << LHSType << RHSType
  6267. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6268. return QualType();
  6269. }
  6270. // Otherwise, use the generic diagnostic.
  6271. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6272. << LHSType << RHSType
  6273. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6274. return QualType();
  6275. }
  6276. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6277. // expression. These are mainly cases where the null pointer is used as an
  6278. // integer instead of a pointer.
  6279. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6280. SourceLocation Loc, bool IsCompare) {
  6281. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6282. // but we use a bit of a hack here for speed; this is a relatively
  6283. // hot path, and isNullPointerConstant is slow.
  6284. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6285. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6286. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6287. // Avoid analyzing cases where the result will either be invalid (and
  6288. // diagnosed as such) or entirely valid and not something to warn about.
  6289. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6290. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6291. return;
  6292. // Comparison operations would not make sense with a null pointer no matter
  6293. // what the other expression is.
  6294. if (!IsCompare) {
  6295. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6296. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6297. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6298. return;
  6299. }
  6300. // The rest of the operations only make sense with a null pointer
  6301. // if the other expression is a pointer.
  6302. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6303. NonNullType->canDecayToPointerType())
  6304. return;
  6305. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6306. << LHSNull /* LHS is NULL */ << NonNullType
  6307. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6308. }
  6309. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6310. SourceLocation Loc,
  6311. bool IsCompAssign, bool IsDiv) {
  6312. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6313. if (LHS.get()->getType()->isVectorType() ||
  6314. RHS.get()->getType()->isVectorType())
  6315. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  6316. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6317. if (LHS.isInvalid() || RHS.isInvalid())
  6318. return QualType();
  6319. if (compType.isNull() || !compType->isArithmeticType())
  6320. return InvalidOperands(Loc, LHS, RHS);
  6321. // Check for division by zero.
  6322. llvm::APSInt RHSValue;
  6323. if (IsDiv && !RHS.get()->isValueDependent() &&
  6324. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6325. DiagRuntimeBehavior(Loc, RHS.get(),
  6326. PDiag(diag::warn_division_by_zero)
  6327. << RHS.get()->getSourceRange());
  6328. return compType;
  6329. }
  6330. QualType Sema::CheckRemainderOperands(
  6331. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6332. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6333. if (LHS.get()->getType()->isVectorType() ||
  6334. RHS.get()->getType()->isVectorType()) {
  6335. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6336. RHS.get()->getType()->hasIntegerRepresentation())
  6337. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  6338. return InvalidOperands(Loc, LHS, RHS);
  6339. }
  6340. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6341. if (LHS.isInvalid() || RHS.isInvalid())
  6342. return QualType();
  6343. if (compType.isNull() || !compType->isIntegerType())
  6344. return InvalidOperands(Loc, LHS, RHS);
  6345. // Check for remainder by zero.
  6346. llvm::APSInt RHSValue;
  6347. if (!RHS.get()->isValueDependent() &&
  6348. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6349. DiagRuntimeBehavior(Loc, RHS.get(),
  6350. PDiag(diag::warn_remainder_by_zero)
  6351. << RHS.get()->getSourceRange());
  6352. return compType;
  6353. }
  6354. /// \brief Diagnose invalid arithmetic on two void pointers.
  6355. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6356. Expr *LHSExpr, Expr *RHSExpr) {
  6357. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6358. ? diag::err_typecheck_pointer_arith_void_type
  6359. : diag::ext_gnu_void_ptr)
  6360. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6361. << RHSExpr->getSourceRange();
  6362. }
  6363. /// \brief Diagnose invalid arithmetic on a void pointer.
  6364. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6365. Expr *Pointer) {
  6366. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6367. ? diag::err_typecheck_pointer_arith_void_type
  6368. : diag::ext_gnu_void_ptr)
  6369. << 0 /* one pointer */ << Pointer->getSourceRange();
  6370. }
  6371. /// \brief Diagnose invalid arithmetic on two function pointers.
  6372. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6373. Expr *LHS, Expr *RHS) {
  6374. assert(LHS->getType()->isAnyPointerType());
  6375. assert(RHS->getType()->isAnyPointerType());
  6376. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6377. ? diag::err_typecheck_pointer_arith_function_type
  6378. : diag::ext_gnu_ptr_func_arith)
  6379. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6380. // We only show the second type if it differs from the first.
  6381. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6382. RHS->getType())
  6383. << RHS->getType()->getPointeeType()
  6384. << LHS->getSourceRange() << RHS->getSourceRange();
  6385. }
  6386. /// \brief Diagnose invalid arithmetic on a function pointer.
  6387. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6388. Expr *Pointer) {
  6389. assert(Pointer->getType()->isAnyPointerType());
  6390. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6391. ? diag::err_typecheck_pointer_arith_function_type
  6392. : diag::ext_gnu_ptr_func_arith)
  6393. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6394. << 0 /* one pointer, so only one type */
  6395. << Pointer->getSourceRange();
  6396. }
  6397. /// \brief Emit error if Operand is incomplete pointer type
  6398. ///
  6399. /// \returns True if pointer has incomplete type
  6400. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6401. Expr *Operand) {
  6402. QualType ResType = Operand->getType();
  6403. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6404. ResType = ResAtomicType->getValueType();
  6405. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6406. QualType PointeeTy = ResType->getPointeeType();
  6407. return S.RequireCompleteType(Loc, PointeeTy,
  6408. diag::err_typecheck_arithmetic_incomplete_type,
  6409. PointeeTy, Operand->getSourceRange());
  6410. }
  6411. /// \brief Check the validity of an arithmetic pointer operand.
  6412. ///
  6413. /// If the operand has pointer type, this code will check for pointer types
  6414. /// which are invalid in arithmetic operations. These will be diagnosed
  6415. /// appropriately, including whether or not the use is supported as an
  6416. /// extension.
  6417. ///
  6418. /// \returns True when the operand is valid to use (even if as an extension).
  6419. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6420. Expr *Operand) {
  6421. QualType ResType = Operand->getType();
  6422. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6423. ResType = ResAtomicType->getValueType();
  6424. if (!ResType->isAnyPointerType()) return true;
  6425. QualType PointeeTy = ResType->getPointeeType();
  6426. if (PointeeTy->isVoidType()) {
  6427. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6428. return !S.getLangOpts().CPlusPlus;
  6429. }
  6430. if (PointeeTy->isFunctionType()) {
  6431. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6432. return !S.getLangOpts().CPlusPlus;
  6433. }
  6434. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6435. return true;
  6436. }
  6437. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6438. /// operands.
  6439. ///
  6440. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6441. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6442. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6443. /// are (potentially problematic) pointers.
  6444. ///
  6445. /// \returns True when the operand is valid to use (even if as an extension).
  6446. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6447. Expr *LHSExpr, Expr *RHSExpr) {
  6448. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6449. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6450. if (!isLHSPointer && !isRHSPointer) return true;
  6451. QualType LHSPointeeTy, RHSPointeeTy;
  6452. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6453. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6454. // if both are pointers check if operation is valid wrt address spaces
  6455. if (isLHSPointer && isRHSPointer) {
  6456. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6457. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6458. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6459. S.Diag(Loc,
  6460. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6461. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6462. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6463. return false;
  6464. }
  6465. }
  6466. // Check for arithmetic on pointers to incomplete types.
  6467. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6468. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6469. if (isLHSVoidPtr || isRHSVoidPtr) {
  6470. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6471. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6472. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6473. return !S.getLangOpts().CPlusPlus;
  6474. }
  6475. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6476. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6477. if (isLHSFuncPtr || isRHSFuncPtr) {
  6478. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6479. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6480. RHSExpr);
  6481. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6482. return !S.getLangOpts().CPlusPlus;
  6483. }
  6484. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6485. return false;
  6486. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6487. return false;
  6488. return true;
  6489. }
  6490. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6491. /// literal.
  6492. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6493. Expr *LHSExpr, Expr *RHSExpr) {
  6494. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6495. Expr* IndexExpr = RHSExpr;
  6496. if (!StrExpr) {
  6497. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6498. IndexExpr = LHSExpr;
  6499. }
  6500. bool IsStringPlusInt = StrExpr &&
  6501. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6502. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6503. return;
  6504. llvm::APSInt index;
  6505. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6506. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6507. if (index.isNonNegative() &&
  6508. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6509. index.isUnsigned()))
  6510. return;
  6511. }
  6512. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6513. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6514. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6515. // Only print a fixit for "str" + int, not for int + "str".
  6516. if (IndexExpr == RHSExpr) {
  6517. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6518. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6519. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6520. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6521. << FixItHint::CreateInsertion(EndLoc, "]");
  6522. } else
  6523. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6524. }
  6525. /// \brief Emit a warning when adding a char literal to a string.
  6526. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6527. Expr *LHSExpr, Expr *RHSExpr) {
  6528. const Expr *StringRefExpr = LHSExpr;
  6529. const CharacterLiteral *CharExpr =
  6530. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6531. if (!CharExpr) {
  6532. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6533. StringRefExpr = RHSExpr;
  6534. }
  6535. if (!CharExpr || !StringRefExpr)
  6536. return;
  6537. const QualType StringType = StringRefExpr->getType();
  6538. // Return if not a PointerType.
  6539. if (!StringType->isAnyPointerType())
  6540. return;
  6541. // Return if not a CharacterType.
  6542. if (!StringType->getPointeeType()->isAnyCharacterType())
  6543. return;
  6544. ASTContext &Ctx = Self.getASTContext();
  6545. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6546. const QualType CharType = CharExpr->getType();
  6547. if (!CharType->isAnyCharacterType() &&
  6548. CharType->isIntegerType() &&
  6549. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6550. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6551. << DiagRange << Ctx.CharTy;
  6552. } else {
  6553. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6554. << DiagRange << CharExpr->getType();
  6555. }
  6556. // Only print a fixit for str + char, not for char + str.
  6557. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6558. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6559. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6560. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6561. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6562. << FixItHint::CreateInsertion(EndLoc, "]");
  6563. } else {
  6564. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6565. }
  6566. }
  6567. /// \brief Emit error when two pointers are incompatible.
  6568. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6569. Expr *LHSExpr, Expr *RHSExpr) {
  6570. assert(LHSExpr->getType()->isAnyPointerType());
  6571. assert(RHSExpr->getType()->isAnyPointerType());
  6572. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6573. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6574. << RHSExpr->getSourceRange();
  6575. }
  6576. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  6577. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  6578. QualType* CompLHSTy) {
  6579. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6580. if (LHS.get()->getType()->isVectorType() ||
  6581. RHS.get()->getType()->isVectorType()) {
  6582. QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
  6583. if (CompLHSTy) *CompLHSTy = compType;
  6584. return compType;
  6585. }
  6586. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6587. if (LHS.isInvalid() || RHS.isInvalid())
  6588. return QualType();
  6589. // Diagnose "string literal" '+' int and string '+' "char literal".
  6590. if (Opc == BO_Add) {
  6591. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6592. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6593. }
  6594. // handle the common case first (both operands are arithmetic).
  6595. if (!compType.isNull() && compType->isArithmeticType()) {
  6596. if (CompLHSTy) *CompLHSTy = compType;
  6597. return compType;
  6598. }
  6599. // Type-checking. Ultimately the pointer's going to be in PExp;
  6600. // note that we bias towards the LHS being the pointer.
  6601. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6602. bool isObjCPointer;
  6603. if (PExp->getType()->isPointerType()) {
  6604. isObjCPointer = false;
  6605. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6606. isObjCPointer = true;
  6607. } else {
  6608. std::swap(PExp, IExp);
  6609. if (PExp->getType()->isPointerType()) {
  6610. isObjCPointer = false;
  6611. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6612. isObjCPointer = true;
  6613. } else {
  6614. return InvalidOperands(Loc, LHS, RHS);
  6615. }
  6616. }
  6617. assert(PExp->getType()->isAnyPointerType());
  6618. if (!IExp->getType()->isIntegerType())
  6619. return InvalidOperands(Loc, LHS, RHS);
  6620. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6621. return QualType();
  6622. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6623. return QualType();
  6624. // Check array bounds for pointer arithemtic
  6625. CheckArrayAccess(PExp, IExp);
  6626. if (CompLHSTy) {
  6627. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  6628. if (LHSTy.isNull()) {
  6629. LHSTy = LHS.get()->getType();
  6630. if (LHSTy->isPromotableIntegerType())
  6631. LHSTy = Context.getPromotedIntegerType(LHSTy);
  6632. }
  6633. *CompLHSTy = LHSTy;
  6634. }
  6635. return PExp->getType();
  6636. }
  6637. // C99 6.5.6
  6638. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  6639. SourceLocation Loc,
  6640. QualType* CompLHSTy) {
  6641. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6642. if (LHS.get()->getType()->isVectorType() ||
  6643. RHS.get()->getType()->isVectorType()) {
  6644. QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
  6645. if (CompLHSTy) *CompLHSTy = compType;
  6646. return compType;
  6647. }
  6648. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6649. if (LHS.isInvalid() || RHS.isInvalid())
  6650. return QualType();
  6651. // Enforce type constraints: C99 6.5.6p3.
  6652. // Handle the common case first (both operands are arithmetic).
  6653. if (!compType.isNull() && compType->isArithmeticType()) {
  6654. if (CompLHSTy) *CompLHSTy = compType;
  6655. return compType;
  6656. }
  6657. // Either ptr - int or ptr - ptr.
  6658. if (LHS.get()->getType()->isAnyPointerType()) {
  6659. QualType lpointee = LHS.get()->getType()->getPointeeType();
  6660. // Diagnose bad cases where we step over interface counts.
  6661. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  6662. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  6663. return QualType();
  6664. // The result type of a pointer-int computation is the pointer type.
  6665. if (RHS.get()->getType()->isIntegerType()) {
  6666. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  6667. return QualType();
  6668. // Check array bounds for pointer arithemtic
  6669. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  6670. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  6671. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  6672. return LHS.get()->getType();
  6673. }
  6674. // Handle pointer-pointer subtractions.
  6675. if (const PointerType *RHSPTy
  6676. = RHS.get()->getType()->getAs<PointerType>()) {
  6677. QualType rpointee = RHSPTy->getPointeeType();
  6678. if (getLangOpts().CPlusPlus) {
  6679. // Pointee types must be the same: C++ [expr.add]
  6680. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  6681. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6682. }
  6683. } else {
  6684. // Pointee types must be compatible C99 6.5.6p3
  6685. if (!Context.typesAreCompatible(
  6686. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  6687. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  6688. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6689. return QualType();
  6690. }
  6691. }
  6692. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  6693. LHS.get(), RHS.get()))
  6694. return QualType();
  6695. // The pointee type may have zero size. As an extension, a structure or
  6696. // union may have zero size or an array may have zero length. In this
  6697. // case subtraction does not make sense.
  6698. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  6699. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  6700. if (ElementSize.isZero()) {
  6701. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  6702. << rpointee.getUnqualifiedType()
  6703. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6704. }
  6705. }
  6706. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  6707. return Context.getPointerDiffType();
  6708. }
  6709. }
  6710. return InvalidOperands(Loc, LHS, RHS);
  6711. }
  6712. static bool isScopedEnumerationType(QualType T) {
  6713. if (const EnumType *ET = T->getAs<EnumType>())
  6714. return ET->getDecl()->isScoped();
  6715. return false;
  6716. }
  6717. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  6718. SourceLocation Loc, unsigned Opc,
  6719. QualType LHSType) {
  6720. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  6721. // so skip remaining warnings as we don't want to modify values within Sema.
  6722. if (S.getLangOpts().OpenCL)
  6723. return;
  6724. llvm::APSInt Right;
  6725. // Check right/shifter operand
  6726. if (RHS.get()->isValueDependent() ||
  6727. !RHS.get()->isIntegerConstantExpr(Right, S.Context))
  6728. return;
  6729. if (Right.isNegative()) {
  6730. S.DiagRuntimeBehavior(Loc, RHS.get(),
  6731. S.PDiag(diag::warn_shift_negative)
  6732. << RHS.get()->getSourceRange());
  6733. return;
  6734. }
  6735. llvm::APInt LeftBits(Right.getBitWidth(),
  6736. S.Context.getTypeSize(LHS.get()->getType()));
  6737. if (Right.uge(LeftBits)) {
  6738. S.DiagRuntimeBehavior(Loc, RHS.get(),
  6739. S.PDiag(diag::warn_shift_gt_typewidth)
  6740. << RHS.get()->getSourceRange());
  6741. return;
  6742. }
  6743. if (Opc != BO_Shl)
  6744. return;
  6745. // When left shifting an ICE which is signed, we can check for overflow which
  6746. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  6747. // integers have defined behavior modulo one more than the maximum value
  6748. // representable in the result type, so never warn for those.
  6749. llvm::APSInt Left;
  6750. if (LHS.get()->isValueDependent() ||
  6751. !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
  6752. LHSType->hasUnsignedIntegerRepresentation())
  6753. return;
  6754. llvm::APInt ResultBits =
  6755. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  6756. if (LeftBits.uge(ResultBits))
  6757. return;
  6758. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  6759. Result = Result.shl(Right);
  6760. // Print the bit representation of the signed integer as an unsigned
  6761. // hexadecimal number.
  6762. SmallString<40> HexResult;
  6763. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  6764. // If we are only missing a sign bit, this is less likely to result in actual
  6765. // bugs -- if the result is cast back to an unsigned type, it will have the
  6766. // expected value. Thus we place this behind a different warning that can be
  6767. // turned off separately if needed.
  6768. if (LeftBits == ResultBits - 1) {
  6769. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  6770. << HexResult.str() << LHSType
  6771. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6772. return;
  6773. }
  6774. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  6775. << HexResult.str() << Result.getMinSignedBits() << LHSType
  6776. << Left.getBitWidth() << LHS.get()->getSourceRange()
  6777. << RHS.get()->getSourceRange();
  6778. }
  6779. /// \brief Return the resulting type when an OpenCL vector is shifted
  6780. /// by a scalar or vector shift amount.
  6781. static QualType checkOpenCLVectorShift(Sema &S,
  6782. ExprResult &LHS, ExprResult &RHS,
  6783. SourceLocation Loc, bool IsCompAssign) {
  6784. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  6785. if (!LHS.get()->getType()->isVectorType()) {
  6786. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  6787. << RHS.get()->getType() << LHS.get()->getType()
  6788. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6789. return QualType();
  6790. }
  6791. if (!IsCompAssign) {
  6792. LHS = S.UsualUnaryConversions(LHS.get());
  6793. if (LHS.isInvalid()) return QualType();
  6794. }
  6795. RHS = S.UsualUnaryConversions(RHS.get());
  6796. if (RHS.isInvalid()) return QualType();
  6797. QualType LHSType = LHS.get()->getType();
  6798. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  6799. QualType LHSEleType = LHSVecTy->getElementType();
  6800. // Note that RHS might not be a vector.
  6801. QualType RHSType = RHS.get()->getType();
  6802. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  6803. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  6804. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  6805. if (!LHSEleType->isIntegerType()) {
  6806. S.Diag(Loc, diag::err_typecheck_expect_int)
  6807. << LHS.get()->getType() << LHS.get()->getSourceRange();
  6808. return QualType();
  6809. }
  6810. if (!RHSEleType->isIntegerType()) {
  6811. S.Diag(Loc, diag::err_typecheck_expect_int)
  6812. << RHS.get()->getType() << RHS.get()->getSourceRange();
  6813. return QualType();
  6814. }
  6815. if (RHSVecTy) {
  6816. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  6817. // are applied component-wise. So if RHS is a vector, then ensure
  6818. // that the number of elements is the same as LHS...
  6819. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  6820. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  6821. << LHS.get()->getType() << RHS.get()->getType()
  6822. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6823. return QualType();
  6824. }
  6825. } else {
  6826. // ...else expand RHS to match the number of elements in LHS.
  6827. QualType VecTy =
  6828. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  6829. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  6830. }
  6831. return LHSType;
  6832. }
  6833. // C99 6.5.7
  6834. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  6835. SourceLocation Loc, unsigned Opc,
  6836. bool IsCompAssign) {
  6837. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6838. // Vector shifts promote their scalar inputs to vector type.
  6839. if (LHS.get()->getType()->isVectorType() ||
  6840. RHS.get()->getType()->isVectorType()) {
  6841. if (LangOpts.OpenCL)
  6842. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  6843. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  6844. }
  6845. // Shifts don't perform usual arithmetic conversions, they just do integer
  6846. // promotions on each operand. C99 6.5.7p3
  6847. // For the LHS, do usual unary conversions, but then reset them away
  6848. // if this is a compound assignment.
  6849. ExprResult OldLHS = LHS;
  6850. LHS = UsualUnaryConversions(LHS.get());
  6851. if (LHS.isInvalid())
  6852. return QualType();
  6853. QualType LHSType = LHS.get()->getType();
  6854. if (IsCompAssign) LHS = OldLHS;
  6855. // The RHS is simpler.
  6856. RHS = UsualUnaryConversions(RHS.get());
  6857. if (RHS.isInvalid())
  6858. return QualType();
  6859. QualType RHSType = RHS.get()->getType();
  6860. // C99 6.5.7p2: Each of the operands shall have integer type.
  6861. if (!LHSType->hasIntegerRepresentation() ||
  6862. !RHSType->hasIntegerRepresentation())
  6863. return InvalidOperands(Loc, LHS, RHS);
  6864. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  6865. // hasIntegerRepresentation() above instead of this.
  6866. if (isScopedEnumerationType(LHSType) ||
  6867. isScopedEnumerationType(RHSType)) {
  6868. return InvalidOperands(Loc, LHS, RHS);
  6869. }
  6870. // Sanity-check shift operands
  6871. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  6872. // "The type of the result is that of the promoted left operand."
  6873. return LHSType;
  6874. }
  6875. static bool IsWithinTemplateSpecialization(Decl *D) {
  6876. if (DeclContext *DC = D->getDeclContext()) {
  6877. if (isa<ClassTemplateSpecializationDecl>(DC))
  6878. return true;
  6879. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  6880. return FD->isFunctionTemplateSpecialization();
  6881. }
  6882. return false;
  6883. }
  6884. /// If two different enums are compared, raise a warning.
  6885. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  6886. Expr *RHS) {
  6887. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  6888. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  6889. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  6890. if (!LHSEnumType)
  6891. return;
  6892. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  6893. if (!RHSEnumType)
  6894. return;
  6895. // Ignore anonymous enums.
  6896. if (!LHSEnumType->getDecl()->getIdentifier())
  6897. return;
  6898. if (!RHSEnumType->getDecl()->getIdentifier())
  6899. return;
  6900. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  6901. return;
  6902. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  6903. << LHSStrippedType << RHSStrippedType
  6904. << LHS->getSourceRange() << RHS->getSourceRange();
  6905. }
  6906. /// \brief Diagnose bad pointer comparisons.
  6907. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  6908. ExprResult &LHS, ExprResult &RHS,
  6909. bool IsError) {
  6910. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  6911. : diag::ext_typecheck_comparison_of_distinct_pointers)
  6912. << LHS.get()->getType() << RHS.get()->getType()
  6913. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6914. }
  6915. /// \brief Returns false if the pointers are converted to a composite type,
  6916. /// true otherwise.
  6917. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  6918. ExprResult &LHS, ExprResult &RHS) {
  6919. // C++ [expr.rel]p2:
  6920. // [...] Pointer conversions (4.10) and qualification
  6921. // conversions (4.4) are performed on pointer operands (or on
  6922. // a pointer operand and a null pointer constant) to bring
  6923. // them to their composite pointer type. [...]
  6924. //
  6925. // C++ [expr.eq]p1 uses the same notion for (in)equality
  6926. // comparisons of pointers.
  6927. // C++ [expr.eq]p2:
  6928. // In addition, pointers to members can be compared, or a pointer to
  6929. // member and a null pointer constant. Pointer to member conversions
  6930. // (4.11) and qualification conversions (4.4) are performed to bring
  6931. // them to a common type. If one operand is a null pointer constant,
  6932. // the common type is the type of the other operand. Otherwise, the
  6933. // common type is a pointer to member type similar (4.4) to the type
  6934. // of one of the operands, with a cv-qualification signature (4.4)
  6935. // that is the union of the cv-qualification signatures of the operand
  6936. // types.
  6937. QualType LHSType = LHS.get()->getType();
  6938. QualType RHSType = RHS.get()->getType();
  6939. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  6940. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  6941. bool NonStandardCompositeType = false;
  6942. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  6943. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  6944. if (T.isNull()) {
  6945. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  6946. return true;
  6947. }
  6948. if (NonStandardCompositeType)
  6949. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  6950. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  6951. << RHS.get()->getSourceRange();
  6952. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  6953. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  6954. return false;
  6955. }
  6956. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  6957. ExprResult &LHS,
  6958. ExprResult &RHS,
  6959. bool IsError) {
  6960. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  6961. : diag::ext_typecheck_comparison_of_fptr_to_void)
  6962. << LHS.get()->getType() << RHS.get()->getType()
  6963. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6964. }
  6965. static bool isObjCObjectLiteral(ExprResult &E) {
  6966. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  6967. case Stmt::ObjCArrayLiteralClass:
  6968. case Stmt::ObjCDictionaryLiteralClass:
  6969. case Stmt::ObjCStringLiteralClass:
  6970. case Stmt::ObjCBoxedExprClass:
  6971. return true;
  6972. default:
  6973. // Note that ObjCBoolLiteral is NOT an object literal!
  6974. return false;
  6975. }
  6976. }
  6977. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  6978. const ObjCObjectPointerType *Type =
  6979. LHS->getType()->getAs<ObjCObjectPointerType>();
  6980. // If this is not actually an Objective-C object, bail out.
  6981. if (!Type)
  6982. return false;
  6983. // Get the LHS object's interface type.
  6984. QualType InterfaceType = Type->getPointeeType();
  6985. if (const ObjCObjectType *iQFaceTy =
  6986. InterfaceType->getAsObjCQualifiedInterfaceType())
  6987. InterfaceType = iQFaceTy->getBaseType();
  6988. // If the RHS isn't an Objective-C object, bail out.
  6989. if (!RHS->getType()->isObjCObjectPointerType())
  6990. return false;
  6991. // Try to find the -isEqual: method.
  6992. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  6993. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  6994. InterfaceType,
  6995. /*instance=*/true);
  6996. if (!Method) {
  6997. if (Type->isObjCIdType()) {
  6998. // For 'id', just check the global pool.
  6999. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7000. /*receiverId=*/true,
  7001. /*warn=*/false);
  7002. } else {
  7003. // Check protocols.
  7004. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7005. /*instance=*/true);
  7006. }
  7007. }
  7008. if (!Method)
  7009. return false;
  7010. QualType T = Method->parameters()[0]->getType();
  7011. if (!T->isObjCObjectPointerType())
  7012. return false;
  7013. QualType R = Method->getReturnType();
  7014. if (!R->isScalarType())
  7015. return false;
  7016. return true;
  7017. }
  7018. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7019. FromE = FromE->IgnoreParenImpCasts();
  7020. switch (FromE->getStmtClass()) {
  7021. default:
  7022. break;
  7023. case Stmt::ObjCStringLiteralClass:
  7024. // "string literal"
  7025. return LK_String;
  7026. case Stmt::ObjCArrayLiteralClass:
  7027. // "array literal"
  7028. return LK_Array;
  7029. case Stmt::ObjCDictionaryLiteralClass:
  7030. // "dictionary literal"
  7031. return LK_Dictionary;
  7032. case Stmt::BlockExprClass:
  7033. return LK_Block;
  7034. case Stmt::ObjCBoxedExprClass: {
  7035. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7036. switch (Inner->getStmtClass()) {
  7037. case Stmt::IntegerLiteralClass:
  7038. case Stmt::FloatingLiteralClass:
  7039. case Stmt::CharacterLiteralClass:
  7040. case Stmt::ObjCBoolLiteralExprClass:
  7041. case Stmt::CXXBoolLiteralExprClass:
  7042. // "numeric literal"
  7043. return LK_Numeric;
  7044. case Stmt::ImplicitCastExprClass: {
  7045. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7046. // Boolean literals can be represented by implicit casts.
  7047. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7048. return LK_Numeric;
  7049. break;
  7050. }
  7051. default:
  7052. break;
  7053. }
  7054. return LK_Boxed;
  7055. }
  7056. }
  7057. return LK_None;
  7058. }
  7059. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7060. ExprResult &LHS, ExprResult &RHS,
  7061. BinaryOperator::Opcode Opc){
  7062. Expr *Literal;
  7063. Expr *Other;
  7064. if (isObjCObjectLiteral(LHS)) {
  7065. Literal = LHS.get();
  7066. Other = RHS.get();
  7067. } else {
  7068. Literal = RHS.get();
  7069. Other = LHS.get();
  7070. }
  7071. // Don't warn on comparisons against nil.
  7072. Other = Other->IgnoreParenCasts();
  7073. if (Other->isNullPointerConstant(S.getASTContext(),
  7074. Expr::NPC_ValueDependentIsNotNull))
  7075. return;
  7076. // This should be kept in sync with warn_objc_literal_comparison.
  7077. // LK_String should always be after the other literals, since it has its own
  7078. // warning flag.
  7079. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7080. assert(LiteralKind != Sema::LK_Block);
  7081. if (LiteralKind == Sema::LK_None) {
  7082. llvm_unreachable("Unknown Objective-C object literal kind");
  7083. }
  7084. if (LiteralKind == Sema::LK_String)
  7085. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7086. << Literal->getSourceRange();
  7087. else
  7088. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7089. << LiteralKind << Literal->getSourceRange();
  7090. if (BinaryOperator::isEqualityOp(Opc) &&
  7091. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7092. SourceLocation Start = LHS.get()->getLocStart();
  7093. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  7094. CharSourceRange OpRange =
  7095. CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
  7096. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7097. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7098. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7099. << FixItHint::CreateInsertion(End, "]");
  7100. }
  7101. }
  7102. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7103. ExprResult &RHS,
  7104. SourceLocation Loc,
  7105. unsigned OpaqueOpc) {
  7106. // This checking requires bools.
  7107. if (!S.getLangOpts().Bool) return;
  7108. // Check that left hand side is !something.
  7109. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7110. if (!UO || UO->getOpcode() != UO_LNot) return;
  7111. // Only check if the right hand side is non-bool arithmetic type.
  7112. if (RHS.get()->getType()->isBooleanType()) return;
  7113. // Make sure that the something in !something is not bool.
  7114. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7115. if (SubExpr->getType()->isBooleanType()) return;
  7116. // Emit warning.
  7117. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7118. << Loc;
  7119. // First note suggest !(x < y)
  7120. SourceLocation FirstOpen = SubExpr->getLocStart();
  7121. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7122. FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
  7123. if (FirstClose.isInvalid())
  7124. FirstOpen = SourceLocation();
  7125. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7126. << FixItHint::CreateInsertion(FirstOpen, "(")
  7127. << FixItHint::CreateInsertion(FirstClose, ")");
  7128. // Second note suggests (!x) < y
  7129. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7130. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7131. SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
  7132. if (SecondClose.isInvalid())
  7133. SecondOpen = SourceLocation();
  7134. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7135. << FixItHint::CreateInsertion(SecondOpen, "(")
  7136. << FixItHint::CreateInsertion(SecondClose, ")");
  7137. }
  7138. // Get the decl for a simple expression: a reference to a variable,
  7139. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7140. static ValueDecl *getCompareDecl(Expr *E) {
  7141. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7142. return DR->getDecl();
  7143. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7144. if (Ivar->isFreeIvar())
  7145. return Ivar->getDecl();
  7146. }
  7147. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7148. if (Mem->isImplicitAccess())
  7149. return Mem->getMemberDecl();
  7150. }
  7151. return nullptr;
  7152. }
  7153. // C99 6.5.8, C++ [expr.rel]
  7154. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7155. SourceLocation Loc, unsigned OpaqueOpc,
  7156. bool IsRelational) {
  7157. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7158. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  7159. // Handle vector comparisons separately.
  7160. if (LHS.get()->getType()->isVectorType() ||
  7161. RHS.get()->getType()->isVectorType())
  7162. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7163. QualType LHSType = LHS.get()->getType();
  7164. QualType RHSType = RHS.get()->getType();
  7165. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7166. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7167. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7168. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
  7169. if (!LHSType->hasFloatingRepresentation() &&
  7170. !(LHSType->isBlockPointerType() && IsRelational) &&
  7171. !LHS.get()->getLocStart().isMacroID() &&
  7172. !RHS.get()->getLocStart().isMacroID() &&
  7173. ActiveTemplateInstantiations.empty()) {
  7174. // For non-floating point types, check for self-comparisons of the form
  7175. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7176. // often indicate logic errors in the program.
  7177. //
  7178. // NOTE: Don't warn about comparison expressions resulting from macro
  7179. // expansion. Also don't warn about comparisons which are only self
  7180. // comparisons within a template specialization. The warnings should catch
  7181. // obvious cases in the definition of the template anyways. The idea is to
  7182. // warn when the typed comparison operator will always evaluate to the same
  7183. // result.
  7184. ValueDecl *DL = getCompareDecl(LHSStripped);
  7185. ValueDecl *DR = getCompareDecl(RHSStripped);
  7186. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7187. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7188. << 0 // self-
  7189. << (Opc == BO_EQ
  7190. || Opc == BO_LE
  7191. || Opc == BO_GE));
  7192. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7193. !DL->getType()->isReferenceType() &&
  7194. !DR->getType()->isReferenceType()) {
  7195. // what is it always going to eval to?
  7196. char always_evals_to;
  7197. switch(Opc) {
  7198. case BO_EQ: // e.g. array1 == array2
  7199. always_evals_to = 0; // false
  7200. break;
  7201. case BO_NE: // e.g. array1 != array2
  7202. always_evals_to = 1; // true
  7203. break;
  7204. default:
  7205. // best we can say is 'a constant'
  7206. always_evals_to = 2; // e.g. array1 <= array2
  7207. break;
  7208. }
  7209. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7210. << 1 // array
  7211. << always_evals_to);
  7212. }
  7213. if (isa<CastExpr>(LHSStripped))
  7214. LHSStripped = LHSStripped->IgnoreParenCasts();
  7215. if (isa<CastExpr>(RHSStripped))
  7216. RHSStripped = RHSStripped->IgnoreParenCasts();
  7217. // Warn about comparisons against a string constant (unless the other
  7218. // operand is null), the user probably wants strcmp.
  7219. Expr *literalString = nullptr;
  7220. Expr *literalStringStripped = nullptr;
  7221. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7222. !RHSStripped->isNullPointerConstant(Context,
  7223. Expr::NPC_ValueDependentIsNull)) {
  7224. literalString = LHS.get();
  7225. literalStringStripped = LHSStripped;
  7226. } else if ((isa<StringLiteral>(RHSStripped) ||
  7227. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7228. !LHSStripped->isNullPointerConstant(Context,
  7229. Expr::NPC_ValueDependentIsNull)) {
  7230. literalString = RHS.get();
  7231. literalStringStripped = RHSStripped;
  7232. }
  7233. if (literalString) {
  7234. DiagRuntimeBehavior(Loc, nullptr,
  7235. PDiag(diag::warn_stringcompare)
  7236. << isa<ObjCEncodeExpr>(literalStringStripped)
  7237. << literalString->getSourceRange());
  7238. }
  7239. }
  7240. // C99 6.5.8p3 / C99 6.5.9p4
  7241. UsualArithmeticConversions(LHS, RHS);
  7242. if (LHS.isInvalid() || RHS.isInvalid())
  7243. return QualType();
  7244. LHSType = LHS.get()->getType();
  7245. RHSType = RHS.get()->getType();
  7246. // The result of comparisons is 'bool' in C++, 'int' in C.
  7247. QualType ResultTy = Context.getLogicalOperationType();
  7248. if (IsRelational) {
  7249. if (LHSType->isRealType() && RHSType->isRealType())
  7250. return ResultTy;
  7251. } else {
  7252. // Check for comparisons of floating point operands using != and ==.
  7253. if (LHSType->hasFloatingRepresentation())
  7254. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7255. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7256. return ResultTy;
  7257. }
  7258. const Expr::NullPointerConstantKind LHSNullKind =
  7259. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7260. const Expr::NullPointerConstantKind RHSNullKind =
  7261. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7262. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7263. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7264. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7265. bool IsEquality = Opc == BO_EQ;
  7266. if (RHSIsNull)
  7267. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7268. RHS.get()->getSourceRange());
  7269. else
  7270. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7271. LHS.get()->getSourceRange());
  7272. }
  7273. // All of the following pointer-related warnings are GCC extensions, except
  7274. // when handling null pointer constants.
  7275. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7276. QualType LCanPointeeTy =
  7277. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7278. QualType RCanPointeeTy =
  7279. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7280. if (getLangOpts().CPlusPlus) {
  7281. if (LCanPointeeTy == RCanPointeeTy)
  7282. return ResultTy;
  7283. if (!IsRelational &&
  7284. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7285. // Valid unless comparison between non-null pointer and function pointer
  7286. // This is a gcc extension compatibility comparison.
  7287. // In a SFINAE context, we treat this as a hard error to maintain
  7288. // conformance with the C++ standard.
  7289. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7290. && !LHSIsNull && !RHSIsNull) {
  7291. diagnoseFunctionPointerToVoidComparison(
  7292. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7293. if (isSFINAEContext())
  7294. return QualType();
  7295. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7296. return ResultTy;
  7297. }
  7298. }
  7299. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7300. return QualType();
  7301. else
  7302. return ResultTy;
  7303. }
  7304. // C99 6.5.9p2 and C99 6.5.8p2
  7305. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7306. RCanPointeeTy.getUnqualifiedType())) {
  7307. // Valid unless a relational comparison of function pointers
  7308. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7309. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7310. << LHSType << RHSType << LHS.get()->getSourceRange()
  7311. << RHS.get()->getSourceRange();
  7312. }
  7313. } else if (!IsRelational &&
  7314. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7315. // Valid unless comparison between non-null pointer and function pointer
  7316. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7317. && !LHSIsNull && !RHSIsNull)
  7318. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7319. /*isError*/false);
  7320. } else {
  7321. // Invalid
  7322. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7323. }
  7324. if (LCanPointeeTy != RCanPointeeTy) {
  7325. const PointerType *lhsPtr = LHSType->getAs<PointerType>();
  7326. if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7327. Diag(Loc,
  7328. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7329. << LHSType << RHSType << 0 /* comparison */
  7330. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7331. }
  7332. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7333. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7334. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7335. : CK_BitCast;
  7336. if (LHSIsNull && !RHSIsNull)
  7337. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7338. else
  7339. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7340. }
  7341. return ResultTy;
  7342. }
  7343. if (getLangOpts().CPlusPlus) {
  7344. // Comparison of nullptr_t with itself.
  7345. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7346. return ResultTy;
  7347. // Comparison of pointers with null pointer constants and equality
  7348. // comparisons of member pointers to null pointer constants.
  7349. if (RHSIsNull &&
  7350. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7351. (!IsRelational &&
  7352. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7353. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7354. LHSType->isMemberPointerType()
  7355. ? CK_NullToMemberPointer
  7356. : CK_NullToPointer);
  7357. return ResultTy;
  7358. }
  7359. if (LHSIsNull &&
  7360. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7361. (!IsRelational &&
  7362. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7363. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7364. RHSType->isMemberPointerType()
  7365. ? CK_NullToMemberPointer
  7366. : CK_NullToPointer);
  7367. return ResultTy;
  7368. }
  7369. // Comparison of member pointers.
  7370. if (!IsRelational &&
  7371. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7372. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7373. return QualType();
  7374. else
  7375. return ResultTy;
  7376. }
  7377. // Handle scoped enumeration types specifically, since they don't promote
  7378. // to integers.
  7379. if (LHS.get()->getType()->isEnumeralType() &&
  7380. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7381. RHS.get()->getType()))
  7382. return ResultTy;
  7383. }
  7384. // Handle block pointer types.
  7385. if (!IsRelational && LHSType->isBlockPointerType() &&
  7386. RHSType->isBlockPointerType()) {
  7387. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7388. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7389. if (!LHSIsNull && !RHSIsNull &&
  7390. !Context.typesAreCompatible(lpointee, rpointee)) {
  7391. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7392. << LHSType << RHSType << LHS.get()->getSourceRange()
  7393. << RHS.get()->getSourceRange();
  7394. }
  7395. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7396. return ResultTy;
  7397. }
  7398. // Allow block pointers to be compared with null pointer constants.
  7399. if (!IsRelational
  7400. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7401. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7402. if (!LHSIsNull && !RHSIsNull) {
  7403. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7404. ->getPointeeType()->isVoidType())
  7405. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7406. ->getPointeeType()->isVoidType())))
  7407. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7408. << LHSType << RHSType << LHS.get()->getSourceRange()
  7409. << RHS.get()->getSourceRange();
  7410. }
  7411. if (LHSIsNull && !RHSIsNull)
  7412. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7413. RHSType->isPointerType() ? CK_BitCast
  7414. : CK_AnyPointerToBlockPointerCast);
  7415. else
  7416. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7417. LHSType->isPointerType() ? CK_BitCast
  7418. : CK_AnyPointerToBlockPointerCast);
  7419. return ResultTy;
  7420. }
  7421. if (LHSType->isObjCObjectPointerType() ||
  7422. RHSType->isObjCObjectPointerType()) {
  7423. const PointerType *LPT = LHSType->getAs<PointerType>();
  7424. const PointerType *RPT = RHSType->getAs<PointerType>();
  7425. if (LPT || RPT) {
  7426. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7427. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7428. if (!LPtrToVoid && !RPtrToVoid &&
  7429. !Context.typesAreCompatible(LHSType, RHSType)) {
  7430. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7431. /*isError*/false);
  7432. }
  7433. if (LHSIsNull && !RHSIsNull) {
  7434. Expr *E = LHS.get();
  7435. if (getLangOpts().ObjCAutoRefCount)
  7436. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7437. LHS = ImpCastExprToType(E, RHSType,
  7438. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7439. }
  7440. else {
  7441. Expr *E = RHS.get();
  7442. if (getLangOpts().ObjCAutoRefCount)
  7443. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7444. Opc);
  7445. RHS = ImpCastExprToType(E, LHSType,
  7446. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7447. }
  7448. return ResultTy;
  7449. }
  7450. if (LHSType->isObjCObjectPointerType() &&
  7451. RHSType->isObjCObjectPointerType()) {
  7452. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7453. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7454. /*isError*/false);
  7455. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7456. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7457. if (LHSIsNull && !RHSIsNull)
  7458. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7459. else
  7460. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7461. return ResultTy;
  7462. }
  7463. }
  7464. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7465. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7466. unsigned DiagID = 0;
  7467. bool isError = false;
  7468. if (LangOpts.DebuggerSupport) {
  7469. // Under a debugger, allow the comparison of pointers to integers,
  7470. // since users tend to want to compare addresses.
  7471. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7472. (RHSIsNull && RHSType->isIntegerType())) {
  7473. if (IsRelational && !getLangOpts().CPlusPlus)
  7474. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7475. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7476. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7477. else if (getLangOpts().CPlusPlus) {
  7478. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7479. isError = true;
  7480. } else
  7481. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7482. if (DiagID) {
  7483. Diag(Loc, DiagID)
  7484. << LHSType << RHSType << LHS.get()->getSourceRange()
  7485. << RHS.get()->getSourceRange();
  7486. if (isError)
  7487. return QualType();
  7488. }
  7489. if (LHSType->isIntegerType())
  7490. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7491. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7492. else
  7493. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7494. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7495. return ResultTy;
  7496. }
  7497. // Handle block pointers.
  7498. if (!IsRelational && RHSIsNull
  7499. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7500. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7501. return ResultTy;
  7502. }
  7503. if (!IsRelational && LHSIsNull
  7504. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7505. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7506. return ResultTy;
  7507. }
  7508. return InvalidOperands(Loc, LHS, RHS);
  7509. }
  7510. // Return a signed type that is of identical size and number of elements.
  7511. // For floating point vectors, return an integer type of identical size
  7512. // and number of elements.
  7513. QualType Sema::GetSignedVectorType(QualType V) {
  7514. const VectorType *VTy = V->getAs<VectorType>();
  7515. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7516. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7517. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7518. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7519. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7520. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7521. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7522. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7523. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7524. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7525. "Unhandled vector element size in vector compare");
  7526. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7527. }
  7528. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7529. /// operates on extended vector types. Instead of producing an IntTy result,
  7530. /// like a scalar comparison, a vector comparison produces a vector of integer
  7531. /// types.
  7532. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7533. SourceLocation Loc,
  7534. bool IsRelational) {
  7535. // Check to make sure we're operating on vectors of the same type and width,
  7536. // Allowing one side to be a scalar of element type.
  7537. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
  7538. if (vType.isNull())
  7539. return vType;
  7540. QualType LHSType = LHS.get()->getType();
  7541. // If AltiVec, the comparison results in a numeric type, i.e.
  7542. // bool for C++, int for C
  7543. if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7544. return Context.getLogicalOperationType();
  7545. // For non-floating point types, check for self-comparisons of the form
  7546. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7547. // often indicate logic errors in the program.
  7548. if (!LHSType->hasFloatingRepresentation() &&
  7549. ActiveTemplateInstantiations.empty()) {
  7550. if (DeclRefExpr* DRL
  7551. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7552. if (DeclRefExpr* DRR
  7553. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7554. if (DRL->getDecl() == DRR->getDecl())
  7555. DiagRuntimeBehavior(Loc, nullptr,
  7556. PDiag(diag::warn_comparison_always)
  7557. << 0 // self-
  7558. << 2 // "a constant"
  7559. );
  7560. }
  7561. // Check for comparisons of floating point operands using != and ==.
  7562. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7563. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7564. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7565. }
  7566. // Return a signed type for the vector.
  7567. return GetSignedVectorType(LHSType);
  7568. }
  7569. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7570. SourceLocation Loc) {
  7571. // Ensure that either both operands are of the same vector type, or
  7572. // one operand is of a vector type and the other is of its element type.
  7573. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
  7574. if (vType.isNull())
  7575. return InvalidOperands(Loc, LHS, RHS);
  7576. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7577. vType->hasFloatingRepresentation())
  7578. return InvalidOperands(Loc, LHS, RHS);
  7579. return GetSignedVectorType(LHS.get()->getType());
  7580. }
  7581. inline QualType Sema::CheckBitwiseOperands(
  7582. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7583. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7584. if (LHS.get()->getType()->isVectorType() ||
  7585. RHS.get()->getType()->isVectorType()) {
  7586. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7587. RHS.get()->getType()->hasIntegerRepresentation())
  7588. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
  7589. return InvalidOperands(Loc, LHS, RHS);
  7590. }
  7591. ExprResult LHSResult = LHS, RHSResult = RHS;
  7592. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  7593. IsCompAssign);
  7594. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  7595. return QualType();
  7596. LHS = LHSResult.get();
  7597. RHS = RHSResult.get();
  7598. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  7599. return compType;
  7600. return InvalidOperands(Loc, LHS, RHS);
  7601. }
  7602. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  7603. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  7604. // Check vector operands differently.
  7605. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  7606. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  7607. // Diagnose cases where the user write a logical and/or but probably meant a
  7608. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  7609. // is a constant.
  7610. if (LHS.get()->getType()->isIntegerType() &&
  7611. !LHS.get()->getType()->isBooleanType() &&
  7612. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  7613. // Don't warn in macros or template instantiations.
  7614. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  7615. // If the RHS can be constant folded, and if it constant folds to something
  7616. // that isn't 0 or 1 (which indicate a potential logical operation that
  7617. // happened to fold to true/false) then warn.
  7618. // Parens on the RHS are ignored.
  7619. llvm::APSInt Result;
  7620. if (RHS.get()->EvaluateAsInt(Result, Context))
  7621. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  7622. !RHS.get()->getExprLoc().isMacroID()) ||
  7623. (Result != 0 && Result != 1)) {
  7624. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  7625. << RHS.get()->getSourceRange()
  7626. << (Opc == BO_LAnd ? "&&" : "||");
  7627. // Suggest replacing the logical operator with the bitwise version
  7628. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  7629. << (Opc == BO_LAnd ? "&" : "|")
  7630. << FixItHint::CreateReplacement(SourceRange(
  7631. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  7632. getLangOpts())),
  7633. Opc == BO_LAnd ? "&" : "|");
  7634. if (Opc == BO_LAnd)
  7635. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  7636. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  7637. << FixItHint::CreateRemoval(
  7638. SourceRange(
  7639. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  7640. 0, getSourceManager(),
  7641. getLangOpts()),
  7642. RHS.get()->getLocEnd()));
  7643. }
  7644. }
  7645. if (!Context.getLangOpts().CPlusPlus) {
  7646. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  7647. // not operate on the built-in scalar and vector float types.
  7648. if (Context.getLangOpts().OpenCL &&
  7649. Context.getLangOpts().OpenCLVersion < 120) {
  7650. if (LHS.get()->getType()->isFloatingType() ||
  7651. RHS.get()->getType()->isFloatingType())
  7652. return InvalidOperands(Loc, LHS, RHS);
  7653. }
  7654. LHS = UsualUnaryConversions(LHS.get());
  7655. if (LHS.isInvalid())
  7656. return QualType();
  7657. RHS = UsualUnaryConversions(RHS.get());
  7658. if (RHS.isInvalid())
  7659. return QualType();
  7660. if (!LHS.get()->getType()->isScalarType() ||
  7661. !RHS.get()->getType()->isScalarType())
  7662. return InvalidOperands(Loc, LHS, RHS);
  7663. return Context.IntTy;
  7664. }
  7665. // The following is safe because we only use this method for
  7666. // non-overloadable operands.
  7667. // C++ [expr.log.and]p1
  7668. // C++ [expr.log.or]p1
  7669. // The operands are both contextually converted to type bool.
  7670. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  7671. if (LHSRes.isInvalid())
  7672. return InvalidOperands(Loc, LHS, RHS);
  7673. LHS = LHSRes;
  7674. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  7675. if (RHSRes.isInvalid())
  7676. return InvalidOperands(Loc, LHS, RHS);
  7677. RHS = RHSRes;
  7678. // C++ [expr.log.and]p2
  7679. // C++ [expr.log.or]p2
  7680. // The result is a bool.
  7681. return Context.BoolTy;
  7682. }
  7683. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  7684. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  7685. if (!ME) return false;
  7686. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  7687. ObjCMessageExpr *Base =
  7688. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  7689. if (!Base) return false;
  7690. return Base->getMethodDecl() != nullptr;
  7691. }
  7692. /// Is the given expression (which must be 'const') a reference to a
  7693. /// variable which was originally non-const, but which has become
  7694. /// 'const' due to being captured within a block?
  7695. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  7696. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  7697. assert(E->isLValue() && E->getType().isConstQualified());
  7698. E = E->IgnoreParens();
  7699. // Must be a reference to a declaration from an enclosing scope.
  7700. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  7701. if (!DRE) return NCCK_None;
  7702. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  7703. // The declaration must be a variable which is not declared 'const'.
  7704. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  7705. if (!var) return NCCK_None;
  7706. if (var->getType().isConstQualified()) return NCCK_None;
  7707. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  7708. // Decide whether the first capture was for a block or a lambda.
  7709. DeclContext *DC = S.CurContext, *Prev = nullptr;
  7710. while (DC != var->getDeclContext()) {
  7711. Prev = DC;
  7712. DC = DC->getParent();
  7713. }
  7714. // Unless we have an init-capture, we've gone one step too far.
  7715. if (!var->isInitCapture())
  7716. DC = Prev;
  7717. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  7718. }
  7719. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  7720. /// emit an error and return true. If so, return false.
  7721. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  7722. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  7723. SourceLocation OrigLoc = Loc;
  7724. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  7725. &Loc);
  7726. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  7727. IsLV = Expr::MLV_InvalidMessageExpression;
  7728. if (IsLV == Expr::MLV_Valid)
  7729. return false;
  7730. unsigned DiagID = 0;
  7731. bool NeedType = false;
  7732. switch (IsLV) { // C99 6.5.16p2
  7733. case Expr::MLV_ConstQualified:
  7734. DiagID = diag::err_typecheck_assign_const;
  7735. // Use a specialized diagnostic when we're assigning to an object
  7736. // from an enclosing function or block.
  7737. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  7738. if (NCCK == NCCK_Block)
  7739. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  7740. else
  7741. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  7742. break;
  7743. }
  7744. // In ARC, use some specialized diagnostics for occasions where we
  7745. // infer 'const'. These are always pseudo-strong variables.
  7746. if (S.getLangOpts().ObjCAutoRefCount) {
  7747. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  7748. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  7749. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  7750. // Use the normal diagnostic if it's pseudo-__strong but the
  7751. // user actually wrote 'const'.
  7752. if (var->isARCPseudoStrong() &&
  7753. (!var->getTypeSourceInfo() ||
  7754. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  7755. // There are two pseudo-strong cases:
  7756. // - self
  7757. ObjCMethodDecl *method = S.getCurMethodDecl();
  7758. if (method && var == method->getSelfDecl())
  7759. DiagID = method->isClassMethod()
  7760. ? diag::err_typecheck_arc_assign_self_class_method
  7761. : diag::err_typecheck_arc_assign_self;
  7762. // - fast enumeration variables
  7763. else
  7764. DiagID = diag::err_typecheck_arr_assign_enumeration;
  7765. SourceRange Assign;
  7766. if (Loc != OrigLoc)
  7767. Assign = SourceRange(OrigLoc, OrigLoc);
  7768. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  7769. // We need to preserve the AST regardless, so migration tool
  7770. // can do its job.
  7771. return false;
  7772. }
  7773. }
  7774. }
  7775. break;
  7776. case Expr::MLV_ArrayType:
  7777. case Expr::MLV_ArrayTemporary:
  7778. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  7779. NeedType = true;
  7780. break;
  7781. case Expr::MLV_NotObjectType:
  7782. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  7783. NeedType = true;
  7784. break;
  7785. case Expr::MLV_LValueCast:
  7786. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  7787. break;
  7788. case Expr::MLV_Valid:
  7789. llvm_unreachable("did not take early return for MLV_Valid");
  7790. case Expr::MLV_InvalidExpression:
  7791. case Expr::MLV_MemberFunction:
  7792. case Expr::MLV_ClassTemporary:
  7793. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  7794. break;
  7795. case Expr::MLV_IncompleteType:
  7796. case Expr::MLV_IncompleteVoidType:
  7797. return S.RequireCompleteType(Loc, E->getType(),
  7798. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  7799. case Expr::MLV_DuplicateVectorComponents:
  7800. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  7801. break;
  7802. case Expr::MLV_NoSetterProperty:
  7803. llvm_unreachable("readonly properties should be processed differently");
  7804. case Expr::MLV_InvalidMessageExpression:
  7805. DiagID = diag::error_readonly_message_assignment;
  7806. break;
  7807. case Expr::MLV_SubObjCPropertySetting:
  7808. DiagID = diag::error_no_subobject_property_setting;
  7809. break;
  7810. }
  7811. SourceRange Assign;
  7812. if (Loc != OrigLoc)
  7813. Assign = SourceRange(OrigLoc, OrigLoc);
  7814. if (NeedType)
  7815. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  7816. else
  7817. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  7818. return true;
  7819. }
  7820. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  7821. SourceLocation Loc,
  7822. Sema &Sema) {
  7823. // C / C++ fields
  7824. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  7825. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  7826. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  7827. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  7828. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  7829. }
  7830. // Objective-C instance variables
  7831. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  7832. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  7833. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  7834. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  7835. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  7836. if (RL && RR && RL->getDecl() == RR->getDecl())
  7837. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  7838. }
  7839. }
  7840. // C99 6.5.16.1
  7841. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  7842. SourceLocation Loc,
  7843. QualType CompoundType) {
  7844. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  7845. // Verify that LHS is a modifiable lvalue, and emit error if not.
  7846. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  7847. return QualType();
  7848. QualType LHSType = LHSExpr->getType();
  7849. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  7850. CompoundType;
  7851. AssignConvertType ConvTy;
  7852. if (CompoundType.isNull()) {
  7853. Expr *RHSCheck = RHS.get();
  7854. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  7855. QualType LHSTy(LHSType);
  7856. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  7857. if (RHS.isInvalid())
  7858. return QualType();
  7859. // Special case of NSObject attributes on c-style pointer types.
  7860. if (ConvTy == IncompatiblePointer &&
  7861. ((Context.isObjCNSObjectType(LHSType) &&
  7862. RHSType->isObjCObjectPointerType()) ||
  7863. (Context.isObjCNSObjectType(RHSType) &&
  7864. LHSType->isObjCObjectPointerType())))
  7865. ConvTy = Compatible;
  7866. if (ConvTy == Compatible &&
  7867. LHSType->isObjCObjectType())
  7868. Diag(Loc, diag::err_objc_object_assignment)
  7869. << LHSType;
  7870. // If the RHS is a unary plus or minus, check to see if they = and + are
  7871. // right next to each other. If so, the user may have typo'd "x =+ 4"
  7872. // instead of "x += 4".
  7873. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  7874. RHSCheck = ICE->getSubExpr();
  7875. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  7876. if ((UO->getOpcode() == UO_Plus ||
  7877. UO->getOpcode() == UO_Minus) &&
  7878. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  7879. // Only if the two operators are exactly adjacent.
  7880. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  7881. // And there is a space or other character before the subexpr of the
  7882. // unary +/-. We don't want to warn on "x=-1".
  7883. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  7884. UO->getSubExpr()->getLocStart().isFileID()) {
  7885. Diag(Loc, diag::warn_not_compound_assign)
  7886. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  7887. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  7888. }
  7889. }
  7890. if (ConvTy == Compatible) {
  7891. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  7892. // Warn about retain cycles where a block captures the LHS, but
  7893. // not if the LHS is a simple variable into which the block is
  7894. // being stored...unless that variable can be captured by reference!
  7895. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  7896. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  7897. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  7898. checkRetainCycles(LHSExpr, RHS.get());
  7899. // It is safe to assign a weak reference into a strong variable.
  7900. // Although this code can still have problems:
  7901. // id x = self.weakProp;
  7902. // id y = self.weakProp;
  7903. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  7904. // paths through the function. This should be revisited if
  7905. // -Wrepeated-use-of-weak is made flow-sensitive.
  7906. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  7907. RHS.get()->getLocStart()))
  7908. getCurFunction()->markSafeWeakUse(RHS.get());
  7909. } else if (getLangOpts().ObjCAutoRefCount) {
  7910. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  7911. }
  7912. }
  7913. } else {
  7914. // Compound assignment "x += y"
  7915. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  7916. }
  7917. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  7918. RHS.get(), AA_Assigning))
  7919. return QualType();
  7920. CheckForNullPointerDereference(*this, LHSExpr);
  7921. // C99 6.5.16p3: The type of an assignment expression is the type of the
  7922. // left operand unless the left operand has qualified type, in which case
  7923. // it is the unqualified version of the type of the left operand.
  7924. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  7925. // is converted to the type of the assignment expression (above).
  7926. // C++ 5.17p1: the type of the assignment expression is that of its left
  7927. // operand.
  7928. return (getLangOpts().CPlusPlus
  7929. ? LHSType : LHSType.getUnqualifiedType());
  7930. }
  7931. // C99 6.5.17
  7932. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7933. SourceLocation Loc) {
  7934. LHS = S.CheckPlaceholderExpr(LHS.get());
  7935. RHS = S.CheckPlaceholderExpr(RHS.get());
  7936. if (LHS.isInvalid() || RHS.isInvalid())
  7937. return QualType();
  7938. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  7939. // operands, but not unary promotions.
  7940. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  7941. // So we treat the LHS as a ignored value, and in C++ we allow the
  7942. // containing site to determine what should be done with the RHS.
  7943. LHS = S.IgnoredValueConversions(LHS.get());
  7944. if (LHS.isInvalid())
  7945. return QualType();
  7946. S.DiagnoseUnusedExprResult(LHS.get());
  7947. if (!S.getLangOpts().CPlusPlus) {
  7948. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  7949. if (RHS.isInvalid())
  7950. return QualType();
  7951. if (!RHS.get()->getType()->isVoidType())
  7952. S.RequireCompleteType(Loc, RHS.get()->getType(),
  7953. diag::err_incomplete_type);
  7954. }
  7955. return RHS.get()->getType();
  7956. }
  7957. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  7958. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  7959. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  7960. ExprValueKind &VK,
  7961. ExprObjectKind &OK,
  7962. SourceLocation OpLoc,
  7963. bool IsInc, bool IsPrefix) {
  7964. if (Op->isTypeDependent())
  7965. return S.Context.DependentTy;
  7966. QualType ResType = Op->getType();
  7967. // Atomic types can be used for increment / decrement where the non-atomic
  7968. // versions can, so ignore the _Atomic() specifier for the purpose of
  7969. // checking.
  7970. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7971. ResType = ResAtomicType->getValueType();
  7972. assert(!ResType.isNull() && "no type for increment/decrement expression");
  7973. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  7974. // Decrement of bool is not allowed.
  7975. if (!IsInc) {
  7976. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  7977. return QualType();
  7978. }
  7979. // Increment of bool sets it to true, but is deprecated.
  7980. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  7981. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  7982. // Error on enum increments and decrements in C++ mode
  7983. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  7984. return QualType();
  7985. } else if (ResType->isRealType()) {
  7986. // OK!
  7987. } else if (ResType->isPointerType()) {
  7988. // C99 6.5.2.4p2, 6.5.6p2
  7989. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  7990. return QualType();
  7991. } else if (ResType->isObjCObjectPointerType()) {
  7992. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  7993. // Otherwise, we just need a complete type.
  7994. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  7995. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  7996. return QualType();
  7997. } else if (ResType->isAnyComplexType()) {
  7998. // C99 does not support ++/-- on complex types, we allow as an extension.
  7999. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8000. << ResType << Op->getSourceRange();
  8001. } else if (ResType->isPlaceholderType()) {
  8002. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8003. if (PR.isInvalid()) return QualType();
  8004. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8005. IsInc, IsPrefix);
  8006. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8007. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8008. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8009. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8010. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8011. } else {
  8012. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8013. << ResType << int(IsInc) << Op->getSourceRange();
  8014. return QualType();
  8015. }
  8016. // At this point, we know we have a real, complex or pointer type.
  8017. // Now make sure the operand is a modifiable lvalue.
  8018. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8019. return QualType();
  8020. // In C++, a prefix increment is the same type as the operand. Otherwise
  8021. // (in C or with postfix), the increment is the unqualified type of the
  8022. // operand.
  8023. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8024. VK = VK_LValue;
  8025. OK = Op->getObjectKind();
  8026. return ResType;
  8027. } else {
  8028. VK = VK_RValue;
  8029. return ResType.getUnqualifiedType();
  8030. }
  8031. }
  8032. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8033. /// This routine allows us to typecheck complex/recursive expressions
  8034. /// where the declaration is needed for type checking. We only need to
  8035. /// handle cases when the expression references a function designator
  8036. /// or is an lvalue. Here are some examples:
  8037. /// - &(x) => x
  8038. /// - &*****f => f for f a function designator.
  8039. /// - &s.xx => s
  8040. /// - &s.zz[1].yy -> s, if zz is an array
  8041. /// - *(x + 1) -> x, if x is an array
  8042. /// - &"123"[2] -> 0
  8043. /// - & __real__ x -> x
  8044. static ValueDecl *getPrimaryDecl(Expr *E) {
  8045. switch (E->getStmtClass()) {
  8046. case Stmt::DeclRefExprClass:
  8047. return cast<DeclRefExpr>(E)->getDecl();
  8048. case Stmt::MemberExprClass:
  8049. // If this is an arrow operator, the address is an offset from
  8050. // the base's value, so the object the base refers to is
  8051. // irrelevant.
  8052. if (cast<MemberExpr>(E)->isArrow())
  8053. return nullptr;
  8054. // Otherwise, the expression refers to a part of the base
  8055. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8056. case Stmt::ArraySubscriptExprClass: {
  8057. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8058. // promotion of register arrays earlier.
  8059. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8060. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8061. if (ICE->getSubExpr()->getType()->isArrayType())
  8062. return getPrimaryDecl(ICE->getSubExpr());
  8063. }
  8064. return nullptr;
  8065. }
  8066. case Stmt::UnaryOperatorClass: {
  8067. UnaryOperator *UO = cast<UnaryOperator>(E);
  8068. switch(UO->getOpcode()) {
  8069. case UO_Real:
  8070. case UO_Imag:
  8071. case UO_Extension:
  8072. return getPrimaryDecl(UO->getSubExpr());
  8073. default:
  8074. return nullptr;
  8075. }
  8076. }
  8077. case Stmt::ParenExprClass:
  8078. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8079. case Stmt::ImplicitCastExprClass:
  8080. // If the result of an implicit cast is an l-value, we care about
  8081. // the sub-expression; otherwise, the result here doesn't matter.
  8082. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8083. default:
  8084. return nullptr;
  8085. }
  8086. }
  8087. namespace {
  8088. enum {
  8089. AO_Bit_Field = 0,
  8090. AO_Vector_Element = 1,
  8091. AO_Property_Expansion = 2,
  8092. AO_Register_Variable = 3,
  8093. AO_No_Error = 4
  8094. };
  8095. }
  8096. /// \brief Diagnose invalid operand for address of operations.
  8097. ///
  8098. /// \param Type The type of operand which cannot have its address taken.
  8099. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8100. Expr *E, unsigned Type) {
  8101. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8102. }
  8103. /// CheckAddressOfOperand - The operand of & must be either a function
  8104. /// designator or an lvalue designating an object. If it is an lvalue, the
  8105. /// object cannot be declared with storage class register or be a bit field.
  8106. /// Note: The usual conversions are *not* applied to the operand of the &
  8107. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8108. /// In C++, the operand might be an overloaded function name, in which case
  8109. /// we allow the '&' but retain the overloaded-function type.
  8110. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8111. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8112. if (PTy->getKind() == BuiltinType::Overload) {
  8113. Expr *E = OrigOp.get()->IgnoreParens();
  8114. if (!isa<OverloadExpr>(E)) {
  8115. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8116. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8117. << OrigOp.get()->getSourceRange();
  8118. return QualType();
  8119. }
  8120. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8121. if (isa<UnresolvedMemberExpr>(Ovl))
  8122. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8123. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8124. << OrigOp.get()->getSourceRange();
  8125. return QualType();
  8126. }
  8127. return Context.OverloadTy;
  8128. }
  8129. if (PTy->getKind() == BuiltinType::UnknownAny)
  8130. return Context.UnknownAnyTy;
  8131. if (PTy->getKind() == BuiltinType::BoundMember) {
  8132. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8133. << OrigOp.get()->getSourceRange();
  8134. return QualType();
  8135. }
  8136. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8137. if (OrigOp.isInvalid()) return QualType();
  8138. }
  8139. if (OrigOp.get()->isTypeDependent())
  8140. return Context.DependentTy;
  8141. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8142. // Make sure to ignore parentheses in subsequent checks
  8143. Expr *op = OrigOp.get()->IgnoreParens();
  8144. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8145. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8146. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8147. return QualType();
  8148. }
  8149. if (getLangOpts().C99) {
  8150. // Implement C99-only parts of addressof rules.
  8151. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8152. if (uOp->getOpcode() == UO_Deref)
  8153. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8154. // (assuming the deref expression is valid).
  8155. return uOp->getSubExpr()->getType();
  8156. }
  8157. // Technically, there should be a check for array subscript
  8158. // expressions here, but the result of one is always an lvalue anyway.
  8159. }
  8160. ValueDecl *dcl = getPrimaryDecl(op);
  8161. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8162. unsigned AddressOfError = AO_No_Error;
  8163. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8164. bool sfinae = (bool)isSFINAEContext();
  8165. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8166. : diag::ext_typecheck_addrof_temporary)
  8167. << op->getType() << op->getSourceRange();
  8168. if (sfinae)
  8169. return QualType();
  8170. // Materialize the temporary as an lvalue so that we can take its address.
  8171. OrigOp = op = new (Context)
  8172. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8173. } else if (isa<ObjCSelectorExpr>(op)) {
  8174. return Context.getPointerType(op->getType());
  8175. } else if (lval == Expr::LV_MemberFunction) {
  8176. // If it's an instance method, make a member pointer.
  8177. // The expression must have exactly the form &A::foo.
  8178. // If the underlying expression isn't a decl ref, give up.
  8179. if (!isa<DeclRefExpr>(op)) {
  8180. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8181. << OrigOp.get()->getSourceRange();
  8182. return QualType();
  8183. }
  8184. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8185. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8186. // The id-expression was parenthesized.
  8187. if (OrigOp.get() != DRE) {
  8188. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8189. << OrigOp.get()->getSourceRange();
  8190. // The method was named without a qualifier.
  8191. } else if (!DRE->getQualifier()) {
  8192. if (MD->getParent()->getName().empty())
  8193. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8194. << op->getSourceRange();
  8195. else {
  8196. SmallString<32> Str;
  8197. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8198. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8199. << op->getSourceRange()
  8200. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8201. }
  8202. }
  8203. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8204. if (isa<CXXDestructorDecl>(MD))
  8205. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8206. QualType MPTy = Context.getMemberPointerType(
  8207. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8208. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8209. RequireCompleteType(OpLoc, MPTy, 0);
  8210. return MPTy;
  8211. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8212. // C99 6.5.3.2p1
  8213. // The operand must be either an l-value or a function designator
  8214. if (!op->getType()->isFunctionType()) {
  8215. // Use a special diagnostic for loads from property references.
  8216. if (isa<PseudoObjectExpr>(op)) {
  8217. AddressOfError = AO_Property_Expansion;
  8218. } else {
  8219. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8220. << op->getType() << op->getSourceRange();
  8221. return QualType();
  8222. }
  8223. }
  8224. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8225. // The operand cannot be a bit-field
  8226. AddressOfError = AO_Bit_Field;
  8227. } else if (op->getObjectKind() == OK_VectorComponent) {
  8228. // The operand cannot be an element of a vector
  8229. AddressOfError = AO_Vector_Element;
  8230. } else if (dcl) { // C99 6.5.3.2p1
  8231. // We have an lvalue with a decl. Make sure the decl is not declared
  8232. // with the register storage-class specifier.
  8233. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8234. // in C++ it is not error to take address of a register
  8235. // variable (c++03 7.1.1P3)
  8236. if (vd->getStorageClass() == SC_Register &&
  8237. !getLangOpts().CPlusPlus) {
  8238. AddressOfError = AO_Register_Variable;
  8239. }
  8240. } else if (isa<MSPropertyDecl>(dcl)) {
  8241. AddressOfError = AO_Property_Expansion;
  8242. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8243. return Context.OverloadTy;
  8244. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8245. // Okay: we can take the address of a field.
  8246. // Could be a pointer to member, though, if there is an explicit
  8247. // scope qualifier for the class.
  8248. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8249. DeclContext *Ctx = dcl->getDeclContext();
  8250. if (Ctx && Ctx->isRecord()) {
  8251. if (dcl->getType()->isReferenceType()) {
  8252. Diag(OpLoc,
  8253. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8254. << dcl->getDeclName() << dcl->getType();
  8255. return QualType();
  8256. }
  8257. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8258. Ctx = Ctx->getParent();
  8259. QualType MPTy = Context.getMemberPointerType(
  8260. op->getType(),
  8261. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8262. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8263. RequireCompleteType(OpLoc, MPTy, 0);
  8264. return MPTy;
  8265. }
  8266. }
  8267. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8268. llvm_unreachable("Unknown/unexpected decl type");
  8269. }
  8270. if (AddressOfError != AO_No_Error) {
  8271. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8272. return QualType();
  8273. }
  8274. if (lval == Expr::LV_IncompleteVoidType) {
  8275. // Taking the address of a void variable is technically illegal, but we
  8276. // allow it in cases which are otherwise valid.
  8277. // Example: "extern void x; void* y = &x;".
  8278. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8279. }
  8280. // If the operand has type "type", the result has type "pointer to type".
  8281. if (op->getType()->isObjCObjectType())
  8282. return Context.getObjCObjectPointerType(op->getType());
  8283. return Context.getPointerType(op->getType());
  8284. }
  8285. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8286. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8287. if (!DRE)
  8288. return;
  8289. const Decl *D = DRE->getDecl();
  8290. if (!D)
  8291. return;
  8292. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8293. if (!Param)
  8294. return;
  8295. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8296. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8297. return;
  8298. if (FunctionScopeInfo *FD = S.getCurFunction())
  8299. if (!FD->ModifiedNonNullParams.count(Param))
  8300. FD->ModifiedNonNullParams.insert(Param);
  8301. }
  8302. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8303. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8304. SourceLocation OpLoc) {
  8305. if (Op->isTypeDependent())
  8306. return S.Context.DependentTy;
  8307. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8308. if (ConvResult.isInvalid())
  8309. return QualType();
  8310. Op = ConvResult.get();
  8311. QualType OpTy = Op->getType();
  8312. QualType Result;
  8313. if (isa<CXXReinterpretCastExpr>(Op)) {
  8314. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8315. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8316. Op->getSourceRange());
  8317. }
  8318. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8319. Result = PT->getPointeeType();
  8320. else if (const ObjCObjectPointerType *OPT =
  8321. OpTy->getAs<ObjCObjectPointerType>())
  8322. Result = OPT->getPointeeType();
  8323. else {
  8324. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8325. if (PR.isInvalid()) return QualType();
  8326. if (PR.get() != Op)
  8327. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8328. }
  8329. if (Result.isNull()) {
  8330. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8331. << OpTy << Op->getSourceRange();
  8332. return QualType();
  8333. }
  8334. // Note that per both C89 and C99, indirection is always legal, even if Result
  8335. // is an incomplete type or void. It would be possible to warn about
  8336. // dereferencing a void pointer, but it's completely well-defined, and such a
  8337. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8338. // for pointers to 'void' but is fine for any other pointer type:
  8339. //
  8340. // C++ [expr.unary.op]p1:
  8341. // [...] the expression to which [the unary * operator] is applied shall
  8342. // be a pointer to an object type, or a pointer to a function type
  8343. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8344. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8345. << OpTy << Op->getSourceRange();
  8346. // Dereferences are usually l-values...
  8347. VK = VK_LValue;
  8348. // ...except that certain expressions are never l-values in C.
  8349. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8350. VK = VK_RValue;
  8351. return Result;
  8352. }
  8353. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8354. BinaryOperatorKind Opc;
  8355. switch (Kind) {
  8356. default: llvm_unreachable("Unknown binop!");
  8357. case tok::periodstar: Opc = BO_PtrMemD; break;
  8358. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8359. case tok::star: Opc = BO_Mul; break;
  8360. case tok::slash: Opc = BO_Div; break;
  8361. case tok::percent: Opc = BO_Rem; break;
  8362. case tok::plus: Opc = BO_Add; break;
  8363. case tok::minus: Opc = BO_Sub; break;
  8364. case tok::lessless: Opc = BO_Shl; break;
  8365. case tok::greatergreater: Opc = BO_Shr; break;
  8366. case tok::lessequal: Opc = BO_LE; break;
  8367. case tok::less: Opc = BO_LT; break;
  8368. case tok::greaterequal: Opc = BO_GE; break;
  8369. case tok::greater: Opc = BO_GT; break;
  8370. case tok::exclaimequal: Opc = BO_NE; break;
  8371. case tok::equalequal: Opc = BO_EQ; break;
  8372. case tok::amp: Opc = BO_And; break;
  8373. case tok::caret: Opc = BO_Xor; break;
  8374. case tok::pipe: Opc = BO_Or; break;
  8375. case tok::ampamp: Opc = BO_LAnd; break;
  8376. case tok::pipepipe: Opc = BO_LOr; break;
  8377. case tok::equal: Opc = BO_Assign; break;
  8378. case tok::starequal: Opc = BO_MulAssign; break;
  8379. case tok::slashequal: Opc = BO_DivAssign; break;
  8380. case tok::percentequal: Opc = BO_RemAssign; break;
  8381. case tok::plusequal: Opc = BO_AddAssign; break;
  8382. case tok::minusequal: Opc = BO_SubAssign; break;
  8383. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8384. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8385. case tok::ampequal: Opc = BO_AndAssign; break;
  8386. case tok::caretequal: Opc = BO_XorAssign; break;
  8387. case tok::pipeequal: Opc = BO_OrAssign; break;
  8388. case tok::comma: Opc = BO_Comma; break;
  8389. }
  8390. return Opc;
  8391. }
  8392. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8393. tok::TokenKind Kind) {
  8394. UnaryOperatorKind Opc;
  8395. switch (Kind) {
  8396. default: llvm_unreachable("Unknown unary op!");
  8397. case tok::plusplus: Opc = UO_PreInc; break;
  8398. case tok::minusminus: Opc = UO_PreDec; break;
  8399. case tok::amp: Opc = UO_AddrOf; break;
  8400. case tok::star: Opc = UO_Deref; break;
  8401. case tok::plus: Opc = UO_Plus; break;
  8402. case tok::minus: Opc = UO_Minus; break;
  8403. case tok::tilde: Opc = UO_Not; break;
  8404. case tok::exclaim: Opc = UO_LNot; break;
  8405. case tok::kw___real: Opc = UO_Real; break;
  8406. case tok::kw___imag: Opc = UO_Imag; break;
  8407. case tok::kw___extension__: Opc = UO_Extension; break;
  8408. }
  8409. return Opc;
  8410. }
  8411. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8412. /// This warning is only emitted for builtin assignment operations. It is also
  8413. /// suppressed in the event of macro expansions.
  8414. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8415. SourceLocation OpLoc) {
  8416. if (!S.ActiveTemplateInstantiations.empty())
  8417. return;
  8418. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  8419. return;
  8420. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8421. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8422. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8423. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8424. if (!LHSDeclRef || !RHSDeclRef ||
  8425. LHSDeclRef->getLocation().isMacroID() ||
  8426. RHSDeclRef->getLocation().isMacroID())
  8427. return;
  8428. const ValueDecl *LHSDecl =
  8429. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  8430. const ValueDecl *RHSDecl =
  8431. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  8432. if (LHSDecl != RHSDecl)
  8433. return;
  8434. if (LHSDecl->getType().isVolatileQualified())
  8435. return;
  8436. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  8437. if (RefTy->getPointeeType().isVolatileQualified())
  8438. return;
  8439. S.Diag(OpLoc, diag::warn_self_assignment)
  8440. << LHSDeclRef->getType()
  8441. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8442. }
  8443. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  8444. /// is usually indicative of introspection within the Objective-C pointer.
  8445. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  8446. SourceLocation OpLoc) {
  8447. if (!S.getLangOpts().ObjC1)
  8448. return;
  8449. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  8450. const Expr *LHS = L.get();
  8451. const Expr *RHS = R.get();
  8452. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8453. ObjCPointerExpr = LHS;
  8454. OtherExpr = RHS;
  8455. }
  8456. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8457. ObjCPointerExpr = RHS;
  8458. OtherExpr = LHS;
  8459. }
  8460. // This warning is deliberately made very specific to reduce false
  8461. // positives with logic that uses '&' for hashing. This logic mainly
  8462. // looks for code trying to introspect into tagged pointers, which
  8463. // code should generally never do.
  8464. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  8465. unsigned Diag = diag::warn_objc_pointer_masking;
  8466. // Determine if we are introspecting the result of performSelectorXXX.
  8467. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  8468. // Special case messages to -performSelector and friends, which
  8469. // can return non-pointer values boxed in a pointer value.
  8470. // Some clients may wish to silence warnings in this subcase.
  8471. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  8472. Selector S = ME->getSelector();
  8473. StringRef SelArg0 = S.getNameForSlot(0);
  8474. if (SelArg0.startswith("performSelector"))
  8475. Diag = diag::warn_objc_pointer_masking_performSelector;
  8476. }
  8477. S.Diag(OpLoc, Diag)
  8478. << ObjCPointerExpr->getSourceRange();
  8479. }
  8480. }
  8481. static NamedDecl *getDeclFromExpr(Expr *E) {
  8482. if (!E)
  8483. return nullptr;
  8484. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  8485. return DRE->getDecl();
  8486. if (auto *ME = dyn_cast<MemberExpr>(E))
  8487. return ME->getMemberDecl();
  8488. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  8489. return IRE->getDecl();
  8490. return nullptr;
  8491. }
  8492. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  8493. /// operator @p Opc at location @c TokLoc. This routine only supports
  8494. /// built-in operations; ActOnBinOp handles overloaded operators.
  8495. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  8496. BinaryOperatorKind Opc,
  8497. Expr *LHSExpr, Expr *RHSExpr) {
  8498. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  8499. // The syntax only allows initializer lists on the RHS of assignment,
  8500. // so we don't need to worry about accepting invalid code for
  8501. // non-assignment operators.
  8502. // C++11 5.17p9:
  8503. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  8504. // of x = {} is x = T().
  8505. InitializationKind Kind =
  8506. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  8507. InitializedEntity Entity =
  8508. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  8509. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  8510. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  8511. if (Init.isInvalid())
  8512. return Init;
  8513. RHSExpr = Init.get();
  8514. }
  8515. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  8516. QualType ResultTy; // Result type of the binary operator.
  8517. // The following two variables are used for compound assignment operators
  8518. QualType CompLHSTy; // Type of LHS after promotions for computation
  8519. QualType CompResultTy; // Type of computation result
  8520. ExprValueKind VK = VK_RValue;
  8521. ExprObjectKind OK = OK_Ordinary;
  8522. if (!getLangOpts().CPlusPlus) {
  8523. // C cannot handle TypoExpr nodes on either side of a binop because it
  8524. // doesn't handle dependent types properly, so make sure any TypoExprs have
  8525. // been dealt with before checking the operands.
  8526. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  8527. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  8528. if (Opc != BO_Assign)
  8529. return ExprResult(E);
  8530. // Avoid correcting the RHS to the same Expr as the LHS.
  8531. Decl *D = getDeclFromExpr(E);
  8532. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  8533. });
  8534. if (!LHS.isUsable() || !RHS.isUsable())
  8535. return ExprError();
  8536. }
  8537. switch (Opc) {
  8538. case BO_Assign:
  8539. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  8540. if (getLangOpts().CPlusPlus &&
  8541. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  8542. VK = LHS.get()->getValueKind();
  8543. OK = LHS.get()->getObjectKind();
  8544. }
  8545. if (!ResultTy.isNull()) {
  8546. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  8547. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  8548. }
  8549. RecordModifiableNonNullParam(*this, LHS.get());
  8550. break;
  8551. case BO_PtrMemD:
  8552. case BO_PtrMemI:
  8553. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  8554. Opc == BO_PtrMemI);
  8555. break;
  8556. case BO_Mul:
  8557. case BO_Div:
  8558. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  8559. Opc == BO_Div);
  8560. break;
  8561. case BO_Rem:
  8562. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  8563. break;
  8564. case BO_Add:
  8565. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  8566. break;
  8567. case BO_Sub:
  8568. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  8569. break;
  8570. case BO_Shl:
  8571. case BO_Shr:
  8572. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  8573. break;
  8574. case BO_LE:
  8575. case BO_LT:
  8576. case BO_GE:
  8577. case BO_GT:
  8578. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  8579. break;
  8580. case BO_EQ:
  8581. case BO_NE:
  8582. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  8583. break;
  8584. case BO_And:
  8585. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  8586. case BO_Xor:
  8587. case BO_Or:
  8588. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  8589. break;
  8590. case BO_LAnd:
  8591. case BO_LOr:
  8592. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  8593. break;
  8594. case BO_MulAssign:
  8595. case BO_DivAssign:
  8596. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  8597. Opc == BO_DivAssign);
  8598. CompLHSTy = CompResultTy;
  8599. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8600. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8601. break;
  8602. case BO_RemAssign:
  8603. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  8604. CompLHSTy = CompResultTy;
  8605. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8606. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8607. break;
  8608. case BO_AddAssign:
  8609. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  8610. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8611. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8612. break;
  8613. case BO_SubAssign:
  8614. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  8615. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8616. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8617. break;
  8618. case BO_ShlAssign:
  8619. case BO_ShrAssign:
  8620. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  8621. CompLHSTy = CompResultTy;
  8622. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8623. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8624. break;
  8625. case BO_AndAssign:
  8626. case BO_OrAssign: // fallthrough
  8627. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  8628. case BO_XorAssign:
  8629. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  8630. CompLHSTy = CompResultTy;
  8631. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8632. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8633. break;
  8634. case BO_Comma:
  8635. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  8636. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  8637. VK = RHS.get()->getValueKind();
  8638. OK = RHS.get()->getObjectKind();
  8639. }
  8640. break;
  8641. }
  8642. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  8643. return ExprError();
  8644. // Check for array bounds violations for both sides of the BinaryOperator
  8645. CheckArrayAccess(LHS.get());
  8646. CheckArrayAccess(RHS.get());
  8647. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  8648. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  8649. &Context.Idents.get("object_setClass"),
  8650. SourceLocation(), LookupOrdinaryName);
  8651. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  8652. SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  8653. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  8654. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  8655. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  8656. FixItHint::CreateInsertion(RHSLocEnd, ")");
  8657. }
  8658. else
  8659. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  8660. }
  8661. else if (const ObjCIvarRefExpr *OIRE =
  8662. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  8663. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  8664. if (CompResultTy.isNull())
  8665. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  8666. OK, OpLoc, FPFeatures.fp_contract);
  8667. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  8668. OK_ObjCProperty) {
  8669. VK = VK_LValue;
  8670. OK = LHS.get()->getObjectKind();
  8671. }
  8672. return new (Context) CompoundAssignOperator(
  8673. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  8674. OpLoc, FPFeatures.fp_contract);
  8675. }
  8676. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  8677. /// operators are mixed in a way that suggests that the programmer forgot that
  8678. /// comparison operators have higher precedence. The most typical example of
  8679. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  8680. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  8681. SourceLocation OpLoc, Expr *LHSExpr,
  8682. Expr *RHSExpr) {
  8683. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  8684. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  8685. // Check that one of the sides is a comparison operator.
  8686. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  8687. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  8688. if (!isLeftComp && !isRightComp)
  8689. return;
  8690. // Bitwise operations are sometimes used as eager logical ops.
  8691. // Don't diagnose this.
  8692. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  8693. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  8694. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  8695. return;
  8696. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  8697. OpLoc)
  8698. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  8699. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  8700. SourceRange ParensRange = isLeftComp ?
  8701. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  8702. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  8703. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  8704. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  8705. SuggestParentheses(Self, OpLoc,
  8706. Self.PDiag(diag::note_precedence_silence) << OpStr,
  8707. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  8708. SuggestParentheses(Self, OpLoc,
  8709. Self.PDiag(diag::note_precedence_bitwise_first)
  8710. << BinaryOperator::getOpcodeStr(Opc),
  8711. ParensRange);
  8712. }
  8713. /// \brief It accepts a '&' expr that is inside a '|' one.
  8714. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  8715. /// in parentheses.
  8716. static void
  8717. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  8718. BinaryOperator *Bop) {
  8719. assert(Bop->getOpcode() == BO_And);
  8720. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  8721. << Bop->getSourceRange() << OpLoc;
  8722. SuggestParentheses(Self, Bop->getOperatorLoc(),
  8723. Self.PDiag(diag::note_precedence_silence)
  8724. << Bop->getOpcodeStr(),
  8725. Bop->getSourceRange());
  8726. }
  8727. /// \brief It accepts a '&&' expr that is inside a '||' one.
  8728. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  8729. /// in parentheses.
  8730. static void
  8731. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  8732. BinaryOperator *Bop) {
  8733. assert(Bop->getOpcode() == BO_LAnd);
  8734. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  8735. << Bop->getSourceRange() << OpLoc;
  8736. SuggestParentheses(Self, Bop->getOperatorLoc(),
  8737. Self.PDiag(diag::note_precedence_silence)
  8738. << Bop->getOpcodeStr(),
  8739. Bop->getSourceRange());
  8740. }
  8741. /// \brief Returns true if the given expression can be evaluated as a constant
  8742. /// 'true'.
  8743. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  8744. bool Res;
  8745. return !E->isValueDependent() &&
  8746. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  8747. }
  8748. /// \brief Returns true if the given expression can be evaluated as a constant
  8749. /// 'false'.
  8750. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  8751. bool Res;
  8752. return !E->isValueDependent() &&
  8753. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  8754. }
  8755. /// \brief Look for '&&' in the left hand of a '||' expr.
  8756. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  8757. Expr *LHSExpr, Expr *RHSExpr) {
  8758. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  8759. if (Bop->getOpcode() == BO_LAnd) {
  8760. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  8761. if (EvaluatesAsFalse(S, RHSExpr))
  8762. return;
  8763. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  8764. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  8765. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  8766. } else if (Bop->getOpcode() == BO_LOr) {
  8767. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  8768. // If it's "a || b && 1 || c" we didn't warn earlier for
  8769. // "a || b && 1", but warn now.
  8770. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  8771. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  8772. }
  8773. }
  8774. }
  8775. }
  8776. /// \brief Look for '&&' in the right hand of a '||' expr.
  8777. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  8778. Expr *LHSExpr, Expr *RHSExpr) {
  8779. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  8780. if (Bop->getOpcode() == BO_LAnd) {
  8781. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  8782. if (EvaluatesAsFalse(S, LHSExpr))
  8783. return;
  8784. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  8785. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  8786. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  8787. }
  8788. }
  8789. }
  8790. /// \brief Look for '&' in the left or right hand of a '|' expr.
  8791. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  8792. Expr *OrArg) {
  8793. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  8794. if (Bop->getOpcode() == BO_And)
  8795. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  8796. }
  8797. }
  8798. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  8799. Expr *SubExpr, StringRef Shift) {
  8800. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  8801. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  8802. StringRef Op = Bop->getOpcodeStr();
  8803. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  8804. << Bop->getSourceRange() << OpLoc << Shift << Op;
  8805. SuggestParentheses(S, Bop->getOperatorLoc(),
  8806. S.PDiag(diag::note_precedence_silence) << Op,
  8807. Bop->getSourceRange());
  8808. }
  8809. }
  8810. }
  8811. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  8812. Expr *LHSExpr, Expr *RHSExpr) {
  8813. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  8814. if (!OCE)
  8815. return;
  8816. FunctionDecl *FD = OCE->getDirectCallee();
  8817. if (!FD || !FD->isOverloadedOperator())
  8818. return;
  8819. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  8820. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  8821. return;
  8822. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  8823. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  8824. << (Kind == OO_LessLess);
  8825. SuggestParentheses(S, OCE->getOperatorLoc(),
  8826. S.PDiag(diag::note_precedence_silence)
  8827. << (Kind == OO_LessLess ? "<<" : ">>"),
  8828. OCE->getSourceRange());
  8829. SuggestParentheses(S, OpLoc,
  8830. S.PDiag(diag::note_evaluate_comparison_first),
  8831. SourceRange(OCE->getArg(1)->getLocStart(),
  8832. RHSExpr->getLocEnd()));
  8833. }
  8834. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  8835. /// precedence.
  8836. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  8837. SourceLocation OpLoc, Expr *LHSExpr,
  8838. Expr *RHSExpr){
  8839. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  8840. if (BinaryOperator::isBitwiseOp(Opc))
  8841. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  8842. // Diagnose "arg1 & arg2 | arg3"
  8843. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  8844. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  8845. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  8846. }
  8847. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  8848. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  8849. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  8850. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  8851. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  8852. }
  8853. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  8854. || Opc == BO_Shr) {
  8855. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  8856. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  8857. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  8858. }
  8859. // Warn on overloaded shift operators and comparisons, such as:
  8860. // cout << 5 == 4;
  8861. if (BinaryOperator::isComparisonOp(Opc))
  8862. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  8863. }
  8864. // Binary Operators. 'Tok' is the token for the operator.
  8865. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  8866. tok::TokenKind Kind,
  8867. Expr *LHSExpr, Expr *RHSExpr) {
  8868. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  8869. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  8870. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  8871. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  8872. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  8873. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  8874. }
  8875. /// Build an overloaded binary operator expression in the given scope.
  8876. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  8877. BinaryOperatorKind Opc,
  8878. Expr *LHS, Expr *RHS) {
  8879. // Find all of the overloaded operators visible from this
  8880. // point. We perform both an operator-name lookup from the local
  8881. // scope and an argument-dependent lookup based on the types of
  8882. // the arguments.
  8883. UnresolvedSet<16> Functions;
  8884. OverloadedOperatorKind OverOp
  8885. = BinaryOperator::getOverloadedOperator(Opc);
  8886. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  8887. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  8888. RHS->getType(), Functions);
  8889. // Build the (potentially-overloaded, potentially-dependent)
  8890. // binary operation.
  8891. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  8892. }
  8893. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  8894. BinaryOperatorKind Opc,
  8895. Expr *LHSExpr, Expr *RHSExpr) {
  8896. // We want to end up calling one of checkPseudoObjectAssignment
  8897. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  8898. // both expressions are overloadable or either is type-dependent),
  8899. // or CreateBuiltinBinOp (in any other case). We also want to get
  8900. // any placeholder types out of the way.
  8901. // Handle pseudo-objects in the LHS.
  8902. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  8903. // Assignments with a pseudo-object l-value need special analysis.
  8904. if (pty->getKind() == BuiltinType::PseudoObject &&
  8905. BinaryOperator::isAssignmentOp(Opc))
  8906. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  8907. // Don't resolve overloads if the other type is overloadable.
  8908. if (pty->getKind() == BuiltinType::Overload) {
  8909. // We can't actually test that if we still have a placeholder,
  8910. // though. Fortunately, none of the exceptions we see in that
  8911. // code below are valid when the LHS is an overload set. Note
  8912. // that an overload set can be dependently-typed, but it never
  8913. // instantiates to having an overloadable type.
  8914. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  8915. if (resolvedRHS.isInvalid()) return ExprError();
  8916. RHSExpr = resolvedRHS.get();
  8917. if (RHSExpr->isTypeDependent() ||
  8918. RHSExpr->getType()->isOverloadableType())
  8919. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  8920. }
  8921. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  8922. if (LHS.isInvalid()) return ExprError();
  8923. LHSExpr = LHS.get();
  8924. }
  8925. // Handle pseudo-objects in the RHS.
  8926. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  8927. // An overload in the RHS can potentially be resolved by the type
  8928. // being assigned to.
  8929. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  8930. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  8931. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  8932. if (LHSExpr->getType()->isOverloadableType())
  8933. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  8934. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  8935. }
  8936. // Don't resolve overloads if the other type is overloadable.
  8937. if (pty->getKind() == BuiltinType::Overload &&
  8938. LHSExpr->getType()->isOverloadableType())
  8939. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  8940. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  8941. if (!resolvedRHS.isUsable()) return ExprError();
  8942. RHSExpr = resolvedRHS.get();
  8943. }
  8944. if (getLangOpts().CPlusPlus) {
  8945. // If either expression is type-dependent, always build an
  8946. // overloaded op.
  8947. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  8948. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  8949. // Otherwise, build an overloaded op if either expression has an
  8950. // overloadable type.
  8951. if (LHSExpr->getType()->isOverloadableType() ||
  8952. RHSExpr->getType()->isOverloadableType())
  8953. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  8954. }
  8955. // Build a built-in binary operation.
  8956. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  8957. }
  8958. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  8959. UnaryOperatorKind Opc,
  8960. Expr *InputExpr) {
  8961. ExprResult Input = InputExpr;
  8962. ExprValueKind VK = VK_RValue;
  8963. ExprObjectKind OK = OK_Ordinary;
  8964. QualType resultType;
  8965. switch (Opc) {
  8966. case UO_PreInc:
  8967. case UO_PreDec:
  8968. case UO_PostInc:
  8969. case UO_PostDec:
  8970. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  8971. OpLoc,
  8972. Opc == UO_PreInc ||
  8973. Opc == UO_PostInc,
  8974. Opc == UO_PreInc ||
  8975. Opc == UO_PreDec);
  8976. break;
  8977. case UO_AddrOf:
  8978. resultType = CheckAddressOfOperand(Input, OpLoc);
  8979. RecordModifiableNonNullParam(*this, InputExpr);
  8980. break;
  8981. case UO_Deref: {
  8982. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  8983. if (Input.isInvalid()) return ExprError();
  8984. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  8985. break;
  8986. }
  8987. case UO_Plus:
  8988. case UO_Minus:
  8989. Input = UsualUnaryConversions(Input.get());
  8990. if (Input.isInvalid()) return ExprError();
  8991. resultType = Input.get()->getType();
  8992. if (resultType->isDependentType())
  8993. break;
  8994. if (resultType->isArithmeticType() || // C99 6.5.3.3p1
  8995. resultType->isVectorType())
  8996. break;
  8997. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  8998. Opc == UO_Plus &&
  8999. resultType->isPointerType())
  9000. break;
  9001. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9002. << resultType << Input.get()->getSourceRange());
  9003. case UO_Not: // bitwise complement
  9004. Input = UsualUnaryConversions(Input.get());
  9005. if (Input.isInvalid())
  9006. return ExprError();
  9007. resultType = Input.get()->getType();
  9008. if (resultType->isDependentType())
  9009. break;
  9010. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9011. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9012. // C99 does not support '~' for complex conjugation.
  9013. Diag(OpLoc, diag::ext_integer_complement_complex)
  9014. << resultType << Input.get()->getSourceRange();
  9015. else if (resultType->hasIntegerRepresentation())
  9016. break;
  9017. else if (resultType->isExtVectorType()) {
  9018. if (Context.getLangOpts().OpenCL) {
  9019. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9020. // on vector float types.
  9021. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9022. if (!T->isIntegerType())
  9023. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9024. << resultType << Input.get()->getSourceRange());
  9025. }
  9026. break;
  9027. } else {
  9028. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9029. << resultType << Input.get()->getSourceRange());
  9030. }
  9031. break;
  9032. case UO_LNot: // logical negation
  9033. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9034. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9035. if (Input.isInvalid()) return ExprError();
  9036. resultType = Input.get()->getType();
  9037. // Though we still have to promote half FP to float...
  9038. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9039. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9040. resultType = Context.FloatTy;
  9041. }
  9042. if (resultType->isDependentType())
  9043. break;
  9044. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9045. // C99 6.5.3.3p1: ok, fallthrough;
  9046. if (Context.getLangOpts().CPlusPlus) {
  9047. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9048. // operand contextually converted to bool.
  9049. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9050. ScalarTypeToBooleanCastKind(resultType));
  9051. } else if (Context.getLangOpts().OpenCL &&
  9052. Context.getLangOpts().OpenCLVersion < 120) {
  9053. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9054. // operate on scalar float types.
  9055. if (!resultType->isIntegerType())
  9056. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9057. << resultType << Input.get()->getSourceRange());
  9058. }
  9059. } else if (resultType->isExtVectorType()) {
  9060. if (Context.getLangOpts().OpenCL &&
  9061. Context.getLangOpts().OpenCLVersion < 120) {
  9062. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9063. // operate on vector float types.
  9064. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9065. if (!T->isIntegerType())
  9066. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9067. << resultType << Input.get()->getSourceRange());
  9068. }
  9069. // Vector logical not returns the signed variant of the operand type.
  9070. resultType = GetSignedVectorType(resultType);
  9071. break;
  9072. } else {
  9073. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9074. << resultType << Input.get()->getSourceRange());
  9075. }
  9076. // LNot always has type int. C99 6.5.3.3p5.
  9077. // In C++, it's bool. C++ 5.3.1p8
  9078. resultType = Context.getLogicalOperationType();
  9079. break;
  9080. case UO_Real:
  9081. case UO_Imag:
  9082. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9083. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9084. // complex l-values to ordinary l-values and all other values to r-values.
  9085. if (Input.isInvalid()) return ExprError();
  9086. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9087. if (Input.get()->getValueKind() != VK_RValue &&
  9088. Input.get()->getObjectKind() == OK_Ordinary)
  9089. VK = Input.get()->getValueKind();
  9090. } else if (!getLangOpts().CPlusPlus) {
  9091. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9092. Input = DefaultLvalueConversion(Input.get());
  9093. }
  9094. break;
  9095. case UO_Extension:
  9096. resultType = Input.get()->getType();
  9097. VK = Input.get()->getValueKind();
  9098. OK = Input.get()->getObjectKind();
  9099. break;
  9100. }
  9101. if (resultType.isNull() || Input.isInvalid())
  9102. return ExprError();
  9103. // Check for array bounds violations in the operand of the UnaryOperator,
  9104. // except for the '*' and '&' operators that have to be handled specially
  9105. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9106. // that are explicitly defined as valid by the standard).
  9107. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9108. CheckArrayAccess(Input.get());
  9109. return new (Context)
  9110. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9111. }
  9112. /// \brief Determine whether the given expression is a qualified member
  9113. /// access expression, of a form that could be turned into a pointer to member
  9114. /// with the address-of operator.
  9115. static bool isQualifiedMemberAccess(Expr *E) {
  9116. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9117. if (!DRE->getQualifier())
  9118. return false;
  9119. ValueDecl *VD = DRE->getDecl();
  9120. if (!VD->isCXXClassMember())
  9121. return false;
  9122. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9123. return true;
  9124. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9125. return Method->isInstance();
  9126. return false;
  9127. }
  9128. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9129. if (!ULE->getQualifier())
  9130. return false;
  9131. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9132. DEnd = ULE->decls_end();
  9133. D != DEnd; ++D) {
  9134. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9135. if (Method->isInstance())
  9136. return true;
  9137. } else {
  9138. // Overload set does not contain methods.
  9139. break;
  9140. }
  9141. }
  9142. return false;
  9143. }
  9144. return false;
  9145. }
  9146. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9147. UnaryOperatorKind Opc, Expr *Input) {
  9148. // First things first: handle placeholders so that the
  9149. // overloaded-operator check considers the right type.
  9150. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9151. // Increment and decrement of pseudo-object references.
  9152. if (pty->getKind() == BuiltinType::PseudoObject &&
  9153. UnaryOperator::isIncrementDecrementOp(Opc))
  9154. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9155. // extension is always a builtin operator.
  9156. if (Opc == UO_Extension)
  9157. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9158. // & gets special logic for several kinds of placeholder.
  9159. // The builtin code knows what to do.
  9160. if (Opc == UO_AddrOf &&
  9161. (pty->getKind() == BuiltinType::Overload ||
  9162. pty->getKind() == BuiltinType::UnknownAny ||
  9163. pty->getKind() == BuiltinType::BoundMember))
  9164. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9165. // Anything else needs to be handled now.
  9166. ExprResult Result = CheckPlaceholderExpr(Input);
  9167. if (Result.isInvalid()) return ExprError();
  9168. Input = Result.get();
  9169. }
  9170. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9171. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9172. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9173. // Find all of the overloaded operators visible from this
  9174. // point. We perform both an operator-name lookup from the local
  9175. // scope and an argument-dependent lookup based on the types of
  9176. // the arguments.
  9177. UnresolvedSet<16> Functions;
  9178. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9179. if (S && OverOp != OO_None)
  9180. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9181. Functions);
  9182. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9183. }
  9184. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9185. }
  9186. // Unary Operators. 'Tok' is the token for the operator.
  9187. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9188. tok::TokenKind Op, Expr *Input) {
  9189. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9190. }
  9191. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9192. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9193. LabelDecl *TheDecl) {
  9194. TheDecl->markUsed(Context);
  9195. // Create the AST node. The address of a label always has type 'void*'.
  9196. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9197. Context.getPointerType(Context.VoidTy));
  9198. }
  9199. /// Given the last statement in a statement-expression, check whether
  9200. /// the result is a producing expression (like a call to an
  9201. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9202. /// release out of the full-expression. Otherwise, return null.
  9203. /// Cannot fail.
  9204. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9205. // Should always be wrapped with one of these.
  9206. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9207. if (!cleanups) return nullptr;
  9208. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9209. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9210. return nullptr;
  9211. // Splice out the cast. This shouldn't modify any interesting
  9212. // features of the statement.
  9213. Expr *producer = cast->getSubExpr();
  9214. assert(producer->getType() == cast->getType());
  9215. assert(producer->getValueKind() == cast->getValueKind());
  9216. cleanups->setSubExpr(producer);
  9217. return cleanups;
  9218. }
  9219. void Sema::ActOnStartStmtExpr() {
  9220. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9221. }
  9222. void Sema::ActOnStmtExprError() {
  9223. // Note that function is also called by TreeTransform when leaving a
  9224. // StmtExpr scope without rebuilding anything.
  9225. DiscardCleanupsInEvaluationContext();
  9226. PopExpressionEvaluationContext();
  9227. }
  9228. ExprResult
  9229. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9230. SourceLocation RPLoc) { // "({..})"
  9231. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9232. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9233. if (hasAnyUnrecoverableErrorsInThisFunction())
  9234. DiscardCleanupsInEvaluationContext();
  9235. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9236. PopExpressionEvaluationContext();
  9237. // FIXME: there are a variety of strange constraints to enforce here, for
  9238. // example, it is not possible to goto into a stmt expression apparently.
  9239. // More semantic analysis is needed.
  9240. // If there are sub-stmts in the compound stmt, take the type of the last one
  9241. // as the type of the stmtexpr.
  9242. QualType Ty = Context.VoidTy;
  9243. bool StmtExprMayBindToTemp = false;
  9244. if (!Compound->body_empty()) {
  9245. Stmt *LastStmt = Compound->body_back();
  9246. LabelStmt *LastLabelStmt = nullptr;
  9247. // If LastStmt is a label, skip down through into the body.
  9248. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9249. LastLabelStmt = Label;
  9250. LastStmt = Label->getSubStmt();
  9251. }
  9252. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9253. // Do function/array conversion on the last expression, but not
  9254. // lvalue-to-rvalue. However, initialize an unqualified type.
  9255. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9256. if (LastExpr.isInvalid())
  9257. return ExprError();
  9258. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9259. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9260. // In ARC, if the final expression ends in a consume, splice
  9261. // the consume out and bind it later. In the alternate case
  9262. // (when dealing with a retainable type), the result
  9263. // initialization will create a produce. In both cases the
  9264. // result will be +1, and we'll need to balance that out with
  9265. // a bind.
  9266. if (Expr *rebuiltLastStmt
  9267. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9268. LastExpr = rebuiltLastStmt;
  9269. } else {
  9270. LastExpr = PerformCopyInitialization(
  9271. InitializedEntity::InitializeResult(LPLoc,
  9272. Ty,
  9273. false),
  9274. SourceLocation(),
  9275. LastExpr);
  9276. }
  9277. if (LastExpr.isInvalid())
  9278. return ExprError();
  9279. if (LastExpr.get() != nullptr) {
  9280. if (!LastLabelStmt)
  9281. Compound->setLastStmt(LastExpr.get());
  9282. else
  9283. LastLabelStmt->setSubStmt(LastExpr.get());
  9284. StmtExprMayBindToTemp = true;
  9285. }
  9286. }
  9287. }
  9288. }
  9289. // FIXME: Check that expression type is complete/non-abstract; statement
  9290. // expressions are not lvalues.
  9291. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9292. if (StmtExprMayBindToTemp)
  9293. return MaybeBindToTemporary(ResStmtExpr);
  9294. return ResStmtExpr;
  9295. }
  9296. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9297. TypeSourceInfo *TInfo,
  9298. OffsetOfComponent *CompPtr,
  9299. unsigned NumComponents,
  9300. SourceLocation RParenLoc) {
  9301. QualType ArgTy = TInfo->getType();
  9302. bool Dependent = ArgTy->isDependentType();
  9303. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9304. // We must have at least one component that refers to the type, and the first
  9305. // one is known to be a field designator. Verify that the ArgTy represents
  9306. // a struct/union/class.
  9307. if (!Dependent && !ArgTy->isRecordType())
  9308. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9309. << ArgTy << TypeRange);
  9310. // Type must be complete per C99 7.17p3 because a declaring a variable
  9311. // with an incomplete type would be ill-formed.
  9312. if (!Dependent
  9313. && RequireCompleteType(BuiltinLoc, ArgTy,
  9314. diag::err_offsetof_incomplete_type, TypeRange))
  9315. return ExprError();
  9316. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9317. // GCC extension, diagnose them.
  9318. // FIXME: This diagnostic isn't actually visible because the location is in
  9319. // a system header!
  9320. if (NumComponents != 1)
  9321. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9322. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  9323. bool DidWarnAboutNonPOD = false;
  9324. QualType CurrentType = ArgTy;
  9325. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9326. SmallVector<OffsetOfNode, 4> Comps;
  9327. SmallVector<Expr*, 4> Exprs;
  9328. for (unsigned i = 0; i != NumComponents; ++i) {
  9329. const OffsetOfComponent &OC = CompPtr[i];
  9330. if (OC.isBrackets) {
  9331. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9332. if (!CurrentType->isDependentType()) {
  9333. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9334. if(!AT)
  9335. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9336. << CurrentType);
  9337. CurrentType = AT->getElementType();
  9338. } else
  9339. CurrentType = Context.DependentTy;
  9340. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9341. if (IdxRval.isInvalid())
  9342. return ExprError();
  9343. Expr *Idx = IdxRval.get();
  9344. // The expression must be an integral expression.
  9345. // FIXME: An integral constant expression?
  9346. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9347. !Idx->getType()->isIntegerType())
  9348. return ExprError(Diag(Idx->getLocStart(),
  9349. diag::err_typecheck_subscript_not_integer)
  9350. << Idx->getSourceRange());
  9351. // Record this array index.
  9352. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9353. Exprs.push_back(Idx);
  9354. continue;
  9355. }
  9356. // Offset of a field.
  9357. if (CurrentType->isDependentType()) {
  9358. // We have the offset of a field, but we can't look into the dependent
  9359. // type. Just record the identifier of the field.
  9360. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9361. CurrentType = Context.DependentTy;
  9362. continue;
  9363. }
  9364. // We need to have a complete type to look into.
  9365. if (RequireCompleteType(OC.LocStart, CurrentType,
  9366. diag::err_offsetof_incomplete_type))
  9367. return ExprError();
  9368. // Look for the designated field.
  9369. const RecordType *RC = CurrentType->getAs<RecordType>();
  9370. if (!RC)
  9371. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9372. << CurrentType);
  9373. RecordDecl *RD = RC->getDecl();
  9374. // C++ [lib.support.types]p5:
  9375. // The macro offsetof accepts a restricted set of type arguments in this
  9376. // International Standard. type shall be a POD structure or a POD union
  9377. // (clause 9).
  9378. // C++11 [support.types]p4:
  9379. // If type is not a standard-layout class (Clause 9), the results are
  9380. // undefined.
  9381. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9382. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9383. unsigned DiagID =
  9384. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  9385. : diag::ext_offsetof_non_pod_type;
  9386. if (!IsSafe && !DidWarnAboutNonPOD &&
  9387. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  9388. PDiag(DiagID)
  9389. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  9390. << CurrentType))
  9391. DidWarnAboutNonPOD = true;
  9392. }
  9393. // Look for the field.
  9394. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  9395. LookupQualifiedName(R, RD);
  9396. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  9397. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  9398. if (!MemberDecl) {
  9399. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  9400. MemberDecl = IndirectMemberDecl->getAnonField();
  9401. }
  9402. if (!MemberDecl)
  9403. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  9404. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  9405. OC.LocEnd));
  9406. // C99 7.17p3:
  9407. // (If the specified member is a bit-field, the behavior is undefined.)
  9408. //
  9409. // We diagnose this as an error.
  9410. if (MemberDecl->isBitField()) {
  9411. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  9412. << MemberDecl->getDeclName()
  9413. << SourceRange(BuiltinLoc, RParenLoc);
  9414. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  9415. return ExprError();
  9416. }
  9417. RecordDecl *Parent = MemberDecl->getParent();
  9418. if (IndirectMemberDecl)
  9419. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  9420. // If the member was found in a base class, introduce OffsetOfNodes for
  9421. // the base class indirections.
  9422. CXXBasePaths Paths;
  9423. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  9424. if (Paths.getDetectedVirtual()) {
  9425. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  9426. << MemberDecl->getDeclName()
  9427. << SourceRange(BuiltinLoc, RParenLoc);
  9428. return ExprError();
  9429. }
  9430. CXXBasePath &Path = Paths.front();
  9431. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  9432. B != BEnd; ++B)
  9433. Comps.push_back(OffsetOfNode(B->Base));
  9434. }
  9435. if (IndirectMemberDecl) {
  9436. for (auto *FI : IndirectMemberDecl->chain()) {
  9437. assert(isa<FieldDecl>(FI));
  9438. Comps.push_back(OffsetOfNode(OC.LocStart,
  9439. cast<FieldDecl>(FI), OC.LocEnd));
  9440. }
  9441. } else
  9442. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  9443. CurrentType = MemberDecl->getType().getNonReferenceType();
  9444. }
  9445. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  9446. Comps, Exprs, RParenLoc);
  9447. }
  9448. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  9449. SourceLocation BuiltinLoc,
  9450. SourceLocation TypeLoc,
  9451. ParsedType ParsedArgTy,
  9452. OffsetOfComponent *CompPtr,
  9453. unsigned NumComponents,
  9454. SourceLocation RParenLoc) {
  9455. TypeSourceInfo *ArgTInfo;
  9456. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  9457. if (ArgTy.isNull())
  9458. return ExprError();
  9459. if (!ArgTInfo)
  9460. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  9461. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  9462. RParenLoc);
  9463. }
  9464. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  9465. Expr *CondExpr,
  9466. Expr *LHSExpr, Expr *RHSExpr,
  9467. SourceLocation RPLoc) {
  9468. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  9469. ExprValueKind VK = VK_RValue;
  9470. ExprObjectKind OK = OK_Ordinary;
  9471. QualType resType;
  9472. bool ValueDependent = false;
  9473. bool CondIsTrue = false;
  9474. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  9475. resType = Context.DependentTy;
  9476. ValueDependent = true;
  9477. } else {
  9478. // The conditional expression is required to be a constant expression.
  9479. llvm::APSInt condEval(32);
  9480. ExprResult CondICE
  9481. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  9482. diag::err_typecheck_choose_expr_requires_constant, false);
  9483. if (CondICE.isInvalid())
  9484. return ExprError();
  9485. CondExpr = CondICE.get();
  9486. CondIsTrue = condEval.getZExtValue();
  9487. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  9488. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  9489. resType = ActiveExpr->getType();
  9490. ValueDependent = ActiveExpr->isValueDependent();
  9491. VK = ActiveExpr->getValueKind();
  9492. OK = ActiveExpr->getObjectKind();
  9493. }
  9494. return new (Context)
  9495. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  9496. CondIsTrue, resType->isDependentType(), ValueDependent);
  9497. }
  9498. //===----------------------------------------------------------------------===//
  9499. // Clang Extensions.
  9500. //===----------------------------------------------------------------------===//
  9501. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  9502. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  9503. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  9504. if (LangOpts.CPlusPlus) {
  9505. Decl *ManglingContextDecl;
  9506. if (MangleNumberingContext *MCtx =
  9507. getCurrentMangleNumberContext(Block->getDeclContext(),
  9508. ManglingContextDecl)) {
  9509. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  9510. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  9511. }
  9512. }
  9513. PushBlockScope(CurScope, Block);
  9514. CurContext->addDecl(Block);
  9515. if (CurScope)
  9516. PushDeclContext(CurScope, Block);
  9517. else
  9518. CurContext = Block;
  9519. getCurBlock()->HasImplicitReturnType = true;
  9520. // Enter a new evaluation context to insulate the block from any
  9521. // cleanups from the enclosing full-expression.
  9522. PushExpressionEvaluationContext(PotentiallyEvaluated);
  9523. }
  9524. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  9525. Scope *CurScope) {
  9526. assert(ParamInfo.getIdentifier() == nullptr &&
  9527. "block-id should have no identifier!");
  9528. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  9529. BlockScopeInfo *CurBlock = getCurBlock();
  9530. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  9531. QualType T = Sig->getType();
  9532. // FIXME: We should allow unexpanded parameter packs here, but that would,
  9533. // in turn, make the block expression contain unexpanded parameter packs.
  9534. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  9535. // Drop the parameters.
  9536. FunctionProtoType::ExtProtoInfo EPI;
  9537. EPI.HasTrailingReturn = false;
  9538. EPI.TypeQuals |= DeclSpec::TQ_const;
  9539. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  9540. Sig = Context.getTrivialTypeSourceInfo(T);
  9541. }
  9542. // GetTypeForDeclarator always produces a function type for a block
  9543. // literal signature. Furthermore, it is always a FunctionProtoType
  9544. // unless the function was written with a typedef.
  9545. assert(T->isFunctionType() &&
  9546. "GetTypeForDeclarator made a non-function block signature");
  9547. // Look for an explicit signature in that function type.
  9548. FunctionProtoTypeLoc ExplicitSignature;
  9549. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  9550. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  9551. // Check whether that explicit signature was synthesized by
  9552. // GetTypeForDeclarator. If so, don't save that as part of the
  9553. // written signature.
  9554. if (ExplicitSignature.getLocalRangeBegin() ==
  9555. ExplicitSignature.getLocalRangeEnd()) {
  9556. // This would be much cheaper if we stored TypeLocs instead of
  9557. // TypeSourceInfos.
  9558. TypeLoc Result = ExplicitSignature.getReturnLoc();
  9559. unsigned Size = Result.getFullDataSize();
  9560. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  9561. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  9562. ExplicitSignature = FunctionProtoTypeLoc();
  9563. }
  9564. }
  9565. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  9566. CurBlock->FunctionType = T;
  9567. const FunctionType *Fn = T->getAs<FunctionType>();
  9568. QualType RetTy = Fn->getReturnType();
  9569. bool isVariadic =
  9570. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  9571. CurBlock->TheDecl->setIsVariadic(isVariadic);
  9572. // Context.DependentTy is used as a placeholder for a missing block
  9573. // return type. TODO: what should we do with declarators like:
  9574. // ^ * { ... }
  9575. // If the answer is "apply template argument deduction"....
  9576. if (RetTy != Context.DependentTy) {
  9577. CurBlock->ReturnType = RetTy;
  9578. CurBlock->TheDecl->setBlockMissingReturnType(false);
  9579. CurBlock->HasImplicitReturnType = false;
  9580. }
  9581. // Push block parameters from the declarator if we had them.
  9582. SmallVector<ParmVarDecl*, 8> Params;
  9583. if (ExplicitSignature) {
  9584. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  9585. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  9586. if (Param->getIdentifier() == nullptr &&
  9587. !Param->isImplicit() &&
  9588. !Param->isInvalidDecl() &&
  9589. !getLangOpts().CPlusPlus)
  9590. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  9591. Params.push_back(Param);
  9592. }
  9593. // Fake up parameter variables if we have a typedef, like
  9594. // ^ fntype { ... }
  9595. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  9596. for (const auto &I : Fn->param_types()) {
  9597. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  9598. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  9599. Params.push_back(Param);
  9600. }
  9601. }
  9602. // Set the parameters on the block decl.
  9603. if (!Params.empty()) {
  9604. CurBlock->TheDecl->setParams(Params);
  9605. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  9606. CurBlock->TheDecl->param_end(),
  9607. /*CheckParameterNames=*/false);
  9608. }
  9609. // Finally we can process decl attributes.
  9610. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  9611. // Put the parameter variables in scope.
  9612. for (auto AI : CurBlock->TheDecl->params()) {
  9613. AI->setOwningFunction(CurBlock->TheDecl);
  9614. // If this has an identifier, add it to the scope stack.
  9615. if (AI->getIdentifier()) {
  9616. CheckShadow(CurBlock->TheScope, AI);
  9617. PushOnScopeChains(AI, CurBlock->TheScope);
  9618. }
  9619. }
  9620. }
  9621. /// ActOnBlockError - If there is an error parsing a block, this callback
  9622. /// is invoked to pop the information about the block from the action impl.
  9623. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  9624. // Leave the expression-evaluation context.
  9625. DiscardCleanupsInEvaluationContext();
  9626. PopExpressionEvaluationContext();
  9627. // Pop off CurBlock, handle nested blocks.
  9628. PopDeclContext();
  9629. PopFunctionScopeInfo();
  9630. }
  9631. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  9632. /// literal was successfully completed. ^(int x){...}
  9633. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  9634. Stmt *Body, Scope *CurScope) {
  9635. // If blocks are disabled, emit an error.
  9636. if (!LangOpts.Blocks)
  9637. Diag(CaretLoc, diag::err_blocks_disable);
  9638. // Leave the expression-evaluation context.
  9639. if (hasAnyUnrecoverableErrorsInThisFunction())
  9640. DiscardCleanupsInEvaluationContext();
  9641. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  9642. PopExpressionEvaluationContext();
  9643. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  9644. if (BSI->HasImplicitReturnType)
  9645. deduceClosureReturnType(*BSI);
  9646. PopDeclContext();
  9647. QualType RetTy = Context.VoidTy;
  9648. if (!BSI->ReturnType.isNull())
  9649. RetTy = BSI->ReturnType;
  9650. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  9651. QualType BlockTy;
  9652. // Set the captured variables on the block.
  9653. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  9654. SmallVector<BlockDecl::Capture, 4> Captures;
  9655. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  9656. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  9657. if (Cap.isThisCapture())
  9658. continue;
  9659. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  9660. Cap.isNested(), Cap.getInitExpr());
  9661. Captures.push_back(NewCap);
  9662. }
  9663. BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
  9664. BSI->CXXThisCaptureIndex != 0);
  9665. // If the user wrote a function type in some form, try to use that.
  9666. if (!BSI->FunctionType.isNull()) {
  9667. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  9668. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  9669. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  9670. // Turn protoless block types into nullary block types.
  9671. if (isa<FunctionNoProtoType>(FTy)) {
  9672. FunctionProtoType::ExtProtoInfo EPI;
  9673. EPI.ExtInfo = Ext;
  9674. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  9675. // Otherwise, if we don't need to change anything about the function type,
  9676. // preserve its sugar structure.
  9677. } else if (FTy->getReturnType() == RetTy &&
  9678. (!NoReturn || FTy->getNoReturnAttr())) {
  9679. BlockTy = BSI->FunctionType;
  9680. // Otherwise, make the minimal modifications to the function type.
  9681. } else {
  9682. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  9683. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9684. EPI.TypeQuals = 0; // FIXME: silently?
  9685. EPI.ExtInfo = Ext;
  9686. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  9687. }
  9688. // If we don't have a function type, just build one from nothing.
  9689. } else {
  9690. FunctionProtoType::ExtProtoInfo EPI;
  9691. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  9692. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  9693. }
  9694. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  9695. BSI->TheDecl->param_end());
  9696. BlockTy = Context.getBlockPointerType(BlockTy);
  9697. // If needed, diagnose invalid gotos and switches in the block.
  9698. if (getCurFunction()->NeedsScopeChecking() &&
  9699. !PP.isCodeCompletionEnabled())
  9700. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  9701. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  9702. // Try to apply the named return value optimization. We have to check again
  9703. // if we can do this, though, because blocks keep return statements around
  9704. // to deduce an implicit return type.
  9705. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  9706. !BSI->TheDecl->isDependentContext())
  9707. computeNRVO(Body, BSI);
  9708. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  9709. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  9710. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  9711. // If the block isn't obviously global, i.e. it captures anything at
  9712. // all, then we need to do a few things in the surrounding context:
  9713. if (Result->getBlockDecl()->hasCaptures()) {
  9714. // First, this expression has a new cleanup object.
  9715. ExprCleanupObjects.push_back(Result->getBlockDecl());
  9716. ExprNeedsCleanups = true;
  9717. // It also gets a branch-protected scope if any of the captured
  9718. // variables needs destruction.
  9719. for (const auto &CI : Result->getBlockDecl()->captures()) {
  9720. const VarDecl *var = CI.getVariable();
  9721. if (var->getType().isDestructedType() != QualType::DK_none) {
  9722. getCurFunction()->setHasBranchProtectedScope();
  9723. break;
  9724. }
  9725. }
  9726. }
  9727. return Result;
  9728. }
  9729. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  9730. Expr *E, ParsedType Ty,
  9731. SourceLocation RPLoc) {
  9732. TypeSourceInfo *TInfo;
  9733. GetTypeFromParser(Ty, &TInfo);
  9734. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  9735. }
  9736. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  9737. Expr *E, TypeSourceInfo *TInfo,
  9738. SourceLocation RPLoc) {
  9739. Expr *OrigExpr = E;
  9740. // Get the va_list type
  9741. QualType VaListType = Context.getBuiltinVaListType();
  9742. if (VaListType->isArrayType()) {
  9743. // Deal with implicit array decay; for example, on x86-64,
  9744. // va_list is an array, but it's supposed to decay to
  9745. // a pointer for va_arg.
  9746. VaListType = Context.getArrayDecayedType(VaListType);
  9747. // Make sure the input expression also decays appropriately.
  9748. ExprResult Result = UsualUnaryConversions(E);
  9749. if (Result.isInvalid())
  9750. return ExprError();
  9751. E = Result.get();
  9752. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  9753. // If va_list is a record type and we are compiling in C++ mode,
  9754. // check the argument using reference binding.
  9755. InitializedEntity Entity
  9756. = InitializedEntity::InitializeParameter(Context,
  9757. Context.getLValueReferenceType(VaListType), false);
  9758. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  9759. if (Init.isInvalid())
  9760. return ExprError();
  9761. E = Init.getAs<Expr>();
  9762. } else {
  9763. // Otherwise, the va_list argument must be an l-value because
  9764. // it is modified by va_arg.
  9765. if (!E->isTypeDependent() &&
  9766. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  9767. return ExprError();
  9768. }
  9769. if (!E->isTypeDependent() &&
  9770. !Context.hasSameType(VaListType, E->getType())) {
  9771. return ExprError(Diag(E->getLocStart(),
  9772. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  9773. << OrigExpr->getType() << E->getSourceRange());
  9774. }
  9775. if (!TInfo->getType()->isDependentType()) {
  9776. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  9777. diag::err_second_parameter_to_va_arg_incomplete,
  9778. TInfo->getTypeLoc()))
  9779. return ExprError();
  9780. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  9781. TInfo->getType(),
  9782. diag::err_second_parameter_to_va_arg_abstract,
  9783. TInfo->getTypeLoc()))
  9784. return ExprError();
  9785. if (!TInfo->getType().isPODType(Context)) {
  9786. Diag(TInfo->getTypeLoc().getBeginLoc(),
  9787. TInfo->getType()->isObjCLifetimeType()
  9788. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  9789. : diag::warn_second_parameter_to_va_arg_not_pod)
  9790. << TInfo->getType()
  9791. << TInfo->getTypeLoc().getSourceRange();
  9792. }
  9793. // Check for va_arg where arguments of the given type will be promoted
  9794. // (i.e. this va_arg is guaranteed to have undefined behavior).
  9795. QualType PromoteType;
  9796. if (TInfo->getType()->isPromotableIntegerType()) {
  9797. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  9798. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  9799. PromoteType = QualType();
  9800. }
  9801. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  9802. PromoteType = Context.DoubleTy;
  9803. if (!PromoteType.isNull())
  9804. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  9805. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  9806. << TInfo->getType()
  9807. << PromoteType
  9808. << TInfo->getTypeLoc().getSourceRange());
  9809. }
  9810. QualType T = TInfo->getType().getNonLValueExprType(Context);
  9811. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
  9812. }
  9813. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  9814. // The type of __null will be int or long, depending on the size of
  9815. // pointers on the target.
  9816. QualType Ty;
  9817. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  9818. if (pw == Context.getTargetInfo().getIntWidth())
  9819. Ty = Context.IntTy;
  9820. else if (pw == Context.getTargetInfo().getLongWidth())
  9821. Ty = Context.LongTy;
  9822. else if (pw == Context.getTargetInfo().getLongLongWidth())
  9823. Ty = Context.LongLongTy;
  9824. else {
  9825. llvm_unreachable("I don't know size of pointer!");
  9826. }
  9827. return new (Context) GNUNullExpr(Ty, TokenLoc);
  9828. }
  9829. bool
  9830. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  9831. if (!getLangOpts().ObjC1)
  9832. return false;
  9833. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  9834. if (!PT)
  9835. return false;
  9836. if (!PT->isObjCIdType()) {
  9837. // Check if the destination is the 'NSString' interface.
  9838. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  9839. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  9840. return false;
  9841. }
  9842. // Ignore any parens, implicit casts (should only be
  9843. // array-to-pointer decays), and not-so-opaque values. The last is
  9844. // important for making this trigger for property assignments.
  9845. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  9846. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  9847. if (OV->getSourceExpr())
  9848. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  9849. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  9850. if (!SL || !SL->isAscii())
  9851. return false;
  9852. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  9853. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  9854. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  9855. return true;
  9856. }
  9857. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  9858. SourceLocation Loc,
  9859. QualType DstType, QualType SrcType,
  9860. Expr *SrcExpr, AssignmentAction Action,
  9861. bool *Complained) {
  9862. if (Complained)
  9863. *Complained = false;
  9864. // Decode the result (notice that AST's are still created for extensions).
  9865. bool CheckInferredResultType = false;
  9866. bool isInvalid = false;
  9867. unsigned DiagKind = 0;
  9868. FixItHint Hint;
  9869. ConversionFixItGenerator ConvHints;
  9870. bool MayHaveConvFixit = false;
  9871. bool MayHaveFunctionDiff = false;
  9872. const ObjCInterfaceDecl *IFace = nullptr;
  9873. const ObjCProtocolDecl *PDecl = nullptr;
  9874. switch (ConvTy) {
  9875. case Compatible:
  9876. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  9877. return false;
  9878. case PointerToInt:
  9879. DiagKind = diag::ext_typecheck_convert_pointer_int;
  9880. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  9881. MayHaveConvFixit = true;
  9882. break;
  9883. case IntToPointer:
  9884. DiagKind = diag::ext_typecheck_convert_int_pointer;
  9885. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  9886. MayHaveConvFixit = true;
  9887. break;
  9888. case IncompatiblePointer:
  9889. DiagKind =
  9890. (Action == AA_Passing_CFAudited ?
  9891. diag::err_arc_typecheck_convert_incompatible_pointer :
  9892. diag::ext_typecheck_convert_incompatible_pointer);
  9893. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  9894. SrcType->isObjCObjectPointerType();
  9895. if (Hint.isNull() && !CheckInferredResultType) {
  9896. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  9897. }
  9898. else if (CheckInferredResultType) {
  9899. SrcType = SrcType.getUnqualifiedType();
  9900. DstType = DstType.getUnqualifiedType();
  9901. }
  9902. MayHaveConvFixit = true;
  9903. break;
  9904. case IncompatiblePointerSign:
  9905. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  9906. break;
  9907. case FunctionVoidPointer:
  9908. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  9909. break;
  9910. case IncompatiblePointerDiscardsQualifiers: {
  9911. // Perform array-to-pointer decay if necessary.
  9912. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  9913. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  9914. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  9915. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  9916. DiagKind = diag::err_typecheck_incompatible_address_space;
  9917. break;
  9918. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  9919. DiagKind = diag::err_typecheck_incompatible_ownership;
  9920. break;
  9921. }
  9922. llvm_unreachable("unknown error case for discarding qualifiers!");
  9923. // fallthrough
  9924. }
  9925. case CompatiblePointerDiscardsQualifiers:
  9926. // If the qualifiers lost were because we were applying the
  9927. // (deprecated) C++ conversion from a string literal to a char*
  9928. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  9929. // Ideally, this check would be performed in
  9930. // checkPointerTypesForAssignment. However, that would require a
  9931. // bit of refactoring (so that the second argument is an
  9932. // expression, rather than a type), which should be done as part
  9933. // of a larger effort to fix checkPointerTypesForAssignment for
  9934. // C++ semantics.
  9935. if (getLangOpts().CPlusPlus &&
  9936. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  9937. return false;
  9938. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  9939. break;
  9940. case IncompatibleNestedPointerQualifiers:
  9941. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  9942. break;
  9943. case IntToBlockPointer:
  9944. DiagKind = diag::err_int_to_block_pointer;
  9945. break;
  9946. case IncompatibleBlockPointer:
  9947. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  9948. break;
  9949. case IncompatibleObjCQualifiedId: {
  9950. if (SrcType->isObjCQualifiedIdType()) {
  9951. const ObjCObjectPointerType *srcOPT =
  9952. SrcType->getAs<ObjCObjectPointerType>();
  9953. for (auto *srcProto : srcOPT->quals()) {
  9954. PDecl = srcProto;
  9955. break;
  9956. }
  9957. if (const ObjCInterfaceType *IFaceT =
  9958. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  9959. IFace = IFaceT->getDecl();
  9960. }
  9961. else if (DstType->isObjCQualifiedIdType()) {
  9962. const ObjCObjectPointerType *dstOPT =
  9963. DstType->getAs<ObjCObjectPointerType>();
  9964. for (auto *dstProto : dstOPT->quals()) {
  9965. PDecl = dstProto;
  9966. break;
  9967. }
  9968. if (const ObjCInterfaceType *IFaceT =
  9969. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  9970. IFace = IFaceT->getDecl();
  9971. }
  9972. DiagKind = diag::warn_incompatible_qualified_id;
  9973. break;
  9974. }
  9975. case IncompatibleVectors:
  9976. DiagKind = diag::warn_incompatible_vectors;
  9977. break;
  9978. case IncompatibleObjCWeakRef:
  9979. DiagKind = diag::err_arc_weak_unavailable_assign;
  9980. break;
  9981. case Incompatible:
  9982. DiagKind = diag::err_typecheck_convert_incompatible;
  9983. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  9984. MayHaveConvFixit = true;
  9985. isInvalid = true;
  9986. MayHaveFunctionDiff = true;
  9987. break;
  9988. }
  9989. QualType FirstType, SecondType;
  9990. switch (Action) {
  9991. case AA_Assigning:
  9992. case AA_Initializing:
  9993. // The destination type comes first.
  9994. FirstType = DstType;
  9995. SecondType = SrcType;
  9996. break;
  9997. case AA_Returning:
  9998. case AA_Passing:
  9999. case AA_Passing_CFAudited:
  10000. case AA_Converting:
  10001. case AA_Sending:
  10002. case AA_Casting:
  10003. // The source type comes first.
  10004. FirstType = SrcType;
  10005. SecondType = DstType;
  10006. break;
  10007. }
  10008. PartialDiagnostic FDiag = PDiag(DiagKind);
  10009. if (Action == AA_Passing_CFAudited)
  10010. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10011. else
  10012. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10013. // If we can fix the conversion, suggest the FixIts.
  10014. assert(ConvHints.isNull() || Hint.isNull());
  10015. if (!ConvHints.isNull()) {
  10016. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10017. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10018. FDiag << *HI;
  10019. } else {
  10020. FDiag << Hint;
  10021. }
  10022. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10023. if (MayHaveFunctionDiff)
  10024. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10025. Diag(Loc, FDiag);
  10026. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10027. PDecl && IFace && !IFace->hasDefinition())
  10028. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10029. << IFace->getName() << PDecl->getName();
  10030. if (SecondType == Context.OverloadTy)
  10031. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10032. FirstType);
  10033. if (CheckInferredResultType)
  10034. EmitRelatedResultTypeNote(SrcExpr);
  10035. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10036. EmitRelatedResultTypeNoteForReturn(DstType);
  10037. if (Complained)
  10038. *Complained = true;
  10039. return isInvalid;
  10040. }
  10041. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10042. llvm::APSInt *Result) {
  10043. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10044. public:
  10045. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10046. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10047. }
  10048. } Diagnoser;
  10049. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10050. }
  10051. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10052. llvm::APSInt *Result,
  10053. unsigned DiagID,
  10054. bool AllowFold) {
  10055. class IDDiagnoser : public VerifyICEDiagnoser {
  10056. unsigned DiagID;
  10057. public:
  10058. IDDiagnoser(unsigned DiagID)
  10059. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10060. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10061. S.Diag(Loc, DiagID) << SR;
  10062. }
  10063. } Diagnoser(DiagID);
  10064. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10065. }
  10066. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10067. SourceRange SR) {
  10068. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10069. }
  10070. ExprResult
  10071. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10072. VerifyICEDiagnoser &Diagnoser,
  10073. bool AllowFold) {
  10074. SourceLocation DiagLoc = E->getLocStart();
  10075. if (getLangOpts().CPlusPlus11) {
  10076. // C++11 [expr.const]p5:
  10077. // If an expression of literal class type is used in a context where an
  10078. // integral constant expression is required, then that class type shall
  10079. // have a single non-explicit conversion function to an integral or
  10080. // unscoped enumeration type
  10081. ExprResult Converted;
  10082. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10083. public:
  10084. CXX11ConvertDiagnoser(bool Silent)
  10085. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10086. Silent, true) {}
  10087. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10088. QualType T) override {
  10089. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10090. }
  10091. SemaDiagnosticBuilder diagnoseIncomplete(
  10092. Sema &S, SourceLocation Loc, QualType T) override {
  10093. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10094. }
  10095. SemaDiagnosticBuilder diagnoseExplicitConv(
  10096. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10097. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10098. }
  10099. SemaDiagnosticBuilder noteExplicitConv(
  10100. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10101. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10102. << ConvTy->isEnumeralType() << ConvTy;
  10103. }
  10104. SemaDiagnosticBuilder diagnoseAmbiguous(
  10105. Sema &S, SourceLocation Loc, QualType T) override {
  10106. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10107. }
  10108. SemaDiagnosticBuilder noteAmbiguous(
  10109. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10110. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10111. << ConvTy->isEnumeralType() << ConvTy;
  10112. }
  10113. SemaDiagnosticBuilder diagnoseConversion(
  10114. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10115. llvm_unreachable("conversion functions are permitted");
  10116. }
  10117. } ConvertDiagnoser(Diagnoser.Suppress);
  10118. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10119. ConvertDiagnoser);
  10120. if (Converted.isInvalid())
  10121. return Converted;
  10122. E = Converted.get();
  10123. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10124. return ExprError();
  10125. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10126. // An ICE must be of integral or unscoped enumeration type.
  10127. if (!Diagnoser.Suppress)
  10128. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10129. return ExprError();
  10130. }
  10131. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10132. // in the non-ICE case.
  10133. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10134. if (Result)
  10135. *Result = E->EvaluateKnownConstInt(Context);
  10136. return E;
  10137. }
  10138. Expr::EvalResult EvalResult;
  10139. SmallVector<PartialDiagnosticAt, 8> Notes;
  10140. EvalResult.Diag = &Notes;
  10141. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10142. // not a constant expression as a side-effect.
  10143. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10144. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10145. // In C++11, we can rely on diagnostics being produced for any expression
  10146. // which is not a constant expression. If no diagnostics were produced, then
  10147. // this is a constant expression.
  10148. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10149. if (Result)
  10150. *Result = EvalResult.Val.getInt();
  10151. return E;
  10152. }
  10153. // If our only note is the usual "invalid subexpression" note, just point
  10154. // the caret at its location rather than producing an essentially
  10155. // redundant note.
  10156. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10157. diag::note_invalid_subexpr_in_const_expr) {
  10158. DiagLoc = Notes[0].first;
  10159. Notes.clear();
  10160. }
  10161. if (!Folded || !AllowFold) {
  10162. if (!Diagnoser.Suppress) {
  10163. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10164. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10165. Diag(Notes[I].first, Notes[I].second);
  10166. }
  10167. return ExprError();
  10168. }
  10169. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10170. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10171. Diag(Notes[I].first, Notes[I].second);
  10172. if (Result)
  10173. *Result = EvalResult.Val.getInt();
  10174. return E;
  10175. }
  10176. namespace {
  10177. // Handle the case where we conclude a expression which we speculatively
  10178. // considered to be unevaluated is actually evaluated.
  10179. class TransformToPE : public TreeTransform<TransformToPE> {
  10180. typedef TreeTransform<TransformToPE> BaseTransform;
  10181. public:
  10182. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10183. // Make sure we redo semantic analysis
  10184. bool AlwaysRebuild() { return true; }
  10185. // Make sure we handle LabelStmts correctly.
  10186. // FIXME: This does the right thing, but maybe we need a more general
  10187. // fix to TreeTransform?
  10188. StmtResult TransformLabelStmt(LabelStmt *S) {
  10189. S->getDecl()->setStmt(nullptr);
  10190. return BaseTransform::TransformLabelStmt(S);
  10191. }
  10192. // We need to special-case DeclRefExprs referring to FieldDecls which
  10193. // are not part of a member pointer formation; normal TreeTransforming
  10194. // doesn't catch this case because of the way we represent them in the AST.
  10195. // FIXME: This is a bit ugly; is it really the best way to handle this
  10196. // case?
  10197. //
  10198. // Error on DeclRefExprs referring to FieldDecls.
  10199. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10200. if (isa<FieldDecl>(E->getDecl()) &&
  10201. !SemaRef.isUnevaluatedContext())
  10202. return SemaRef.Diag(E->getLocation(),
  10203. diag::err_invalid_non_static_member_use)
  10204. << E->getDecl() << E->getSourceRange();
  10205. return BaseTransform::TransformDeclRefExpr(E);
  10206. }
  10207. // Exception: filter out member pointer formation
  10208. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10209. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10210. return E;
  10211. return BaseTransform::TransformUnaryOperator(E);
  10212. }
  10213. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10214. // Lambdas never need to be transformed.
  10215. return E;
  10216. }
  10217. };
  10218. }
  10219. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10220. assert(isUnevaluatedContext() &&
  10221. "Should only transform unevaluated expressions");
  10222. ExprEvalContexts.back().Context =
  10223. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10224. if (isUnevaluatedContext())
  10225. return E;
  10226. return TransformToPE(*this).TransformExpr(E);
  10227. }
  10228. void
  10229. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10230. Decl *LambdaContextDecl,
  10231. bool IsDecltype) {
  10232. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10233. ExprNeedsCleanups, LambdaContextDecl,
  10234. IsDecltype);
  10235. ExprNeedsCleanups = false;
  10236. if (!MaybeODRUseExprs.empty())
  10237. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10238. }
  10239. void
  10240. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10241. ReuseLambdaContextDecl_t,
  10242. bool IsDecltype) {
  10243. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10244. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10245. }
  10246. void Sema::PopExpressionEvaluationContext() {
  10247. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10248. unsigned NumTypos = Rec.NumTypos;
  10249. if (!Rec.Lambdas.empty()) {
  10250. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10251. unsigned D;
  10252. if (Rec.isUnevaluated()) {
  10253. // C++11 [expr.prim.lambda]p2:
  10254. // A lambda-expression shall not appear in an unevaluated operand
  10255. // (Clause 5).
  10256. D = diag::err_lambda_unevaluated_operand;
  10257. } else {
  10258. // C++1y [expr.const]p2:
  10259. // A conditional-expression e is a core constant expression unless the
  10260. // evaluation of e, following the rules of the abstract machine, would
  10261. // evaluate [...] a lambda-expression.
  10262. D = diag::err_lambda_in_constant_expression;
  10263. }
  10264. for (const auto *L : Rec.Lambdas)
  10265. Diag(L->getLocStart(), D);
  10266. } else {
  10267. // Mark the capture expressions odr-used. This was deferred
  10268. // during lambda expression creation.
  10269. for (auto *Lambda : Rec.Lambdas) {
  10270. for (auto *C : Lambda->capture_inits())
  10271. MarkDeclarationsReferencedInExpr(C);
  10272. }
  10273. }
  10274. }
  10275. // When are coming out of an unevaluated context, clear out any
  10276. // temporaries that we may have created as part of the evaluation of
  10277. // the expression in that context: they aren't relevant because they
  10278. // will never be constructed.
  10279. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10280. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10281. ExprCleanupObjects.end());
  10282. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10283. CleanupVarDeclMarking();
  10284. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10285. // Otherwise, merge the contexts together.
  10286. } else {
  10287. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10288. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10289. Rec.SavedMaybeODRUseExprs.end());
  10290. }
  10291. // Pop the current expression evaluation context off the stack.
  10292. ExprEvalContexts.pop_back();
  10293. if (!ExprEvalContexts.empty())
  10294. ExprEvalContexts.back().NumTypos += NumTypos;
  10295. else
  10296. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10297. "last ExpressionEvaluationContextRecord");
  10298. }
  10299. void Sema::DiscardCleanupsInEvaluationContext() {
  10300. ExprCleanupObjects.erase(
  10301. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10302. ExprCleanupObjects.end());
  10303. ExprNeedsCleanups = false;
  10304. MaybeODRUseExprs.clear();
  10305. }
  10306. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10307. if (!E->getType()->isVariablyModifiedType())
  10308. return E;
  10309. return TransformToPotentiallyEvaluated(E);
  10310. }
  10311. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10312. // Do not mark anything as "used" within a dependent context; wait for
  10313. // an instantiation.
  10314. if (SemaRef.CurContext->isDependentContext())
  10315. return false;
  10316. switch (SemaRef.ExprEvalContexts.back().Context) {
  10317. case Sema::Unevaluated:
  10318. case Sema::UnevaluatedAbstract:
  10319. // We are in an expression that is not potentially evaluated; do nothing.
  10320. // (Depending on how you read the standard, we actually do need to do
  10321. // something here for null pointer constants, but the standard's
  10322. // definition of a null pointer constant is completely crazy.)
  10323. return false;
  10324. case Sema::ConstantEvaluated:
  10325. case Sema::PotentiallyEvaluated:
  10326. // We are in a potentially evaluated expression (or a constant-expression
  10327. // in C++03); we need to do implicit template instantiation, implicitly
  10328. // define class members, and mark most declarations as used.
  10329. return true;
  10330. case Sema::PotentiallyEvaluatedIfUsed:
  10331. // Referenced declarations will only be used if the construct in the
  10332. // containing expression is used.
  10333. return false;
  10334. }
  10335. llvm_unreachable("Invalid context");
  10336. }
  10337. /// \brief Mark a function referenced, and check whether it is odr-used
  10338. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10339. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10340. bool OdrUse) {
  10341. assert(Func && "No function?");
  10342. Func->setReferenced();
  10343. // C++11 [basic.def.odr]p3:
  10344. // A function whose name appears as a potentially-evaluated expression is
  10345. // odr-used if it is the unique lookup result or the selected member of a
  10346. // set of overloaded functions [...].
  10347. //
  10348. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10349. // can just check that here. Skip the rest of this function if we've already
  10350. // marked the function as used.
  10351. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10352. !IsPotentiallyEvaluatedContext(*this)) {
  10353. // C++11 [temp.inst]p3:
  10354. // Unless a function template specialization has been explicitly
  10355. // instantiated or explicitly specialized, the function template
  10356. // specialization is implicitly instantiated when the specialization is
  10357. // referenced in a context that requires a function definition to exist.
  10358. //
  10359. // We consider constexpr function templates to be referenced in a context
  10360. // that requires a definition to exist whenever they are referenced.
  10361. //
  10362. // FIXME: This instantiates constexpr functions too frequently. If this is
  10363. // really an unevaluated context (and we're not just in the definition of a
  10364. // function template or overload resolution or other cases which we
  10365. // incorrectly consider to be unevaluated contexts), and we're not in a
  10366. // subexpression which we actually need to evaluate (for instance, a
  10367. // template argument, array bound or an expression in a braced-init-list),
  10368. // we are not permitted to instantiate this constexpr function definition.
  10369. //
  10370. // FIXME: This also implicitly defines special members too frequently. They
  10371. // are only supposed to be implicitly defined if they are odr-used, but they
  10372. // are not odr-used from constant expressions in unevaluated contexts.
  10373. // However, they cannot be referenced if they are deleted, and they are
  10374. // deleted whenever the implicit definition of the special member would
  10375. // fail.
  10376. if (!Func->isConstexpr() || Func->getBody())
  10377. return;
  10378. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  10379. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  10380. return;
  10381. }
  10382. // Note that this declaration has been used.
  10383. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  10384. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  10385. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  10386. if (Constructor->isDefaultConstructor()) {
  10387. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  10388. return;
  10389. DefineImplicitDefaultConstructor(Loc, Constructor);
  10390. } else if (Constructor->isCopyConstructor()) {
  10391. DefineImplicitCopyConstructor(Loc, Constructor);
  10392. } else if (Constructor->isMoveConstructor()) {
  10393. DefineImplicitMoveConstructor(Loc, Constructor);
  10394. }
  10395. } else if (Constructor->getInheritedConstructor()) {
  10396. DefineInheritingConstructor(Loc, Constructor);
  10397. }
  10398. } else if (CXXDestructorDecl *Destructor =
  10399. dyn_cast<CXXDestructorDecl>(Func)) {
  10400. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  10401. if (Destructor->isDefaulted() && !Destructor->isDeleted())
  10402. DefineImplicitDestructor(Loc, Destructor);
  10403. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  10404. MarkVTableUsed(Loc, Destructor->getParent());
  10405. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  10406. if (MethodDecl->isOverloadedOperator() &&
  10407. MethodDecl->getOverloadedOperator() == OO_Equal) {
  10408. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  10409. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  10410. if (MethodDecl->isCopyAssignmentOperator())
  10411. DefineImplicitCopyAssignment(Loc, MethodDecl);
  10412. else
  10413. DefineImplicitMoveAssignment(Loc, MethodDecl);
  10414. }
  10415. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  10416. MethodDecl->getParent()->isLambda()) {
  10417. CXXConversionDecl *Conversion =
  10418. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  10419. if (Conversion->isLambdaToBlockPointerConversion())
  10420. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  10421. else
  10422. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  10423. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  10424. MarkVTableUsed(Loc, MethodDecl->getParent());
  10425. }
  10426. // Recursive functions should be marked when used from another function.
  10427. // FIXME: Is this really right?
  10428. if (CurContext == Func) return;
  10429. // Resolve the exception specification for any function which is
  10430. // used: CodeGen will need it.
  10431. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  10432. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  10433. ResolveExceptionSpec(Loc, FPT);
  10434. if (!OdrUse) return;
  10435. // Implicit instantiation of function templates and member functions of
  10436. // class templates.
  10437. if (Func->isImplicitlyInstantiable()) {
  10438. bool AlreadyInstantiated = false;
  10439. SourceLocation PointOfInstantiation = Loc;
  10440. if (FunctionTemplateSpecializationInfo *SpecInfo
  10441. = Func->getTemplateSpecializationInfo()) {
  10442. if (SpecInfo->getPointOfInstantiation().isInvalid())
  10443. SpecInfo->setPointOfInstantiation(Loc);
  10444. else if (SpecInfo->getTemplateSpecializationKind()
  10445. == TSK_ImplicitInstantiation) {
  10446. AlreadyInstantiated = true;
  10447. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  10448. }
  10449. } else if (MemberSpecializationInfo *MSInfo
  10450. = Func->getMemberSpecializationInfo()) {
  10451. if (MSInfo->getPointOfInstantiation().isInvalid())
  10452. MSInfo->setPointOfInstantiation(Loc);
  10453. else if (MSInfo->getTemplateSpecializationKind()
  10454. == TSK_ImplicitInstantiation) {
  10455. AlreadyInstantiated = true;
  10456. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  10457. }
  10458. }
  10459. if (!AlreadyInstantiated || Func->isConstexpr()) {
  10460. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  10461. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  10462. ActiveTemplateInstantiations.size())
  10463. PendingLocalImplicitInstantiations.push_back(
  10464. std::make_pair(Func, PointOfInstantiation));
  10465. else if (Func->isConstexpr())
  10466. // Do not defer instantiations of constexpr functions, to avoid the
  10467. // expression evaluator needing to call back into Sema if it sees a
  10468. // call to such a function.
  10469. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  10470. else {
  10471. PendingInstantiations.push_back(std::make_pair(Func,
  10472. PointOfInstantiation));
  10473. // Notify the consumer that a function was implicitly instantiated.
  10474. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  10475. }
  10476. }
  10477. } else {
  10478. // Walk redefinitions, as some of them may be instantiable.
  10479. for (auto i : Func->redecls()) {
  10480. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  10481. MarkFunctionReferenced(Loc, i);
  10482. }
  10483. }
  10484. // Keep track of used but undefined functions.
  10485. if (!Func->isDefined()) {
  10486. if (mightHaveNonExternalLinkage(Func))
  10487. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  10488. else if (Func->getMostRecentDecl()->isInlined() &&
  10489. (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
  10490. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  10491. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  10492. }
  10493. // Normally the most current decl is marked used while processing the use and
  10494. // any subsequent decls are marked used by decl merging. This fails with
  10495. // template instantiation since marking can happen at the end of the file
  10496. // and, because of the two phase lookup, this function is called with at
  10497. // decl in the middle of a decl chain. We loop to maintain the invariant
  10498. // that once a decl is used, all decls after it are also used.
  10499. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  10500. F->markUsed(Context);
  10501. if (F == Func)
  10502. break;
  10503. }
  10504. }
  10505. static void
  10506. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  10507. VarDecl *var, DeclContext *DC) {
  10508. DeclContext *VarDC = var->getDeclContext();
  10509. // If the parameter still belongs to the translation unit, then
  10510. // we're actually just using one parameter in the declaration of
  10511. // the next.
  10512. if (isa<ParmVarDecl>(var) &&
  10513. isa<TranslationUnitDecl>(VarDC))
  10514. return;
  10515. // For C code, don't diagnose about capture if we're not actually in code
  10516. // right now; it's impossible to write a non-constant expression outside of
  10517. // function context, so we'll get other (more useful) diagnostics later.
  10518. //
  10519. // For C++, things get a bit more nasty... it would be nice to suppress this
  10520. // diagnostic for certain cases like using a local variable in an array bound
  10521. // for a member of a local class, but the correct predicate is not obvious.
  10522. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  10523. return;
  10524. if (isa<CXXMethodDecl>(VarDC) &&
  10525. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  10526. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  10527. << var->getIdentifier();
  10528. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  10529. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  10530. << var->getIdentifier() << fn->getDeclName();
  10531. } else if (isa<BlockDecl>(VarDC)) {
  10532. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  10533. << var->getIdentifier();
  10534. } else {
  10535. // FIXME: Is there any other context where a local variable can be
  10536. // declared?
  10537. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  10538. << var->getIdentifier();
  10539. }
  10540. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  10541. << var->getIdentifier();
  10542. // FIXME: Add additional diagnostic info about class etc. which prevents
  10543. // capture.
  10544. }
  10545. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  10546. bool &SubCapturesAreNested,
  10547. QualType &CaptureType,
  10548. QualType &DeclRefType) {
  10549. // Check whether we've already captured it.
  10550. if (CSI->CaptureMap.count(Var)) {
  10551. // If we found a capture, any subcaptures are nested.
  10552. SubCapturesAreNested = true;
  10553. // Retrieve the capture type for this variable.
  10554. CaptureType = CSI->getCapture(Var).getCaptureType();
  10555. // Compute the type of an expression that refers to this variable.
  10556. DeclRefType = CaptureType.getNonReferenceType();
  10557. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  10558. if (Cap.isCopyCapture() &&
  10559. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  10560. DeclRefType.addConst();
  10561. return true;
  10562. }
  10563. return false;
  10564. }
  10565. // Only block literals, captured statements, and lambda expressions can
  10566. // capture; other scopes don't work.
  10567. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  10568. SourceLocation Loc,
  10569. const bool Diagnose, Sema &S) {
  10570. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  10571. return getLambdaAwareParentOfDeclContext(DC);
  10572. else if (Var->hasLocalStorage()) {
  10573. if (Diagnose)
  10574. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  10575. }
  10576. return nullptr;
  10577. }
  10578. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  10579. // certain types of variables (unnamed, variably modified types etc.)
  10580. // so check for eligibility.
  10581. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  10582. SourceLocation Loc,
  10583. const bool Diagnose, Sema &S) {
  10584. bool IsBlock = isa<BlockScopeInfo>(CSI);
  10585. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  10586. // Lambdas are not allowed to capture unnamed variables
  10587. // (e.g. anonymous unions).
  10588. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  10589. // assuming that's the intent.
  10590. if (IsLambda && !Var->getDeclName()) {
  10591. if (Diagnose) {
  10592. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  10593. S.Diag(Var->getLocation(), diag::note_declared_at);
  10594. }
  10595. return false;
  10596. }
  10597. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  10598. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  10599. if (Diagnose) {
  10600. S.Diag(Loc, diag::err_ref_vm_type);
  10601. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10602. << Var->getDeclName();
  10603. }
  10604. return false;
  10605. }
  10606. // Prohibit structs with flexible array members too.
  10607. // We cannot capture what is in the tail end of the struct.
  10608. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  10609. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  10610. if (Diagnose) {
  10611. if (IsBlock)
  10612. S.Diag(Loc, diag::err_ref_flexarray_type);
  10613. else
  10614. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  10615. << Var->getDeclName();
  10616. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10617. << Var->getDeclName();
  10618. }
  10619. return false;
  10620. }
  10621. }
  10622. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  10623. // Lambdas and captured statements are not allowed to capture __block
  10624. // variables; they don't support the expected semantics.
  10625. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  10626. if (Diagnose) {
  10627. S.Diag(Loc, diag::err_capture_block_variable)
  10628. << Var->getDeclName() << !IsLambda;
  10629. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10630. << Var->getDeclName();
  10631. }
  10632. return false;
  10633. }
  10634. return true;
  10635. }
  10636. // Returns true if the capture by block was successful.
  10637. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  10638. SourceLocation Loc,
  10639. const bool BuildAndDiagnose,
  10640. QualType &CaptureType,
  10641. QualType &DeclRefType,
  10642. const bool Nested,
  10643. Sema &S) {
  10644. Expr *CopyExpr = nullptr;
  10645. bool ByRef = false;
  10646. // Blocks are not allowed to capture arrays.
  10647. if (CaptureType->isArrayType()) {
  10648. if (BuildAndDiagnose) {
  10649. S.Diag(Loc, diag::err_ref_array_type);
  10650. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10651. << Var->getDeclName();
  10652. }
  10653. return false;
  10654. }
  10655. // Forbid the block-capture of autoreleasing variables.
  10656. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  10657. if (BuildAndDiagnose) {
  10658. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  10659. << /*block*/ 0;
  10660. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10661. << Var->getDeclName();
  10662. }
  10663. return false;
  10664. }
  10665. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  10666. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  10667. // Block capture by reference does not change the capture or
  10668. // declaration reference types.
  10669. ByRef = true;
  10670. } else {
  10671. // Block capture by copy introduces 'const'.
  10672. CaptureType = CaptureType.getNonReferenceType().withConst();
  10673. DeclRefType = CaptureType;
  10674. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  10675. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  10676. // The capture logic needs the destructor, so make sure we mark it.
  10677. // Usually this is unnecessary because most local variables have
  10678. // their destructors marked at declaration time, but parameters are
  10679. // an exception because it's technically only the call site that
  10680. // actually requires the destructor.
  10681. if (isa<ParmVarDecl>(Var))
  10682. S.FinalizeVarWithDestructor(Var, Record);
  10683. // Enter a new evaluation context to insulate the copy
  10684. // full-expression.
  10685. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  10686. // According to the blocks spec, the capture of a variable from
  10687. // the stack requires a const copy constructor. This is not true
  10688. // of the copy/move done to move a __block variable to the heap.
  10689. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  10690. DeclRefType.withConst(),
  10691. VK_LValue, Loc);
  10692. ExprResult Result
  10693. = S.PerformCopyInitialization(
  10694. InitializedEntity::InitializeBlock(Var->getLocation(),
  10695. CaptureType, false),
  10696. Loc, DeclRef);
  10697. // Build a full-expression copy expression if initialization
  10698. // succeeded and used a non-trivial constructor. Recover from
  10699. // errors by pretending that the copy isn't necessary.
  10700. if (!Result.isInvalid() &&
  10701. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  10702. ->isTrivial()) {
  10703. Result = S.MaybeCreateExprWithCleanups(Result);
  10704. CopyExpr = Result.get();
  10705. }
  10706. }
  10707. }
  10708. }
  10709. // Actually capture the variable.
  10710. if (BuildAndDiagnose)
  10711. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  10712. SourceLocation(), CaptureType, CopyExpr);
  10713. return true;
  10714. }
  10715. /// \brief Capture the given variable in the captured region.
  10716. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  10717. VarDecl *Var,
  10718. SourceLocation Loc,
  10719. const bool BuildAndDiagnose,
  10720. QualType &CaptureType,
  10721. QualType &DeclRefType,
  10722. const bool RefersToCapturedVariable,
  10723. Sema &S) {
  10724. // By default, capture variables by reference.
  10725. bool ByRef = true;
  10726. // Using an LValue reference type is consistent with Lambdas (see below).
  10727. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  10728. Expr *CopyExpr = nullptr;
  10729. if (BuildAndDiagnose) {
  10730. // The current implementation assumes that all variables are captured
  10731. // by references. Since there is no capture by copy, no expression
  10732. // evaluation will be needed.
  10733. RecordDecl *RD = RSI->TheRecordDecl;
  10734. FieldDecl *Field
  10735. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  10736. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  10737. nullptr, false, ICIS_NoInit);
  10738. Field->setImplicit(true);
  10739. Field->setAccess(AS_private);
  10740. RD->addDecl(Field);
  10741. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  10742. DeclRefType, VK_LValue, Loc);
  10743. Var->setReferenced(true);
  10744. Var->markUsed(S.Context);
  10745. }
  10746. // Actually capture the variable.
  10747. if (BuildAndDiagnose)
  10748. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  10749. SourceLocation(), CaptureType, CopyExpr);
  10750. return true;
  10751. }
  10752. /// \brief Create a field within the lambda class for the variable
  10753. /// being captured. Handle Array captures.
  10754. static ExprResult addAsFieldToClosureType(Sema &S,
  10755. LambdaScopeInfo *LSI,
  10756. VarDecl *Var, QualType FieldType,
  10757. QualType DeclRefType,
  10758. SourceLocation Loc,
  10759. bool RefersToCapturedVariable) {
  10760. CXXRecordDecl *Lambda = LSI->Lambda;
  10761. // Build the non-static data member.
  10762. FieldDecl *Field
  10763. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  10764. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  10765. nullptr, false, ICIS_NoInit);
  10766. Field->setImplicit(true);
  10767. Field->setAccess(AS_private);
  10768. Lambda->addDecl(Field);
  10769. // C++11 [expr.prim.lambda]p21:
  10770. // When the lambda-expression is evaluated, the entities that
  10771. // are captured by copy are used to direct-initialize each
  10772. // corresponding non-static data member of the resulting closure
  10773. // object. (For array members, the array elements are
  10774. // direct-initialized in increasing subscript order.) These
  10775. // initializations are performed in the (unspecified) order in
  10776. // which the non-static data members are declared.
  10777. // Introduce a new evaluation context for the initialization, so
  10778. // that temporaries introduced as part of the capture are retained
  10779. // to be re-"exported" from the lambda expression itself.
  10780. EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
  10781. // C++ [expr.prim.labda]p12:
  10782. // An entity captured by a lambda-expression is odr-used (3.2) in
  10783. // the scope containing the lambda-expression.
  10784. Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  10785. DeclRefType, VK_LValue, Loc);
  10786. Var->setReferenced(true);
  10787. Var->markUsed(S.Context);
  10788. // When the field has array type, create index variables for each
  10789. // dimension of the array. We use these index variables to subscript
  10790. // the source array, and other clients (e.g., CodeGen) will perform
  10791. // the necessary iteration with these index variables.
  10792. SmallVector<VarDecl *, 4> IndexVariables;
  10793. QualType BaseType = FieldType;
  10794. QualType SizeType = S.Context.getSizeType();
  10795. LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
  10796. while (const ConstantArrayType *Array
  10797. = S.Context.getAsConstantArrayType(BaseType)) {
  10798. // Create the iteration variable for this array index.
  10799. IdentifierInfo *IterationVarName = nullptr;
  10800. {
  10801. SmallString<8> Str;
  10802. llvm::raw_svector_ostream OS(Str);
  10803. OS << "__i" << IndexVariables.size();
  10804. IterationVarName = &S.Context.Idents.get(OS.str());
  10805. }
  10806. VarDecl *IterationVar
  10807. = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  10808. IterationVarName, SizeType,
  10809. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  10810. SC_None);
  10811. IndexVariables.push_back(IterationVar);
  10812. LSI->ArrayIndexVars.push_back(IterationVar);
  10813. // Create a reference to the iteration variable.
  10814. ExprResult IterationVarRef
  10815. = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
  10816. assert(!IterationVarRef.isInvalid() &&
  10817. "Reference to invented variable cannot fail!");
  10818. IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
  10819. assert(!IterationVarRef.isInvalid() &&
  10820. "Conversion of invented variable cannot fail!");
  10821. // Subscript the array with this iteration variable.
  10822. ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
  10823. Ref, Loc, IterationVarRef.get(), Loc);
  10824. if (Subscript.isInvalid()) {
  10825. S.CleanupVarDeclMarking();
  10826. S.DiscardCleanupsInEvaluationContext();
  10827. return ExprError();
  10828. }
  10829. Ref = Subscript.get();
  10830. BaseType = Array->getElementType();
  10831. }
  10832. // Construct the entity that we will be initializing. For an array, this
  10833. // will be first element in the array, which may require several levels
  10834. // of array-subscript entities.
  10835. SmallVector<InitializedEntity, 4> Entities;
  10836. Entities.reserve(1 + IndexVariables.size());
  10837. Entities.push_back(
  10838. InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
  10839. Field->getType(), Loc));
  10840. for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
  10841. Entities.push_back(InitializedEntity::InitializeElement(S.Context,
  10842. 0,
  10843. Entities.back()));
  10844. InitializationKind InitKind
  10845. = InitializationKind::CreateDirect(Loc, Loc, Loc);
  10846. InitializationSequence Init(S, Entities.back(), InitKind, Ref);
  10847. ExprResult Result(true);
  10848. if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
  10849. Result = Init.Perform(S, Entities.back(), InitKind, Ref);
  10850. // If this initialization requires any cleanups (e.g., due to a
  10851. // default argument to a copy constructor), note that for the
  10852. // lambda.
  10853. if (S.ExprNeedsCleanups)
  10854. LSI->ExprNeedsCleanups = true;
  10855. // Exit the expression evaluation context used for the capture.
  10856. S.CleanupVarDeclMarking();
  10857. S.DiscardCleanupsInEvaluationContext();
  10858. return Result;
  10859. }
  10860. /// \brief Capture the given variable in the lambda.
  10861. static bool captureInLambda(LambdaScopeInfo *LSI,
  10862. VarDecl *Var,
  10863. SourceLocation Loc,
  10864. const bool BuildAndDiagnose,
  10865. QualType &CaptureType,
  10866. QualType &DeclRefType,
  10867. const bool RefersToCapturedVariable,
  10868. const Sema::TryCaptureKind Kind,
  10869. SourceLocation EllipsisLoc,
  10870. const bool IsTopScope,
  10871. Sema &S) {
  10872. // Determine whether we are capturing by reference or by value.
  10873. bool ByRef = false;
  10874. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  10875. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  10876. } else {
  10877. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  10878. }
  10879. // Compute the type of the field that will capture this variable.
  10880. if (ByRef) {
  10881. // C++11 [expr.prim.lambda]p15:
  10882. // An entity is captured by reference if it is implicitly or
  10883. // explicitly captured but not captured by copy. It is
  10884. // unspecified whether additional unnamed non-static data
  10885. // members are declared in the closure type for entities
  10886. // captured by reference.
  10887. //
  10888. // FIXME: It is not clear whether we want to build an lvalue reference
  10889. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  10890. // to do the former, while EDG does the latter. Core issue 1249 will
  10891. // clarify, but for now we follow GCC because it's a more permissive and
  10892. // easily defensible position.
  10893. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  10894. } else {
  10895. // C++11 [expr.prim.lambda]p14:
  10896. // For each entity captured by copy, an unnamed non-static
  10897. // data member is declared in the closure type. The
  10898. // declaration order of these members is unspecified. The type
  10899. // of such a data member is the type of the corresponding
  10900. // captured entity if the entity is not a reference to an
  10901. // object, or the referenced type otherwise. [Note: If the
  10902. // captured entity is a reference to a function, the
  10903. // corresponding data member is also a reference to a
  10904. // function. - end note ]
  10905. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  10906. if (!RefType->getPointeeType()->isFunctionType())
  10907. CaptureType = RefType->getPointeeType();
  10908. }
  10909. // Forbid the lambda copy-capture of autoreleasing variables.
  10910. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  10911. if (BuildAndDiagnose) {
  10912. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  10913. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10914. << Var->getDeclName();
  10915. }
  10916. return false;
  10917. }
  10918. // Make sure that by-copy captures are of a complete and non-abstract type.
  10919. if (BuildAndDiagnose) {
  10920. if (!CaptureType->isDependentType() &&
  10921. S.RequireCompleteType(Loc, CaptureType,
  10922. diag::err_capture_of_incomplete_type,
  10923. Var->getDeclName()))
  10924. return false;
  10925. if (S.RequireNonAbstractType(Loc, CaptureType,
  10926. diag::err_capture_of_abstract_type))
  10927. return false;
  10928. }
  10929. }
  10930. // Capture this variable in the lambda.
  10931. Expr *CopyExpr = nullptr;
  10932. if (BuildAndDiagnose) {
  10933. ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
  10934. CaptureType, DeclRefType, Loc,
  10935. RefersToCapturedVariable);
  10936. if (!Result.isInvalid())
  10937. CopyExpr = Result.get();
  10938. }
  10939. // Compute the type of a reference to this captured variable.
  10940. if (ByRef)
  10941. DeclRefType = CaptureType.getNonReferenceType();
  10942. else {
  10943. // C++ [expr.prim.lambda]p5:
  10944. // The closure type for a lambda-expression has a public inline
  10945. // function call operator [...]. This function call operator is
  10946. // declared const (9.3.1) if and only if the lambda-expression’s
  10947. // parameter-declaration-clause is not followed by mutable.
  10948. DeclRefType = CaptureType.getNonReferenceType();
  10949. if (!LSI->Mutable && !CaptureType->isReferenceType())
  10950. DeclRefType.addConst();
  10951. }
  10952. // Add the capture.
  10953. if (BuildAndDiagnose)
  10954. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  10955. Loc, EllipsisLoc, CaptureType, CopyExpr);
  10956. return true;
  10957. }
  10958. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
  10959. TryCaptureKind Kind, SourceLocation EllipsisLoc,
  10960. bool BuildAndDiagnose,
  10961. QualType &CaptureType,
  10962. QualType &DeclRefType,
  10963. const unsigned *const FunctionScopeIndexToStopAt) {
  10964. bool Nested = Var->isInitCapture();
  10965. DeclContext *DC = CurContext;
  10966. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  10967. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  10968. // We need to sync up the Declaration Context with the
  10969. // FunctionScopeIndexToStopAt
  10970. if (FunctionScopeIndexToStopAt) {
  10971. unsigned FSIndex = FunctionScopes.size() - 1;
  10972. while (FSIndex != MaxFunctionScopesIndex) {
  10973. DC = getLambdaAwareParentOfDeclContext(DC);
  10974. --FSIndex;
  10975. }
  10976. }
  10977. // If the variable is declared in the current context (and is not an
  10978. // init-capture), there is no need to capture it.
  10979. if (!Nested && Var->getDeclContext() == DC) return true;
  10980. // Capture global variables if it is required to use private copy of this
  10981. // variable.
  10982. bool IsGlobal = !Var->hasLocalStorage();
  10983. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  10984. return true;
  10985. // Walk up the stack to determine whether we can capture the variable,
  10986. // performing the "simple" checks that don't depend on type. We stop when
  10987. // we've either hit the declared scope of the variable or find an existing
  10988. // capture of that variable. We start from the innermost capturing-entity
  10989. // (the DC) and ensure that all intervening capturing-entities
  10990. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  10991. // declcontext can either capture the variable or have already captured
  10992. // the variable.
  10993. CaptureType = Var->getType();
  10994. DeclRefType = CaptureType.getNonReferenceType();
  10995. bool Explicit = (Kind != TryCapture_Implicit);
  10996. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  10997. do {
  10998. // Only block literals, captured statements, and lambda expressions can
  10999. // capture; other scopes don't work.
  11000. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11001. ExprLoc,
  11002. BuildAndDiagnose,
  11003. *this);
  11004. // We need to check for the parent *first* because, if we *have*
  11005. // private-captured a global variable, we need to recursively capture it in
  11006. // intermediate blocks, lambdas, etc.
  11007. if (!ParentDC) {
  11008. if (IsGlobal) {
  11009. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11010. break;
  11011. }
  11012. return true;
  11013. }
  11014. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11015. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11016. // Check whether we've already captured it.
  11017. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11018. DeclRefType))
  11019. break;
  11020. // If we are instantiating a generic lambda call operator body,
  11021. // we do not want to capture new variables. What was captured
  11022. // during either a lambdas transformation or initial parsing
  11023. // should be used.
  11024. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11025. if (BuildAndDiagnose) {
  11026. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11027. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11028. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11029. Diag(Var->getLocation(), diag::note_previous_decl)
  11030. << Var->getDeclName();
  11031. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11032. } else
  11033. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11034. }
  11035. return true;
  11036. }
  11037. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11038. // certain types of variables (unnamed, variably modified types etc.)
  11039. // so check for eligibility.
  11040. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11041. return true;
  11042. // Try to capture variable-length arrays types.
  11043. if (Var->getType()->isVariablyModifiedType()) {
  11044. // We're going to walk down into the type and look for VLA
  11045. // expressions.
  11046. QualType QTy = Var->getType();
  11047. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11048. QTy = PVD->getOriginalType();
  11049. do {
  11050. const Type *Ty = QTy.getTypePtr();
  11051. switch (Ty->getTypeClass()) {
  11052. #define TYPE(Class, Base)
  11053. #define ABSTRACT_TYPE(Class, Base)
  11054. #define NON_CANONICAL_TYPE(Class, Base)
  11055. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11056. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11057. #include "clang/AST/TypeNodes.def"
  11058. QTy = QualType();
  11059. break;
  11060. // These types are never variably-modified.
  11061. case Type::Builtin:
  11062. case Type::Complex:
  11063. case Type::Vector:
  11064. case Type::ExtVector:
  11065. case Type::Record:
  11066. case Type::Enum:
  11067. case Type::Elaborated:
  11068. case Type::TemplateSpecialization:
  11069. case Type::ObjCObject:
  11070. case Type::ObjCInterface:
  11071. case Type::ObjCObjectPointer:
  11072. llvm_unreachable("type class is never variably-modified!");
  11073. case Type::Adjusted:
  11074. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11075. break;
  11076. case Type::Decayed:
  11077. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11078. break;
  11079. case Type::Pointer:
  11080. QTy = cast<PointerType>(Ty)->getPointeeType();
  11081. break;
  11082. case Type::BlockPointer:
  11083. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11084. break;
  11085. case Type::LValueReference:
  11086. case Type::RValueReference:
  11087. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11088. break;
  11089. case Type::MemberPointer:
  11090. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11091. break;
  11092. case Type::ConstantArray:
  11093. case Type::IncompleteArray:
  11094. // Losing element qualification here is fine.
  11095. QTy = cast<ArrayType>(Ty)->getElementType();
  11096. break;
  11097. case Type::VariableArray: {
  11098. // Losing element qualification here is fine.
  11099. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11100. // Unknown size indication requires no size computation.
  11101. // Otherwise, evaluate and record it.
  11102. if (auto Size = VAT->getSizeExpr()) {
  11103. if (!CSI->isVLATypeCaptured(VAT)) {
  11104. RecordDecl *CapRecord = nullptr;
  11105. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11106. CapRecord = LSI->Lambda;
  11107. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11108. CapRecord = CRSI->TheRecordDecl;
  11109. }
  11110. if (CapRecord) {
  11111. auto ExprLoc = Size->getExprLoc();
  11112. auto SizeType = Context.getSizeType();
  11113. // Build the non-static data member.
  11114. auto Field = FieldDecl::Create(
  11115. Context, CapRecord, ExprLoc, ExprLoc,
  11116. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11117. /*BW*/ nullptr, /*Mutable*/ false,
  11118. /*InitStyle*/ ICIS_NoInit);
  11119. Field->setImplicit(true);
  11120. Field->setAccess(AS_private);
  11121. Field->setCapturedVLAType(VAT);
  11122. CapRecord->addDecl(Field);
  11123. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11124. }
  11125. }
  11126. }
  11127. QTy = VAT->getElementType();
  11128. break;
  11129. }
  11130. case Type::FunctionProto:
  11131. case Type::FunctionNoProto:
  11132. QTy = cast<FunctionType>(Ty)->getReturnType();
  11133. break;
  11134. case Type::Paren:
  11135. case Type::TypeOf:
  11136. case Type::UnaryTransform:
  11137. case Type::Attributed:
  11138. case Type::SubstTemplateTypeParm:
  11139. case Type::PackExpansion:
  11140. // Keep walking after single level desugaring.
  11141. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11142. break;
  11143. case Type::Typedef:
  11144. QTy = cast<TypedefType>(Ty)->desugar();
  11145. break;
  11146. case Type::Decltype:
  11147. QTy = cast<DecltypeType>(Ty)->desugar();
  11148. break;
  11149. case Type::Auto:
  11150. QTy = cast<AutoType>(Ty)->getDeducedType();
  11151. break;
  11152. case Type::TypeOfExpr:
  11153. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11154. break;
  11155. case Type::Atomic:
  11156. QTy = cast<AtomicType>(Ty)->getValueType();
  11157. break;
  11158. }
  11159. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11160. }
  11161. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11162. // No capture-default, and this is not an explicit capture
  11163. // so cannot capture this variable.
  11164. if (BuildAndDiagnose) {
  11165. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11166. Diag(Var->getLocation(), diag::note_previous_decl)
  11167. << Var->getDeclName();
  11168. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11169. diag::note_lambda_decl);
  11170. // FIXME: If we error out because an outer lambda can not implicitly
  11171. // capture a variable that an inner lambda explicitly captures, we
  11172. // should have the inner lambda do the explicit capture - because
  11173. // it makes for cleaner diagnostics later. This would purely be done
  11174. // so that the diagnostic does not misleadingly claim that a variable
  11175. // can not be captured by a lambda implicitly even though it is captured
  11176. // explicitly. Suggestion:
  11177. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11178. // at the function head
  11179. // - cache the StartingDeclContext - this must be a lambda
  11180. // - captureInLambda in the innermost lambda the variable.
  11181. }
  11182. return true;
  11183. }
  11184. FunctionScopesIndex--;
  11185. DC = ParentDC;
  11186. Explicit = false;
  11187. } while (!Var->getDeclContext()->Equals(DC));
  11188. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11189. // computing the type of the capture at each step, checking type-specific
  11190. // requirements, and adding captures if requested.
  11191. // If the variable had already been captured previously, we start capturing
  11192. // at the lambda nested within that one.
  11193. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11194. ++I) {
  11195. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11196. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11197. if (!captureInBlock(BSI, Var, ExprLoc,
  11198. BuildAndDiagnose, CaptureType,
  11199. DeclRefType, Nested, *this))
  11200. return true;
  11201. Nested = true;
  11202. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11203. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11204. BuildAndDiagnose, CaptureType,
  11205. DeclRefType, Nested, *this))
  11206. return true;
  11207. Nested = true;
  11208. } else {
  11209. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11210. if (!captureInLambda(LSI, Var, ExprLoc,
  11211. BuildAndDiagnose, CaptureType,
  11212. DeclRefType, Nested, Kind, EllipsisLoc,
  11213. /*IsTopScope*/I == N - 1, *this))
  11214. return true;
  11215. Nested = true;
  11216. }
  11217. }
  11218. return false;
  11219. }
  11220. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11221. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11222. QualType CaptureType;
  11223. QualType DeclRefType;
  11224. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11225. /*BuildAndDiagnose=*/true, CaptureType,
  11226. DeclRefType, nullptr);
  11227. }
  11228. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11229. QualType CaptureType;
  11230. QualType DeclRefType;
  11231. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11232. /*BuildAndDiagnose=*/false, CaptureType,
  11233. DeclRefType, nullptr);
  11234. }
  11235. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11236. QualType CaptureType;
  11237. QualType DeclRefType;
  11238. // Determine whether we can capture this variable.
  11239. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11240. /*BuildAndDiagnose=*/false, CaptureType,
  11241. DeclRefType, nullptr))
  11242. return QualType();
  11243. return DeclRefType;
  11244. }
  11245. // If either the type of the variable or the initializer is dependent,
  11246. // return false. Otherwise, determine whether the variable is a constant
  11247. // expression. Use this if you need to know if a variable that might or
  11248. // might not be dependent is truly a constant expression.
  11249. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11250. ASTContext &Context) {
  11251. if (Var->getType()->isDependentType())
  11252. return false;
  11253. const VarDecl *DefVD = nullptr;
  11254. Var->getAnyInitializer(DefVD);
  11255. if (!DefVD)
  11256. return false;
  11257. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11258. Expr *Init = cast<Expr>(Eval->Value);
  11259. if (Init->isValueDependent())
  11260. return false;
  11261. return IsVariableAConstantExpression(Var, Context);
  11262. }
  11263. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11264. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11265. // an object that satisfies the requirements for appearing in a
  11266. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11267. // is immediately applied." This function handles the lvalue-to-rvalue
  11268. // conversion part.
  11269. MaybeODRUseExprs.erase(E->IgnoreParens());
  11270. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11271. // to a variable that is a constant expression, and if so, identify it as
  11272. // a reference to a variable that does not involve an odr-use of that
  11273. // variable.
  11274. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11275. Expr *SansParensExpr = E->IgnoreParens();
  11276. VarDecl *Var = nullptr;
  11277. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11278. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11279. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11280. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11281. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11282. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11283. }
  11284. }
  11285. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11286. Res = CorrectDelayedTyposInExpr(Res);
  11287. if (!Res.isUsable())
  11288. return Res;
  11289. // If a constant-expression is a reference to a variable where we delay
  11290. // deciding whether it is an odr-use, just assume we will apply the
  11291. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11292. // (a non-type template argument), we have special handling anyway.
  11293. UpdateMarkingForLValueToRValue(Res.get());
  11294. return Res;
  11295. }
  11296. void Sema::CleanupVarDeclMarking() {
  11297. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11298. e = MaybeODRUseExprs.end();
  11299. i != e; ++i) {
  11300. VarDecl *Var;
  11301. SourceLocation Loc;
  11302. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11303. Var = cast<VarDecl>(DRE->getDecl());
  11304. Loc = DRE->getLocation();
  11305. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11306. Var = cast<VarDecl>(ME->getMemberDecl());
  11307. Loc = ME->getMemberLoc();
  11308. } else {
  11309. llvm_unreachable("Unexpected expression");
  11310. }
  11311. MarkVarDeclODRUsed(Var, Loc, *this,
  11312. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11313. }
  11314. MaybeODRUseExprs.clear();
  11315. }
  11316. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11317. VarDecl *Var, Expr *E) {
  11318. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11319. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11320. Var->setReferenced();
  11321. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11322. bool MarkODRUsed = true;
  11323. // If the context is not potentially evaluated, this is not an odr-use and
  11324. // does not trigger instantiation.
  11325. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11326. if (SemaRef.isUnevaluatedContext())
  11327. return;
  11328. // If we don't yet know whether this context is going to end up being an
  11329. // evaluated context, and we're referencing a variable from an enclosing
  11330. // scope, add a potential capture.
  11331. //
  11332. // FIXME: Is this necessary? These contexts are only used for default
  11333. // arguments, where local variables can't be used.
  11334. const bool RefersToEnclosingScope =
  11335. (SemaRef.CurContext != Var->getDeclContext() &&
  11336. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11337. if (RefersToEnclosingScope) {
  11338. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11339. // If a variable could potentially be odr-used, defer marking it so
  11340. // until we finish analyzing the full expression for any
  11341. // lvalue-to-rvalue
  11342. // or discarded value conversions that would obviate odr-use.
  11343. // Add it to the list of potential captures that will be analyzed
  11344. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11345. // unless the variable is a reference that was initialized by a constant
  11346. // expression (this will never need to be captured or odr-used).
  11347. assert(E && "Capture variable should be used in an expression.");
  11348. if (!Var->getType()->isReferenceType() ||
  11349. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11350. LSI->addPotentialCapture(E->IgnoreParens());
  11351. }
  11352. }
  11353. if (!isTemplateInstantiation(TSK))
  11354. return;
  11355. // Instantiate, but do not mark as odr-used, variable templates.
  11356. MarkODRUsed = false;
  11357. }
  11358. VarTemplateSpecializationDecl *VarSpec =
  11359. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11360. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11361. "Can't instantiate a partial template specialization.");
  11362. // Perform implicit instantiation of static data members, static data member
  11363. // templates of class templates, and variable template specializations. Delay
  11364. // instantiations of variable templates, except for those that could be used
  11365. // in a constant expression.
  11366. if (isTemplateInstantiation(TSK)) {
  11367. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11368. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11369. if (Var->getPointOfInstantiation().isInvalid()) {
  11370. // This is a modification of an existing AST node. Notify listeners.
  11371. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11372. L->StaticDataMemberInstantiated(Var);
  11373. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11374. // Don't bother trying to instantiate it again, unless we might need
  11375. // its initializer before we get to the end of the TU.
  11376. TryInstantiating = false;
  11377. }
  11378. if (Var->getPointOfInstantiation().isInvalid())
  11379. Var->setTemplateSpecializationKind(TSK, Loc);
  11380. if (TryInstantiating) {
  11381. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11382. bool InstantiationDependent = false;
  11383. bool IsNonDependent =
  11384. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11385. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11386. : true;
  11387. // Do not instantiate specializations that are still type-dependent.
  11388. if (IsNonDependent) {
  11389. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11390. // Do not defer instantiations of variables which could be used in a
  11391. // constant expression.
  11392. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11393. } else {
  11394. SemaRef.PendingInstantiations
  11395. .push_back(std::make_pair(Var, PointOfInstantiation));
  11396. }
  11397. }
  11398. }
  11399. }
  11400. if(!MarkODRUsed) return;
  11401. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11402. // the requirements for appearing in a constant expression (5.19) and, if
  11403. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11404. // is immediately applied." We check the first part here, and
  11405. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11406. // Note that we use the C++11 definition everywhere because nothing in
  11407. // C++03 depends on whether we get the C++03 version correct. The second
  11408. // part does not apply to references, since they are not objects.
  11409. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11410. // A reference initialized by a constant expression can never be
  11411. // odr-used, so simply ignore it.
  11412. if (!Var->getType()->isReferenceType())
  11413. SemaRef.MaybeODRUseExprs.insert(E);
  11414. } else
  11415. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11416. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11417. }
  11418. /// \brief Mark a variable referenced, and check whether it is odr-used
  11419. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11420. /// used directly for normal expressions referring to VarDecl.
  11421. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11422. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11423. }
  11424. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11425. Decl *D, Expr *E, bool OdrUse) {
  11426. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11427. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11428. return;
  11429. }
  11430. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11431. // If this is a call to a method via a cast, also mark the method in the
  11432. // derived class used in case codegen can devirtualize the call.
  11433. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11434. if (!ME)
  11435. return;
  11436. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11437. if (!MD)
  11438. return;
  11439. // Only attempt to devirtualize if this is truly a virtual call.
  11440. bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
  11441. if (!IsVirtualCall)
  11442. return;
  11443. const Expr *Base = ME->getBase();
  11444. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  11445. if (!MostDerivedClassDecl)
  11446. return;
  11447. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  11448. if (!DM || DM->isPure())
  11449. return;
  11450. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  11451. }
  11452. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  11453. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  11454. // TODO: update this with DR# once a defect report is filed.
  11455. // C++11 defect. The address of a pure member should not be an ODR use, even
  11456. // if it's a qualified reference.
  11457. bool OdrUse = true;
  11458. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  11459. if (Method->isVirtual())
  11460. OdrUse = false;
  11461. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  11462. }
  11463. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  11464. void Sema::MarkMemberReferenced(MemberExpr *E) {
  11465. // C++11 [basic.def.odr]p2:
  11466. // A non-overloaded function whose name appears as a potentially-evaluated
  11467. // expression or a member of a set of candidate functions, if selected by
  11468. // overload resolution when referred to from a potentially-evaluated
  11469. // expression, is odr-used, unless it is a pure virtual function and its
  11470. // name is not explicitly qualified.
  11471. bool OdrUse = true;
  11472. if (!E->hasQualifier()) {
  11473. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  11474. if (Method->isPure())
  11475. OdrUse = false;
  11476. }
  11477. SourceLocation Loc = E->getMemberLoc().isValid() ?
  11478. E->getMemberLoc() : E->getLocStart();
  11479. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  11480. }
  11481. /// \brief Perform marking for a reference to an arbitrary declaration. It
  11482. /// marks the declaration referenced, and performs odr-use checking for
  11483. /// functions and variables. This method should not be used when building a
  11484. /// normal expression which refers to a variable.
  11485. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  11486. if (OdrUse) {
  11487. if (auto *VD = dyn_cast<VarDecl>(D)) {
  11488. MarkVariableReferenced(Loc, VD);
  11489. return;
  11490. }
  11491. }
  11492. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  11493. MarkFunctionReferenced(Loc, FD, OdrUse);
  11494. return;
  11495. }
  11496. D->setReferenced();
  11497. }
  11498. namespace {
  11499. // Mark all of the declarations referenced
  11500. // FIXME: Not fully implemented yet! We need to have a better understanding
  11501. // of when we're entering
  11502. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  11503. Sema &S;
  11504. SourceLocation Loc;
  11505. public:
  11506. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  11507. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  11508. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  11509. bool TraverseRecordType(RecordType *T);
  11510. };
  11511. }
  11512. bool MarkReferencedDecls::TraverseTemplateArgument(
  11513. const TemplateArgument &Arg) {
  11514. if (Arg.getKind() == TemplateArgument::Declaration) {
  11515. if (Decl *D = Arg.getAsDecl())
  11516. S.MarkAnyDeclReferenced(Loc, D, true);
  11517. }
  11518. return Inherited::TraverseTemplateArgument(Arg);
  11519. }
  11520. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  11521. if (ClassTemplateSpecializationDecl *Spec
  11522. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  11523. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  11524. return TraverseTemplateArguments(Args.data(), Args.size());
  11525. }
  11526. return true;
  11527. }
  11528. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  11529. MarkReferencedDecls Marker(*this, Loc);
  11530. Marker.TraverseType(Context.getCanonicalType(T));
  11531. }
  11532. namespace {
  11533. /// \brief Helper class that marks all of the declarations referenced by
  11534. /// potentially-evaluated subexpressions as "referenced".
  11535. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  11536. Sema &S;
  11537. bool SkipLocalVariables;
  11538. public:
  11539. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  11540. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  11541. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  11542. void VisitDeclRefExpr(DeclRefExpr *E) {
  11543. // If we were asked not to visit local variables, don't.
  11544. if (SkipLocalVariables) {
  11545. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  11546. if (VD->hasLocalStorage())
  11547. return;
  11548. }
  11549. S.MarkDeclRefReferenced(E);
  11550. }
  11551. void VisitMemberExpr(MemberExpr *E) {
  11552. S.MarkMemberReferenced(E);
  11553. Inherited::VisitMemberExpr(E);
  11554. }
  11555. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  11556. S.MarkFunctionReferenced(E->getLocStart(),
  11557. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  11558. Visit(E->getSubExpr());
  11559. }
  11560. void VisitCXXNewExpr(CXXNewExpr *E) {
  11561. if (E->getOperatorNew())
  11562. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  11563. if (E->getOperatorDelete())
  11564. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  11565. Inherited::VisitCXXNewExpr(E);
  11566. }
  11567. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  11568. if (E->getOperatorDelete())
  11569. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  11570. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  11571. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  11572. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  11573. S.MarkFunctionReferenced(E->getLocStart(),
  11574. S.LookupDestructor(Record));
  11575. }
  11576. Inherited::VisitCXXDeleteExpr(E);
  11577. }
  11578. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  11579. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  11580. Inherited::VisitCXXConstructExpr(E);
  11581. }
  11582. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  11583. Visit(E->getExpr());
  11584. }
  11585. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  11586. Inherited::VisitImplicitCastExpr(E);
  11587. if (E->getCastKind() == CK_LValueToRValue)
  11588. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  11589. }
  11590. };
  11591. }
  11592. /// \brief Mark any declarations that appear within this expression or any
  11593. /// potentially-evaluated subexpressions as "referenced".
  11594. ///
  11595. /// \param SkipLocalVariables If true, don't mark local variables as
  11596. /// 'referenced'.
  11597. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  11598. bool SkipLocalVariables) {
  11599. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  11600. }
  11601. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  11602. /// of the program being compiled.
  11603. ///
  11604. /// This routine emits the given diagnostic when the code currently being
  11605. /// type-checked is "potentially evaluated", meaning that there is a
  11606. /// possibility that the code will actually be executable. Code in sizeof()
  11607. /// expressions, code used only during overload resolution, etc., are not
  11608. /// potentially evaluated. This routine will suppress such diagnostics or,
  11609. /// in the absolutely nutty case of potentially potentially evaluated
  11610. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  11611. /// later.
  11612. ///
  11613. /// This routine should be used for all diagnostics that describe the run-time
  11614. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  11615. /// Failure to do so will likely result in spurious diagnostics or failures
  11616. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  11617. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  11618. const PartialDiagnostic &PD) {
  11619. switch (ExprEvalContexts.back().Context) {
  11620. case Unevaluated:
  11621. case UnevaluatedAbstract:
  11622. // The argument will never be evaluated, so don't complain.
  11623. break;
  11624. case ConstantEvaluated:
  11625. // Relevant diagnostics should be produced by constant evaluation.
  11626. break;
  11627. case PotentiallyEvaluated:
  11628. case PotentiallyEvaluatedIfUsed:
  11629. if (Statement && getCurFunctionOrMethodDecl()) {
  11630. FunctionScopes.back()->PossiblyUnreachableDiags.
  11631. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  11632. }
  11633. else
  11634. Diag(Loc, PD);
  11635. return true;
  11636. }
  11637. return false;
  11638. }
  11639. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  11640. CallExpr *CE, FunctionDecl *FD) {
  11641. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  11642. return false;
  11643. // If we're inside a decltype's expression, don't check for a valid return
  11644. // type or construct temporaries until we know whether this is the last call.
  11645. if (ExprEvalContexts.back().IsDecltype) {
  11646. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  11647. return false;
  11648. }
  11649. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  11650. FunctionDecl *FD;
  11651. CallExpr *CE;
  11652. public:
  11653. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  11654. : FD(FD), CE(CE) { }
  11655. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  11656. if (!FD) {
  11657. S.Diag(Loc, diag::err_call_incomplete_return)
  11658. << T << CE->getSourceRange();
  11659. return;
  11660. }
  11661. S.Diag(Loc, diag::err_call_function_incomplete_return)
  11662. << CE->getSourceRange() << FD->getDeclName() << T;
  11663. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  11664. << FD->getDeclName();
  11665. }
  11666. } Diagnoser(FD, CE);
  11667. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  11668. return true;
  11669. return false;
  11670. }
  11671. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  11672. // will prevent this condition from triggering, which is what we want.
  11673. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  11674. SourceLocation Loc;
  11675. unsigned diagnostic = diag::warn_condition_is_assignment;
  11676. bool IsOrAssign = false;
  11677. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  11678. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  11679. return;
  11680. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  11681. // Greylist some idioms by putting them into a warning subcategory.
  11682. if (ObjCMessageExpr *ME
  11683. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  11684. Selector Sel = ME->getSelector();
  11685. // self = [<foo> init...]
  11686. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  11687. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  11688. // <foo> = [<bar> nextObject]
  11689. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  11690. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  11691. }
  11692. Loc = Op->getOperatorLoc();
  11693. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  11694. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  11695. return;
  11696. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  11697. Loc = Op->getOperatorLoc();
  11698. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  11699. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  11700. else {
  11701. // Not an assignment.
  11702. return;
  11703. }
  11704. Diag(Loc, diagnostic) << E->getSourceRange();
  11705. SourceLocation Open = E->getLocStart();
  11706. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  11707. Diag(Loc, diag::note_condition_assign_silence)
  11708. << FixItHint::CreateInsertion(Open, "(")
  11709. << FixItHint::CreateInsertion(Close, ")");
  11710. if (IsOrAssign)
  11711. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  11712. << FixItHint::CreateReplacement(Loc, "!=");
  11713. else
  11714. Diag(Loc, diag::note_condition_assign_to_comparison)
  11715. << FixItHint::CreateReplacement(Loc, "==");
  11716. }
  11717. /// \brief Redundant parentheses over an equality comparison can indicate
  11718. /// that the user intended an assignment used as condition.
  11719. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  11720. // Don't warn if the parens came from a macro.
  11721. SourceLocation parenLoc = ParenE->getLocStart();
  11722. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  11723. return;
  11724. // Don't warn for dependent expressions.
  11725. if (ParenE->isTypeDependent())
  11726. return;
  11727. Expr *E = ParenE->IgnoreParens();
  11728. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  11729. if (opE->getOpcode() == BO_EQ &&
  11730. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  11731. == Expr::MLV_Valid) {
  11732. SourceLocation Loc = opE->getOperatorLoc();
  11733. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  11734. SourceRange ParenERange = ParenE->getSourceRange();
  11735. Diag(Loc, diag::note_equality_comparison_silence)
  11736. << FixItHint::CreateRemoval(ParenERange.getBegin())
  11737. << FixItHint::CreateRemoval(ParenERange.getEnd());
  11738. Diag(Loc, diag::note_equality_comparison_to_assign)
  11739. << FixItHint::CreateReplacement(Loc, "=");
  11740. }
  11741. }
  11742. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  11743. DiagnoseAssignmentAsCondition(E);
  11744. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  11745. DiagnoseEqualityWithExtraParens(parenE);
  11746. ExprResult result = CheckPlaceholderExpr(E);
  11747. if (result.isInvalid()) return ExprError();
  11748. E = result.get();
  11749. if (!E->isTypeDependent()) {
  11750. if (getLangOpts().CPlusPlus)
  11751. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  11752. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  11753. if (ERes.isInvalid())
  11754. return ExprError();
  11755. E = ERes.get();
  11756. QualType T = E->getType();
  11757. if (!T->isScalarType()) { // C99 6.8.4.1p1
  11758. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  11759. << T << E->getSourceRange();
  11760. return ExprError();
  11761. }
  11762. CheckBoolLikeConversion(E, Loc);
  11763. }
  11764. return E;
  11765. }
  11766. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  11767. Expr *SubExpr) {
  11768. if (!SubExpr)
  11769. return ExprError();
  11770. return CheckBooleanCondition(SubExpr, Loc);
  11771. }
  11772. namespace {
  11773. /// A visitor for rebuilding a call to an __unknown_any expression
  11774. /// to have an appropriate type.
  11775. struct RebuildUnknownAnyFunction
  11776. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  11777. Sema &S;
  11778. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  11779. ExprResult VisitStmt(Stmt *S) {
  11780. llvm_unreachable("unexpected statement!");
  11781. }
  11782. ExprResult VisitExpr(Expr *E) {
  11783. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  11784. << E->getSourceRange();
  11785. return ExprError();
  11786. }
  11787. /// Rebuild an expression which simply semantically wraps another
  11788. /// expression which it shares the type and value kind of.
  11789. template <class T> ExprResult rebuildSugarExpr(T *E) {
  11790. ExprResult SubResult = Visit(E->getSubExpr());
  11791. if (SubResult.isInvalid()) return ExprError();
  11792. Expr *SubExpr = SubResult.get();
  11793. E->setSubExpr(SubExpr);
  11794. E->setType(SubExpr->getType());
  11795. E->setValueKind(SubExpr->getValueKind());
  11796. assert(E->getObjectKind() == OK_Ordinary);
  11797. return E;
  11798. }
  11799. ExprResult VisitParenExpr(ParenExpr *E) {
  11800. return rebuildSugarExpr(E);
  11801. }
  11802. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  11803. return rebuildSugarExpr(E);
  11804. }
  11805. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  11806. ExprResult SubResult = Visit(E->getSubExpr());
  11807. if (SubResult.isInvalid()) return ExprError();
  11808. Expr *SubExpr = SubResult.get();
  11809. E->setSubExpr(SubExpr);
  11810. E->setType(S.Context.getPointerType(SubExpr->getType()));
  11811. assert(E->getValueKind() == VK_RValue);
  11812. assert(E->getObjectKind() == OK_Ordinary);
  11813. return E;
  11814. }
  11815. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  11816. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  11817. E->setType(VD->getType());
  11818. assert(E->getValueKind() == VK_RValue);
  11819. if (S.getLangOpts().CPlusPlus &&
  11820. !(isa<CXXMethodDecl>(VD) &&
  11821. cast<CXXMethodDecl>(VD)->isInstance()))
  11822. E->setValueKind(VK_LValue);
  11823. return E;
  11824. }
  11825. ExprResult VisitMemberExpr(MemberExpr *E) {
  11826. return resolveDecl(E, E->getMemberDecl());
  11827. }
  11828. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  11829. return resolveDecl(E, E->getDecl());
  11830. }
  11831. };
  11832. }
  11833. /// Given a function expression of unknown-any type, try to rebuild it
  11834. /// to have a function type.
  11835. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  11836. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  11837. if (Result.isInvalid()) return ExprError();
  11838. return S.DefaultFunctionArrayConversion(Result.get());
  11839. }
  11840. namespace {
  11841. /// A visitor for rebuilding an expression of type __unknown_anytype
  11842. /// into one which resolves the type directly on the referring
  11843. /// expression. Strict preservation of the original source
  11844. /// structure is not a goal.
  11845. struct RebuildUnknownAnyExpr
  11846. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  11847. Sema &S;
  11848. /// The current destination type.
  11849. QualType DestType;
  11850. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  11851. : S(S), DestType(CastType) {}
  11852. ExprResult VisitStmt(Stmt *S) {
  11853. llvm_unreachable("unexpected statement!");
  11854. }
  11855. ExprResult VisitExpr(Expr *E) {
  11856. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  11857. << E->getSourceRange();
  11858. return ExprError();
  11859. }
  11860. ExprResult VisitCallExpr(CallExpr *E);
  11861. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  11862. /// Rebuild an expression which simply semantically wraps another
  11863. /// expression which it shares the type and value kind of.
  11864. template <class T> ExprResult rebuildSugarExpr(T *E) {
  11865. ExprResult SubResult = Visit(E->getSubExpr());
  11866. if (SubResult.isInvalid()) return ExprError();
  11867. Expr *SubExpr = SubResult.get();
  11868. E->setSubExpr(SubExpr);
  11869. E->setType(SubExpr->getType());
  11870. E->setValueKind(SubExpr->getValueKind());
  11871. assert(E->getObjectKind() == OK_Ordinary);
  11872. return E;
  11873. }
  11874. ExprResult VisitParenExpr(ParenExpr *E) {
  11875. return rebuildSugarExpr(E);
  11876. }
  11877. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  11878. return rebuildSugarExpr(E);
  11879. }
  11880. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  11881. const PointerType *Ptr = DestType->getAs<PointerType>();
  11882. if (!Ptr) {
  11883. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  11884. << E->getSourceRange();
  11885. return ExprError();
  11886. }
  11887. assert(E->getValueKind() == VK_RValue);
  11888. assert(E->getObjectKind() == OK_Ordinary);
  11889. E->setType(DestType);
  11890. // Build the sub-expression as if it were an object of the pointee type.
  11891. DestType = Ptr->getPointeeType();
  11892. ExprResult SubResult = Visit(E->getSubExpr());
  11893. if (SubResult.isInvalid()) return ExprError();
  11894. E->setSubExpr(SubResult.get());
  11895. return E;
  11896. }
  11897. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  11898. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  11899. ExprResult VisitMemberExpr(MemberExpr *E) {
  11900. return resolveDecl(E, E->getMemberDecl());
  11901. }
  11902. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  11903. return resolveDecl(E, E->getDecl());
  11904. }
  11905. };
  11906. }
  11907. /// Rebuilds a call expression which yielded __unknown_anytype.
  11908. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  11909. Expr *CalleeExpr = E->getCallee();
  11910. enum FnKind {
  11911. FK_MemberFunction,
  11912. FK_FunctionPointer,
  11913. FK_BlockPointer
  11914. };
  11915. FnKind Kind;
  11916. QualType CalleeType = CalleeExpr->getType();
  11917. if (CalleeType == S.Context.BoundMemberTy) {
  11918. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  11919. Kind = FK_MemberFunction;
  11920. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  11921. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  11922. CalleeType = Ptr->getPointeeType();
  11923. Kind = FK_FunctionPointer;
  11924. } else {
  11925. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  11926. Kind = FK_BlockPointer;
  11927. }
  11928. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  11929. // Verify that this is a legal result type of a function.
  11930. if (DestType->isArrayType() || DestType->isFunctionType()) {
  11931. unsigned diagID = diag::err_func_returning_array_function;
  11932. if (Kind == FK_BlockPointer)
  11933. diagID = diag::err_block_returning_array_function;
  11934. S.Diag(E->getExprLoc(), diagID)
  11935. << DestType->isFunctionType() << DestType;
  11936. return ExprError();
  11937. }
  11938. // Otherwise, go ahead and set DestType as the call's result.
  11939. E->setType(DestType.getNonLValueExprType(S.Context));
  11940. E->setValueKind(Expr::getValueKindForType(DestType));
  11941. assert(E->getObjectKind() == OK_Ordinary);
  11942. // Rebuild the function type, replacing the result type with DestType.
  11943. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  11944. if (Proto) {
  11945. // __unknown_anytype(...) is a special case used by the debugger when
  11946. // it has no idea what a function's signature is.
  11947. //
  11948. // We want to build this call essentially under the K&R
  11949. // unprototyped rules, but making a FunctionNoProtoType in C++
  11950. // would foul up all sorts of assumptions. However, we cannot
  11951. // simply pass all arguments as variadic arguments, nor can we
  11952. // portably just call the function under a non-variadic type; see
  11953. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  11954. // However, it turns out that in practice it is generally safe to
  11955. // call a function declared as "A foo(B,C,D);" under the prototype
  11956. // "A foo(B,C,D,...);". The only known exception is with the
  11957. // Windows ABI, where any variadic function is implicitly cdecl
  11958. // regardless of its normal CC. Therefore we change the parameter
  11959. // types to match the types of the arguments.
  11960. //
  11961. // This is a hack, but it is far superior to moving the
  11962. // corresponding target-specific code from IR-gen to Sema/AST.
  11963. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  11964. SmallVector<QualType, 8> ArgTypes;
  11965. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  11966. ArgTypes.reserve(E->getNumArgs());
  11967. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  11968. Expr *Arg = E->getArg(i);
  11969. QualType ArgType = Arg->getType();
  11970. if (E->isLValue()) {
  11971. ArgType = S.Context.getLValueReferenceType(ArgType);
  11972. } else if (E->isXValue()) {
  11973. ArgType = S.Context.getRValueReferenceType(ArgType);
  11974. }
  11975. ArgTypes.push_back(ArgType);
  11976. }
  11977. ParamTypes = ArgTypes;
  11978. }
  11979. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  11980. Proto->getExtProtoInfo());
  11981. } else {
  11982. DestType = S.Context.getFunctionNoProtoType(DestType,
  11983. FnType->getExtInfo());
  11984. }
  11985. // Rebuild the appropriate pointer-to-function type.
  11986. switch (Kind) {
  11987. case FK_MemberFunction:
  11988. // Nothing to do.
  11989. break;
  11990. case FK_FunctionPointer:
  11991. DestType = S.Context.getPointerType(DestType);
  11992. break;
  11993. case FK_BlockPointer:
  11994. DestType = S.Context.getBlockPointerType(DestType);
  11995. break;
  11996. }
  11997. // Finally, we can recurse.
  11998. ExprResult CalleeResult = Visit(CalleeExpr);
  11999. if (!CalleeResult.isUsable()) return ExprError();
  12000. E->setCallee(CalleeResult.get());
  12001. // Bind a temporary if necessary.
  12002. return S.MaybeBindToTemporary(E);
  12003. }
  12004. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12005. // Verify that this is a legal result type of a call.
  12006. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12007. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12008. << DestType->isFunctionType() << DestType;
  12009. return ExprError();
  12010. }
  12011. // Rewrite the method result type if available.
  12012. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12013. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12014. Method->setReturnType(DestType);
  12015. }
  12016. // Change the type of the message.
  12017. E->setType(DestType.getNonReferenceType());
  12018. E->setValueKind(Expr::getValueKindForType(DestType));
  12019. return S.MaybeBindToTemporary(E);
  12020. }
  12021. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12022. // The only case we should ever see here is a function-to-pointer decay.
  12023. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12024. assert(E->getValueKind() == VK_RValue);
  12025. assert(E->getObjectKind() == OK_Ordinary);
  12026. E->setType(DestType);
  12027. // Rebuild the sub-expression as the pointee (function) type.
  12028. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12029. ExprResult Result = Visit(E->getSubExpr());
  12030. if (!Result.isUsable()) return ExprError();
  12031. E->setSubExpr(Result.get());
  12032. return E;
  12033. } else if (E->getCastKind() == CK_LValueToRValue) {
  12034. assert(E->getValueKind() == VK_RValue);
  12035. assert(E->getObjectKind() == OK_Ordinary);
  12036. assert(isa<BlockPointerType>(E->getType()));
  12037. E->setType(DestType);
  12038. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12039. DestType = S.Context.getLValueReferenceType(DestType);
  12040. ExprResult Result = Visit(E->getSubExpr());
  12041. if (!Result.isUsable()) return ExprError();
  12042. E->setSubExpr(Result.get());
  12043. return E;
  12044. } else {
  12045. llvm_unreachable("Unhandled cast type!");
  12046. }
  12047. }
  12048. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12049. ExprValueKind ValueKind = VK_LValue;
  12050. QualType Type = DestType;
  12051. // We know how to make this work for certain kinds of decls:
  12052. // - functions
  12053. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12054. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12055. DestType = Ptr->getPointeeType();
  12056. ExprResult Result = resolveDecl(E, VD);
  12057. if (Result.isInvalid()) return ExprError();
  12058. return S.ImpCastExprToType(Result.get(), Type,
  12059. CK_FunctionToPointerDecay, VK_RValue);
  12060. }
  12061. if (!Type->isFunctionType()) {
  12062. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12063. << VD << E->getSourceRange();
  12064. return ExprError();
  12065. }
  12066. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12067. // We must match the FunctionDecl's type to the hack introduced in
  12068. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12069. // type. See the lengthy commentary in that routine.
  12070. QualType FDT = FD->getType();
  12071. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12072. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12073. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12074. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12075. SourceLocation Loc = FD->getLocation();
  12076. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12077. FD->getDeclContext(),
  12078. Loc, Loc, FD->getNameInfo().getName(),
  12079. DestType, FD->getTypeSourceInfo(),
  12080. SC_None, false/*isInlineSpecified*/,
  12081. FD->hasPrototype(),
  12082. false/*isConstexprSpecified*/);
  12083. if (FD->getQualifier())
  12084. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12085. SmallVector<ParmVarDecl*, 16> Params;
  12086. for (const auto &AI : FT->param_types()) {
  12087. ParmVarDecl *Param =
  12088. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12089. Param->setScopeInfo(0, Params.size());
  12090. Params.push_back(Param);
  12091. }
  12092. NewFD->setParams(Params);
  12093. DRE->setDecl(NewFD);
  12094. VD = DRE->getDecl();
  12095. }
  12096. }
  12097. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12098. if (MD->isInstance()) {
  12099. ValueKind = VK_RValue;
  12100. Type = S.Context.BoundMemberTy;
  12101. }
  12102. // Function references aren't l-values in C.
  12103. if (!S.getLangOpts().CPlusPlus)
  12104. ValueKind = VK_RValue;
  12105. // - variables
  12106. } else if (isa<VarDecl>(VD)) {
  12107. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12108. Type = RefTy->getPointeeType();
  12109. } else if (Type->isFunctionType()) {
  12110. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12111. << VD << E->getSourceRange();
  12112. return ExprError();
  12113. }
  12114. // - nothing else
  12115. } else {
  12116. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12117. << VD << E->getSourceRange();
  12118. return ExprError();
  12119. }
  12120. // Modifying the declaration like this is friendly to IR-gen but
  12121. // also really dangerous.
  12122. VD->setType(DestType);
  12123. E->setType(Type);
  12124. E->setValueKind(ValueKind);
  12125. return E;
  12126. }
  12127. /// Check a cast of an unknown-any type. We intentionally only
  12128. /// trigger this for C-style casts.
  12129. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12130. Expr *CastExpr, CastKind &CastKind,
  12131. ExprValueKind &VK, CXXCastPath &Path) {
  12132. // Rewrite the casted expression from scratch.
  12133. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12134. if (!result.isUsable()) return ExprError();
  12135. CastExpr = result.get();
  12136. VK = CastExpr->getValueKind();
  12137. CastKind = CK_NoOp;
  12138. return CastExpr;
  12139. }
  12140. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12141. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12142. }
  12143. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12144. Expr *arg, QualType &paramType) {
  12145. // If the syntactic form of the argument is not an explicit cast of
  12146. // any sort, just do default argument promotion.
  12147. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12148. if (!castArg) {
  12149. ExprResult result = DefaultArgumentPromotion(arg);
  12150. if (result.isInvalid()) return ExprError();
  12151. paramType = result.get()->getType();
  12152. return result;
  12153. }
  12154. // Otherwise, use the type that was written in the explicit cast.
  12155. assert(!arg->hasPlaceholderType());
  12156. paramType = castArg->getTypeAsWritten();
  12157. // Copy-initialize a parameter of that type.
  12158. InitializedEntity entity =
  12159. InitializedEntity::InitializeParameter(Context, paramType,
  12160. /*consumed*/ false);
  12161. return PerformCopyInitialization(entity, callLoc, arg);
  12162. }
  12163. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12164. Expr *orig = E;
  12165. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12166. while (true) {
  12167. E = E->IgnoreParenImpCasts();
  12168. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12169. E = call->getCallee();
  12170. diagID = diag::err_uncasted_call_of_unknown_any;
  12171. } else {
  12172. break;
  12173. }
  12174. }
  12175. SourceLocation loc;
  12176. NamedDecl *d;
  12177. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12178. loc = ref->getLocation();
  12179. d = ref->getDecl();
  12180. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12181. loc = mem->getMemberLoc();
  12182. d = mem->getMemberDecl();
  12183. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12184. diagID = diag::err_uncasted_call_of_unknown_any;
  12185. loc = msg->getSelectorStartLoc();
  12186. d = msg->getMethodDecl();
  12187. if (!d) {
  12188. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12189. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12190. << orig->getSourceRange();
  12191. return ExprError();
  12192. }
  12193. } else {
  12194. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12195. << E->getSourceRange();
  12196. return ExprError();
  12197. }
  12198. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12199. // Never recoverable.
  12200. return ExprError();
  12201. }
  12202. /// Check for operands with placeholder types and complain if found.
  12203. /// Returns true if there was an error and no recovery was possible.
  12204. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12205. if (!getLangOpts().CPlusPlus) {
  12206. // C cannot handle TypoExpr nodes on either side of a binop because it
  12207. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12208. // been dealt with before checking the operands.
  12209. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12210. if (!Result.isUsable()) return ExprError();
  12211. E = Result.get();
  12212. }
  12213. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12214. if (!placeholderType) return E;
  12215. switch (placeholderType->getKind()) {
  12216. // Overloaded expressions.
  12217. case BuiltinType::Overload: {
  12218. // Try to resolve a single function template specialization.
  12219. // This is obligatory.
  12220. ExprResult result = E;
  12221. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12222. return result;
  12223. // If that failed, try to recover with a call.
  12224. } else {
  12225. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12226. /*complain*/ true);
  12227. return result;
  12228. }
  12229. }
  12230. // Bound member functions.
  12231. case BuiltinType::BoundMember: {
  12232. ExprResult result = E;
  12233. tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
  12234. /*complain*/ true);
  12235. return result;
  12236. }
  12237. // ARC unbridged casts.
  12238. case BuiltinType::ARCUnbridgedCast: {
  12239. Expr *realCast = stripARCUnbridgedCast(E);
  12240. diagnoseARCUnbridgedCast(realCast);
  12241. return realCast;
  12242. }
  12243. // Expressions of unknown type.
  12244. case BuiltinType::UnknownAny:
  12245. return diagnoseUnknownAnyExpr(*this, E);
  12246. // Pseudo-objects.
  12247. case BuiltinType::PseudoObject:
  12248. return checkPseudoObjectRValue(E);
  12249. case BuiltinType::BuiltinFn: {
  12250. // Accept __noop without parens by implicitly converting it to a call expr.
  12251. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12252. if (DRE) {
  12253. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12254. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12255. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12256. CK_BuiltinFnToFnPtr).get();
  12257. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12258. VK_RValue, SourceLocation());
  12259. }
  12260. }
  12261. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12262. return ExprError();
  12263. }
  12264. // Everything else should be impossible.
  12265. #define BUILTIN_TYPE(Id, SingletonId) \
  12266. case BuiltinType::Id:
  12267. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12268. #include "clang/AST/BuiltinTypes.def"
  12269. break;
  12270. }
  12271. llvm_unreachable("invalid placeholder type!");
  12272. }
  12273. bool Sema::CheckCaseExpression(Expr *E) {
  12274. if (E->isTypeDependent())
  12275. return true;
  12276. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12277. return E->getType()->isIntegralOrEnumerationType();
  12278. return false;
  12279. }
  12280. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12281. ExprResult
  12282. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12283. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12284. "Unknown Objective-C Boolean value!");
  12285. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12286. if (!Context.getBOOLDecl()) {
  12287. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12288. Sema::LookupOrdinaryName);
  12289. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12290. NamedDecl *ND = Result.getFoundDecl();
  12291. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12292. Context.setBOOLDecl(TD);
  12293. }
  12294. }
  12295. if (Context.getBOOLDecl())
  12296. BoolT = Context.getBOOLType();
  12297. return new (Context)
  12298. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12299. }