SemaExpr.cpp 553 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341
  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 bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
  78. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  79. if (!OMD)
  80. return false;
  81. const ObjCInterfaceDecl *OID = OMD->getClassInterface();
  82. if (!OID)
  83. return false;
  84. for (const ObjCCategoryDecl *Cat : OID->visible_categories())
  85. if (ObjCMethodDecl *CatMeth =
  86. Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
  87. if (!CatMeth->hasAttr<AvailabilityAttr>())
  88. return true;
  89. return false;
  90. }
  91. static AvailabilityResult
  92. DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
  93. const ObjCInterfaceDecl *UnknownObjCClass,
  94. bool ObjCPropertyAccess) {
  95. // See if this declaration is unavailable or deprecated.
  96. std::string Message;
  97. AvailabilityResult Result = D->getAvailability(&Message);
  98. // For typedefs, if the typedef declaration appears available look
  99. // to the underlying type to see if it is more restrictive.
  100. while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  101. if (Result == AR_Available) {
  102. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  103. D = TT->getDecl();
  104. Result = D->getAvailability(&Message);
  105. continue;
  106. }
  107. }
  108. break;
  109. }
  110. // Forward class declarations get their attributes from their definition.
  111. if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
  112. if (IDecl->getDefinition()) {
  113. D = IDecl->getDefinition();
  114. Result = D->getAvailability(&Message);
  115. }
  116. }
  117. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
  118. if (Result == AR_Available) {
  119. const DeclContext *DC = ECD->getDeclContext();
  120. if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
  121. Result = TheEnumDecl->getAvailability(&Message);
  122. }
  123. const ObjCPropertyDecl *ObjCPDecl = nullptr;
  124. if (Result == AR_Deprecated || Result == AR_Unavailable ||
  125. AR_NotYetIntroduced) {
  126. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  127. if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
  128. AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
  129. if (PDeclResult == Result)
  130. ObjCPDecl = PD;
  131. }
  132. }
  133. }
  134. switch (Result) {
  135. case AR_Available:
  136. break;
  137. case AR_Deprecated:
  138. if (S.getCurContextAvailability() != AR_Deprecated)
  139. S.EmitAvailabilityWarning(Sema::AD_Deprecation,
  140. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  141. ObjCPropertyAccess);
  142. break;
  143. case AR_NotYetIntroduced: {
  144. // Don't do this for enums, they can't be redeclared.
  145. if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
  146. break;
  147. bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
  148. // Objective-C method declarations in categories are not modelled as
  149. // redeclarations, so manually look for a redeclaration in a category
  150. // if necessary.
  151. if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
  152. Warn = false;
  153. // In general, D will point to the most recent redeclaration. However,
  154. // for `@class A;` decls, this isn't true -- manually go through the
  155. // redecl chain in that case.
  156. if (Warn && isa<ObjCInterfaceDecl>(D))
  157. for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
  158. Redecl = Redecl->getPreviousDecl())
  159. if (!Redecl->hasAttr<AvailabilityAttr>() ||
  160. Redecl->getAttr<AvailabilityAttr>()->isInherited())
  161. Warn = false;
  162. if (Warn)
  163. S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
  164. UnknownObjCClass, ObjCPDecl,
  165. ObjCPropertyAccess);
  166. break;
  167. }
  168. case AR_Unavailable:
  169. if (S.getCurContextAvailability() != AR_Unavailable)
  170. S.EmitAvailabilityWarning(Sema::AD_Unavailable,
  171. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  172. ObjCPropertyAccess);
  173. break;
  174. }
  175. return Result;
  176. }
  177. /// \brief Emit a note explaining that this function is deleted.
  178. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  179. assert(Decl->isDeleted());
  180. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  181. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  182. // If the method was explicitly defaulted, point at that declaration.
  183. if (!Method->isImplicit())
  184. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  185. // Try to diagnose why this special member function was implicitly
  186. // deleted. This might fail, if that reason no longer applies.
  187. CXXSpecialMember CSM = getSpecialMember(Method);
  188. if (CSM != CXXInvalid)
  189. ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
  190. return;
  191. }
  192. if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
  193. if (CXXConstructorDecl *BaseCD =
  194. const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
  195. Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
  196. if (BaseCD->isDeleted()) {
  197. NoteDeletedFunction(BaseCD);
  198. } else {
  199. // FIXME: An explanation of why exactly it can't be inherited
  200. // would be nice.
  201. Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
  202. }
  203. return;
  204. }
  205. }
  206. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  207. << Decl << true;
  208. }
  209. /// \brief Determine whether a FunctionDecl was ever declared with an
  210. /// explicit storage class.
  211. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  212. for (auto I : D->redecls()) {
  213. if (I->getStorageClass() != SC_None)
  214. return true;
  215. }
  216. return false;
  217. }
  218. /// \brief Check whether we're in an extern inline function and referring to a
  219. /// variable or function with internal linkage (C11 6.7.4p3).
  220. ///
  221. /// This is only a warning because we used to silently accept this code, but
  222. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  223. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  224. /// and so while there may still be user mistakes, most of the time we can't
  225. /// prove that there are errors.
  226. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  227. const NamedDecl *D,
  228. SourceLocation Loc) {
  229. // This is disabled under C++; there are too many ways for this to fire in
  230. // contexts where the warning is a false positive, or where it is technically
  231. // correct but benign.
  232. if (S.getLangOpts().CPlusPlus)
  233. return;
  234. // Check if this is an inlined function or method.
  235. FunctionDecl *Current = S.getCurFunctionDecl();
  236. if (!Current)
  237. return;
  238. if (!Current->isInlined())
  239. return;
  240. if (!Current->isExternallyVisible())
  241. return;
  242. // Check if the decl has internal linkage.
  243. if (D->getFormalLinkage() != InternalLinkage)
  244. return;
  245. // Downgrade from ExtWarn to Extension if
  246. // (1) the supposedly external inline function is in the main file,
  247. // and probably won't be included anywhere else.
  248. // (2) the thing we're referencing is a pure function.
  249. // (3) the thing we're referencing is another inline function.
  250. // This last can give us false negatives, but it's better than warning on
  251. // wrappers for simple C library functions.
  252. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  253. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  254. if (!DowngradeWarning && UsedFn)
  255. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  256. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  257. : diag::ext_internal_in_extern_inline)
  258. << /*IsVar=*/!UsedFn << D;
  259. S.MaybeSuggestAddingStaticToDecl(Current);
  260. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  261. << D;
  262. }
  263. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  264. const FunctionDecl *First = Cur->getFirstDecl();
  265. // Suggest "static" on the function, if possible.
  266. if (!hasAnyExplicitStorageClass(First)) {
  267. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  268. Diag(DeclBegin, diag::note_convert_inline_to_static)
  269. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  270. }
  271. }
  272. /// \brief Determine whether the use of this declaration is valid, and
  273. /// emit any corresponding diagnostics.
  274. ///
  275. /// This routine diagnoses various problems with referencing
  276. /// declarations that can occur when using a declaration. For example,
  277. /// it might warn if a deprecated or unavailable declaration is being
  278. /// used, or produce an error (and return true) if a C++0x deleted
  279. /// function is being used.
  280. ///
  281. /// \returns true if there was an error (this declaration cannot be
  282. /// referenced), false otherwise.
  283. ///
  284. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  285. const ObjCInterfaceDecl *UnknownObjCClass,
  286. bool ObjCPropertyAccess) {
  287. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  288. // If there were any diagnostics suppressed by template argument deduction,
  289. // emit them now.
  290. SuppressedDiagnosticsMap::iterator
  291. Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  292. if (Pos != SuppressedDiagnostics.end()) {
  293. SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
  294. for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
  295. Diag(Suppressed[I].first, Suppressed[I].second);
  296. // Clear out the list of suppressed diagnostics, so that we don't emit
  297. // them again for this specialization. However, we don't obsolete this
  298. // entry from the table, because we want to avoid ever emitting these
  299. // diagnostics again.
  300. Suppressed.clear();
  301. }
  302. // C++ [basic.start.main]p3:
  303. // The function 'main' shall not be used within a program.
  304. if (cast<FunctionDecl>(D)->isMain())
  305. Diag(Loc, diag::ext_main_used);
  306. }
  307. // See if this is an auto-typed variable whose initializer we are parsing.
  308. if (ParsingInitForAutoVars.count(D)) {
  309. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  310. << D->getDeclName();
  311. return true;
  312. }
  313. // See if this is a deleted function.
  314. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  315. if (FD->isDeleted()) {
  316. Diag(Loc, diag::err_deleted_function_use);
  317. NoteDeletedFunction(FD);
  318. return true;
  319. }
  320. // If the function has a deduced return type, and we can't deduce it,
  321. // then we can't use it either.
  322. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  323. DeduceReturnType(FD, Loc))
  324. return true;
  325. }
  326. DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
  327. ObjCPropertyAccess);
  328. DiagnoseUnusedOfDecl(*this, D, Loc);
  329. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  330. return false;
  331. }
  332. /// \brief Retrieve the message suffix that should be added to a
  333. /// diagnostic complaining about the given function being deleted or
  334. /// unavailable.
  335. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  336. std::string Message;
  337. if (FD->getAvailability(&Message))
  338. return ": " + Message;
  339. return std::string();
  340. }
  341. /// DiagnoseSentinelCalls - This routine checks whether a call or
  342. /// message-send is to a declaration with the sentinel attribute, and
  343. /// if so, it checks that the requirements of the sentinel are
  344. /// satisfied.
  345. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  346. ArrayRef<Expr *> Args) {
  347. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  348. if (!attr)
  349. return;
  350. // The number of formal parameters of the declaration.
  351. unsigned numFormalParams;
  352. // The kind of declaration. This is also an index into a %select in
  353. // the diagnostic.
  354. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  355. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  356. numFormalParams = MD->param_size();
  357. calleeType = CT_Method;
  358. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  359. numFormalParams = FD->param_size();
  360. calleeType = CT_Function;
  361. } else if (isa<VarDecl>(D)) {
  362. QualType type = cast<ValueDecl>(D)->getType();
  363. const FunctionType *fn = nullptr;
  364. if (const PointerType *ptr = type->getAs<PointerType>()) {
  365. fn = ptr->getPointeeType()->getAs<FunctionType>();
  366. if (!fn) return;
  367. calleeType = CT_Function;
  368. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  369. fn = ptr->getPointeeType()->castAs<FunctionType>();
  370. calleeType = CT_Block;
  371. } else {
  372. return;
  373. }
  374. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  375. numFormalParams = proto->getNumParams();
  376. } else {
  377. numFormalParams = 0;
  378. }
  379. } else {
  380. return;
  381. }
  382. // "nullPos" is the number of formal parameters at the end which
  383. // effectively count as part of the variadic arguments. This is
  384. // useful if you would prefer to not have *any* formal parameters,
  385. // but the language forces you to have at least one.
  386. unsigned nullPos = attr->getNullPos();
  387. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  388. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  389. // The number of arguments which should follow the sentinel.
  390. unsigned numArgsAfterSentinel = attr->getSentinel();
  391. // If there aren't enough arguments for all the formal parameters,
  392. // the sentinel, and the args after the sentinel, complain.
  393. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  394. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  395. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  396. return;
  397. }
  398. // Otherwise, find the sentinel expression.
  399. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  400. if (!sentinelExpr) return;
  401. if (sentinelExpr->isValueDependent()) return;
  402. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  403. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  404. // or 'NULL' if those are actually defined in the context. Only use
  405. // 'nil' for ObjC methods, where it's much more likely that the
  406. // variadic arguments form a list of object pointers.
  407. SourceLocation MissingNilLoc
  408. = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
  409. std::string NullValue;
  410. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  411. NullValue = "nil";
  412. else if (getLangOpts().CPlusPlus11)
  413. NullValue = "nullptr";
  414. else if (PP.isMacroDefined("NULL"))
  415. NullValue = "NULL";
  416. else
  417. NullValue = "(void*) 0";
  418. if (MissingNilLoc.isInvalid())
  419. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  420. else
  421. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  422. << int(calleeType)
  423. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  424. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  425. }
  426. SourceRange Sema::getExprRange(Expr *E) const {
  427. return E ? E->getSourceRange() : SourceRange();
  428. }
  429. //===----------------------------------------------------------------------===//
  430. // Standard Promotions and Conversions
  431. //===----------------------------------------------------------------------===//
  432. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  433. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
  434. // Handle any placeholder expressions which made it here.
  435. if (E->getType()->isPlaceholderType()) {
  436. ExprResult result = CheckPlaceholderExpr(E);
  437. if (result.isInvalid()) return ExprError();
  438. E = result.get();
  439. }
  440. QualType Ty = E->getType();
  441. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  442. if (Ty->isFunctionType()) {
  443. // If we are here, we are not calling a function but taking
  444. // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
  445. if (getLangOpts().OpenCL) {
  446. Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
  447. return ExprError();
  448. }
  449. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  450. CK_FunctionToPointerDecay).get();
  451. } else if (Ty->isArrayType()) {
  452. // In C90 mode, arrays only promote to pointers if the array expression is
  453. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  454. // type 'array of type' is converted to an expression that has type 'pointer
  455. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  456. // that has type 'array of type' ...". The relevant change is "an lvalue"
  457. // (C90) to "an expression" (C99).
  458. //
  459. // C++ 4.2p1:
  460. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  461. // T" can be converted to an rvalue of type "pointer to T".
  462. //
  463. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  464. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  465. CK_ArrayToPointerDecay).get();
  466. }
  467. return E;
  468. }
  469. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  470. // Check to see if we are dereferencing a null pointer. If so,
  471. // and if not volatile-qualified, this is undefined behavior that the
  472. // optimizer will delete, so warn about it. People sometimes try to use this
  473. // to get a deterministic trap and are surprised by clang's behavior. This
  474. // only handles the pattern "*null", which is a very syntactic check.
  475. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  476. if (UO->getOpcode() == UO_Deref &&
  477. UO->getSubExpr()->IgnoreParenCasts()->
  478. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  479. !UO->getType().isVolatileQualified()) {
  480. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  481. S.PDiag(diag::warn_indirection_through_null)
  482. << UO->getSubExpr()->getSourceRange());
  483. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  484. S.PDiag(diag::note_indirection_through_null));
  485. }
  486. }
  487. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  488. SourceLocation AssignLoc,
  489. const Expr* RHS) {
  490. const ObjCIvarDecl *IV = OIRE->getDecl();
  491. if (!IV)
  492. return;
  493. DeclarationName MemberName = IV->getDeclName();
  494. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  495. if (!Member || !Member->isStr("isa"))
  496. return;
  497. const Expr *Base = OIRE->getBase();
  498. QualType BaseType = Base->getType();
  499. if (OIRE->isArrow())
  500. BaseType = BaseType->getPointeeType();
  501. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  502. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  503. ObjCInterfaceDecl *ClassDeclared = nullptr;
  504. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  505. if (!ClassDeclared->getSuperClass()
  506. && (*ClassDeclared->ivar_begin()) == IV) {
  507. if (RHS) {
  508. NamedDecl *ObjectSetClass =
  509. S.LookupSingleName(S.TUScope,
  510. &S.Context.Idents.get("object_setClass"),
  511. SourceLocation(), S.LookupOrdinaryName);
  512. if (ObjectSetClass) {
  513. SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
  514. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  515. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  516. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  517. AssignLoc), ",") <<
  518. FixItHint::CreateInsertion(RHSLocEnd, ")");
  519. }
  520. else
  521. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  522. } else {
  523. NamedDecl *ObjectGetClass =
  524. S.LookupSingleName(S.TUScope,
  525. &S.Context.Idents.get("object_getClass"),
  526. SourceLocation(), S.LookupOrdinaryName);
  527. if (ObjectGetClass)
  528. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  529. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  530. FixItHint::CreateReplacement(
  531. SourceRange(OIRE->getOpLoc(),
  532. OIRE->getLocEnd()), ")");
  533. else
  534. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  535. }
  536. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  537. }
  538. }
  539. }
  540. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  541. // Handle any placeholder expressions which made it here.
  542. if (E->getType()->isPlaceholderType()) {
  543. ExprResult result = CheckPlaceholderExpr(E);
  544. if (result.isInvalid()) return ExprError();
  545. E = result.get();
  546. }
  547. // C++ [conv.lval]p1:
  548. // A glvalue of a non-function, non-array type T can be
  549. // converted to a prvalue.
  550. if (!E->isGLValue()) return E;
  551. QualType T = E->getType();
  552. assert(!T.isNull() && "r-value conversion on typeless expression?");
  553. // We don't want to throw lvalue-to-rvalue casts on top of
  554. // expressions of certain types in C++.
  555. if (getLangOpts().CPlusPlus &&
  556. (E->getType() == Context.OverloadTy ||
  557. T->isDependentType() ||
  558. T->isRecordType()))
  559. return E;
  560. // The C standard is actually really unclear on this point, and
  561. // DR106 tells us what the result should be but not why. It's
  562. // generally best to say that void types just doesn't undergo
  563. // lvalue-to-rvalue at all. Note that expressions of unqualified
  564. // 'void' type are never l-values, but qualified void can be.
  565. if (T->isVoidType())
  566. return E;
  567. // OpenCL usually rejects direct accesses to values of 'half' type.
  568. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
  569. T->isHalfType()) {
  570. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  571. << 0 << T;
  572. return ExprError();
  573. }
  574. CheckForNullPointerDereference(*this, E);
  575. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  576. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  577. &Context.Idents.get("object_getClass"),
  578. SourceLocation(), LookupOrdinaryName);
  579. if (ObjectGetClass)
  580. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  581. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  582. FixItHint::CreateReplacement(
  583. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  584. else
  585. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  586. }
  587. else if (const ObjCIvarRefExpr *OIRE =
  588. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  589. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  590. // C++ [conv.lval]p1:
  591. // [...] If T is a non-class type, the type of the prvalue is the
  592. // cv-unqualified version of T. Otherwise, the type of the
  593. // rvalue is T.
  594. //
  595. // C99 6.3.2.1p2:
  596. // If the lvalue has qualified type, the value has the unqualified
  597. // version of the type of the lvalue; otherwise, the value has the
  598. // type of the lvalue.
  599. if (T.hasQualifiers())
  600. T = T.getUnqualifiedType();
  601. UpdateMarkingForLValueToRValue(E);
  602. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  603. // balance that.
  604. if (getLangOpts().ObjCAutoRefCount &&
  605. E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  606. ExprNeedsCleanups = true;
  607. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  608. nullptr, VK_RValue);
  609. // C11 6.3.2.1p2:
  610. // ... if the lvalue has atomic type, the value has the non-atomic version
  611. // of the type of the lvalue ...
  612. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  613. T = Atomic->getValueType().getUnqualifiedType();
  614. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  615. nullptr, VK_RValue);
  616. }
  617. return Res;
  618. }
  619. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
  620. ExprResult Res = DefaultFunctionArrayConversion(E);
  621. if (Res.isInvalid())
  622. return ExprError();
  623. Res = DefaultLvalueConversion(Res.get());
  624. if (Res.isInvalid())
  625. return ExprError();
  626. return Res;
  627. }
  628. /// CallExprUnaryConversions - a special case of an unary conversion
  629. /// performed on a function designator of a call expression.
  630. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  631. QualType Ty = E->getType();
  632. ExprResult Res = E;
  633. // Only do implicit cast for a function type, but not for a pointer
  634. // to function type.
  635. if (Ty->isFunctionType()) {
  636. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  637. CK_FunctionToPointerDecay).get();
  638. if (Res.isInvalid())
  639. return ExprError();
  640. }
  641. Res = DefaultLvalueConversion(Res.get());
  642. if (Res.isInvalid())
  643. return ExprError();
  644. return Res.get();
  645. }
  646. /// UsualUnaryConversions - Performs various conversions that are common to most
  647. /// operators (C99 6.3). The conversions of array and function types are
  648. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  649. /// apply if the array is an argument to the sizeof or address (&) operators.
  650. /// In these instances, this routine should *not* be called.
  651. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  652. // First, convert to an r-value.
  653. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  654. if (Res.isInvalid())
  655. return ExprError();
  656. E = Res.get();
  657. QualType Ty = E->getType();
  658. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  659. // Half FP have to be promoted to float unless it is natively supported
  660. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  661. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  662. // Try to perform integral promotions if the object has a theoretically
  663. // promotable type.
  664. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  665. // C99 6.3.1.1p2:
  666. //
  667. // The following may be used in an expression wherever an int or
  668. // unsigned int may be used:
  669. // - an object or expression with an integer type whose integer
  670. // conversion rank is less than or equal to the rank of int
  671. // and unsigned int.
  672. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  673. //
  674. // If an int can represent all values of the original type, the
  675. // value is converted to an int; otherwise, it is converted to an
  676. // unsigned int. These are called the integer promotions. All
  677. // other types are unchanged by the integer promotions.
  678. QualType PTy = Context.isPromotableBitField(E);
  679. if (!PTy.isNull()) {
  680. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  681. return E;
  682. }
  683. if (Ty->isPromotableIntegerType()) {
  684. QualType PT = Context.getPromotedIntegerType(Ty);
  685. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  686. return E;
  687. }
  688. }
  689. return E;
  690. }
  691. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  692. /// do not have a prototype. Arguments that have type float or __fp16
  693. /// are promoted to double. All other argument types are converted by
  694. /// UsualUnaryConversions().
  695. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  696. QualType Ty = E->getType();
  697. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  698. ExprResult Res = UsualUnaryConversions(E);
  699. if (Res.isInvalid())
  700. return ExprError();
  701. E = Res.get();
  702. // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  703. // double.
  704. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  705. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  706. BTy->getKind() == BuiltinType::Float))
  707. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  708. // C++ performs lvalue-to-rvalue conversion as a default argument
  709. // promotion, even on class types, but note:
  710. // C++11 [conv.lval]p2:
  711. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  712. // operand or a subexpression thereof the value contained in the
  713. // referenced object is not accessed. Otherwise, if the glvalue
  714. // has a class type, the conversion copy-initializes a temporary
  715. // of type T from the glvalue and the result of the conversion
  716. // is a prvalue for the temporary.
  717. // FIXME: add some way to gate this entire thing for correctness in
  718. // potentially potentially evaluated contexts.
  719. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  720. ExprResult Temp = PerformCopyInitialization(
  721. InitializedEntity::InitializeTemporary(E->getType()),
  722. E->getExprLoc(), E);
  723. if (Temp.isInvalid())
  724. return ExprError();
  725. E = Temp.get();
  726. }
  727. return E;
  728. }
  729. /// Determine the degree of POD-ness for an expression.
  730. /// Incomplete types are considered POD, since this check can be performed
  731. /// when we're in an unevaluated context.
  732. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  733. if (Ty->isIncompleteType()) {
  734. // C++11 [expr.call]p7:
  735. // After these conversions, if the argument does not have arithmetic,
  736. // enumeration, pointer, pointer to member, or class type, the program
  737. // is ill-formed.
  738. //
  739. // Since we've already performed array-to-pointer and function-to-pointer
  740. // decay, the only such type in C++ is cv void. This also handles
  741. // initializer lists as variadic arguments.
  742. if (Ty->isVoidType())
  743. return VAK_Invalid;
  744. if (Ty->isObjCObjectType())
  745. return VAK_Invalid;
  746. return VAK_Valid;
  747. }
  748. if (Ty.isCXX98PODType(Context))
  749. return VAK_Valid;
  750. // C++11 [expr.call]p7:
  751. // Passing a potentially-evaluated argument of class type (Clause 9)
  752. // having a non-trivial copy constructor, a non-trivial move constructor,
  753. // or a non-trivial destructor, with no corresponding parameter,
  754. // is conditionally-supported with implementation-defined semantics.
  755. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  756. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  757. if (!Record->hasNonTrivialCopyConstructor() &&
  758. !Record->hasNonTrivialMoveConstructor() &&
  759. !Record->hasNonTrivialDestructor())
  760. return VAK_ValidInCXX11;
  761. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  762. return VAK_Valid;
  763. if (Ty->isObjCObjectType())
  764. return VAK_Invalid;
  765. if (getLangOpts().MSVCCompat)
  766. return VAK_MSVCUndefined;
  767. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  768. // permitted to reject them. We should consider doing so.
  769. return VAK_Undefined;
  770. }
  771. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  772. // Don't allow one to pass an Objective-C interface to a vararg.
  773. const QualType &Ty = E->getType();
  774. VarArgKind VAK = isValidVarArgType(Ty);
  775. // Complain about passing non-POD types through varargs.
  776. switch (VAK) {
  777. case VAK_ValidInCXX11:
  778. DiagRuntimeBehavior(
  779. E->getLocStart(), nullptr,
  780. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  781. << Ty << CT);
  782. // Fall through.
  783. case VAK_Valid:
  784. if (Ty->isRecordType()) {
  785. // This is unlikely to be what the user intended. If the class has a
  786. // 'c_str' member function, the user probably meant to call that.
  787. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  788. PDiag(diag::warn_pass_class_arg_to_vararg)
  789. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  790. }
  791. break;
  792. case VAK_Undefined:
  793. case VAK_MSVCUndefined:
  794. DiagRuntimeBehavior(
  795. E->getLocStart(), nullptr,
  796. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  797. << getLangOpts().CPlusPlus11 << Ty << CT);
  798. break;
  799. case VAK_Invalid:
  800. if (Ty->isObjCObjectType())
  801. DiagRuntimeBehavior(
  802. E->getLocStart(), nullptr,
  803. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  804. << Ty << CT);
  805. else
  806. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  807. << isa<InitListExpr>(E) << Ty << CT;
  808. break;
  809. }
  810. }
  811. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  812. /// will create a trap if the resulting type is not a POD type.
  813. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  814. FunctionDecl *FDecl) {
  815. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  816. // Strip the unbridged-cast placeholder expression off, if applicable.
  817. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  818. (CT == VariadicMethod ||
  819. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  820. E = stripARCUnbridgedCast(E);
  821. // Otherwise, do normal placeholder checking.
  822. } else {
  823. ExprResult ExprRes = CheckPlaceholderExpr(E);
  824. if (ExprRes.isInvalid())
  825. return ExprError();
  826. E = ExprRes.get();
  827. }
  828. }
  829. ExprResult ExprRes = DefaultArgumentPromotion(E);
  830. if (ExprRes.isInvalid())
  831. return ExprError();
  832. E = ExprRes.get();
  833. // Diagnostics regarding non-POD argument types are
  834. // emitted along with format string checking in Sema::CheckFunctionCall().
  835. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  836. // Turn this into a trap.
  837. CXXScopeSpec SS;
  838. SourceLocation TemplateKWLoc;
  839. UnqualifiedId Name;
  840. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  841. E->getLocStart());
  842. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  843. Name, true, false);
  844. if (TrapFn.isInvalid())
  845. return ExprError();
  846. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  847. E->getLocStart(), None,
  848. E->getLocEnd());
  849. if (Call.isInvalid())
  850. return ExprError();
  851. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  852. Call.get(), E);
  853. if (Comma.isInvalid())
  854. return ExprError();
  855. return Comma.get();
  856. }
  857. if (!getLangOpts().CPlusPlus &&
  858. RequireCompleteType(E->getExprLoc(), E->getType(),
  859. diag::err_call_incomplete_argument))
  860. return ExprError();
  861. return E;
  862. }
  863. /// \brief Converts an integer to complex float type. Helper function of
  864. /// UsualArithmeticConversions()
  865. ///
  866. /// \return false if the integer expression is an integer type and is
  867. /// successfully converted to the complex type.
  868. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  869. ExprResult &ComplexExpr,
  870. QualType IntTy,
  871. QualType ComplexTy,
  872. bool SkipCast) {
  873. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  874. if (SkipCast) return false;
  875. if (IntTy->isIntegerType()) {
  876. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  877. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  878. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  879. CK_FloatingRealToComplex);
  880. } else {
  881. assert(IntTy->isComplexIntegerType());
  882. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  883. CK_IntegralComplexToFloatingComplex);
  884. }
  885. return false;
  886. }
  887. /// \brief Handle arithmetic conversion with complex types. Helper function of
  888. /// UsualArithmeticConversions()
  889. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  890. ExprResult &RHS, QualType LHSType,
  891. QualType RHSType,
  892. bool IsCompAssign) {
  893. // if we have an integer operand, the result is the complex type.
  894. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  895. /*skipCast*/false))
  896. return LHSType;
  897. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  898. /*skipCast*/IsCompAssign))
  899. return RHSType;
  900. // This handles complex/complex, complex/float, or float/complex.
  901. // When both operands are complex, the shorter operand is converted to the
  902. // type of the longer, and that is the type of the result. This corresponds
  903. // to what is done when combining two real floating-point operands.
  904. // The fun begins when size promotion occur across type domains.
  905. // From H&S 6.3.4: When one operand is complex and the other is a real
  906. // floating-point type, the less precise type is converted, within it's
  907. // real or complex domain, to the precision of the other type. For example,
  908. // when combining a "long double" with a "double _Complex", the
  909. // "double _Complex" is promoted to "long double _Complex".
  910. // Compute the rank of the two types, regardless of whether they are complex.
  911. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  912. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  913. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  914. QualType LHSElementType =
  915. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  916. QualType RHSElementType =
  917. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  918. QualType ResultType = S.Context.getComplexType(LHSElementType);
  919. if (Order < 0) {
  920. // Promote the precision of the LHS if not an assignment.
  921. ResultType = S.Context.getComplexType(RHSElementType);
  922. if (!IsCompAssign) {
  923. if (LHSComplexType)
  924. LHS =
  925. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  926. else
  927. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  928. }
  929. } else if (Order > 0) {
  930. // Promote the precision of the RHS.
  931. if (RHSComplexType)
  932. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  933. else
  934. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  935. }
  936. return ResultType;
  937. }
  938. /// \brief Hande arithmetic conversion from integer to float. Helper function
  939. /// of UsualArithmeticConversions()
  940. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  941. ExprResult &IntExpr,
  942. QualType FloatTy, QualType IntTy,
  943. bool ConvertFloat, bool ConvertInt) {
  944. if (IntTy->isIntegerType()) {
  945. if (ConvertInt)
  946. // Convert intExpr to the lhs floating point type.
  947. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  948. CK_IntegralToFloating);
  949. return FloatTy;
  950. }
  951. // Convert both sides to the appropriate complex float.
  952. assert(IntTy->isComplexIntegerType());
  953. QualType result = S.Context.getComplexType(FloatTy);
  954. // _Complex int -> _Complex float
  955. if (ConvertInt)
  956. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  957. CK_IntegralComplexToFloatingComplex);
  958. // float -> _Complex float
  959. if (ConvertFloat)
  960. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  961. CK_FloatingRealToComplex);
  962. return result;
  963. }
  964. /// \brief Handle arithmethic conversion with floating point types. Helper
  965. /// function of UsualArithmeticConversions()
  966. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  967. ExprResult &RHS, QualType LHSType,
  968. QualType RHSType, bool IsCompAssign) {
  969. bool LHSFloat = LHSType->isRealFloatingType();
  970. bool RHSFloat = RHSType->isRealFloatingType();
  971. // If we have two real floating types, convert the smaller operand
  972. // to the bigger result.
  973. if (LHSFloat && RHSFloat) {
  974. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  975. if (order > 0) {
  976. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  977. return LHSType;
  978. }
  979. assert(order < 0 && "illegal float comparison");
  980. if (!IsCompAssign)
  981. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  982. return RHSType;
  983. }
  984. if (LHSFloat) {
  985. // Half FP has to be promoted to float unless it is natively supported
  986. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  987. LHSType = S.Context.FloatTy;
  988. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  989. /*convertFloat=*/!IsCompAssign,
  990. /*convertInt=*/ true);
  991. }
  992. assert(RHSFloat);
  993. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  994. /*convertInt=*/ true,
  995. /*convertFloat=*/!IsCompAssign);
  996. }
  997. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  998. namespace {
  999. /// These helper callbacks are placed in an anonymous namespace to
  1000. /// permit their use as function template parameters.
  1001. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1002. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1003. }
  1004. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1005. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1006. CK_IntegralComplexCast);
  1007. }
  1008. }
  1009. /// \brief Handle integer arithmetic conversions. Helper function of
  1010. /// UsualArithmeticConversions()
  1011. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1012. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1013. ExprResult &RHS, QualType LHSType,
  1014. QualType RHSType, bool IsCompAssign) {
  1015. // The rules for this case are in C99 6.3.1.8
  1016. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1017. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1018. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1019. if (LHSSigned == RHSSigned) {
  1020. // Same signedness; use the higher-ranked type
  1021. if (order >= 0) {
  1022. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1023. return LHSType;
  1024. } else if (!IsCompAssign)
  1025. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1026. return RHSType;
  1027. } else if (order != (LHSSigned ? 1 : -1)) {
  1028. // The unsigned type has greater than or equal rank to the
  1029. // signed type, so use the unsigned type
  1030. if (RHSSigned) {
  1031. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1032. return LHSType;
  1033. } else if (!IsCompAssign)
  1034. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1035. return RHSType;
  1036. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1037. // The two types are different widths; if we are here, that
  1038. // means the signed type is larger than the unsigned type, so
  1039. // use the signed type.
  1040. if (LHSSigned) {
  1041. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1042. return LHSType;
  1043. } else if (!IsCompAssign)
  1044. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1045. return RHSType;
  1046. } else {
  1047. // The signed type is higher-ranked than the unsigned type,
  1048. // but isn't actually any bigger (like unsigned int and long
  1049. // on most 32-bit systems). Use the unsigned type corresponding
  1050. // to the signed type.
  1051. QualType result =
  1052. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1053. RHS = (*doRHSCast)(S, RHS.get(), result);
  1054. if (!IsCompAssign)
  1055. LHS = (*doLHSCast)(S, LHS.get(), result);
  1056. return result;
  1057. }
  1058. }
  1059. /// \brief Handle conversions with GCC complex int extension. Helper function
  1060. /// of UsualArithmeticConversions()
  1061. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1062. ExprResult &RHS, QualType LHSType,
  1063. QualType RHSType,
  1064. bool IsCompAssign) {
  1065. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1066. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1067. if (LHSComplexInt && RHSComplexInt) {
  1068. QualType LHSEltType = LHSComplexInt->getElementType();
  1069. QualType RHSEltType = RHSComplexInt->getElementType();
  1070. QualType ScalarType =
  1071. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1072. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1073. return S.Context.getComplexType(ScalarType);
  1074. }
  1075. if (LHSComplexInt) {
  1076. QualType LHSEltType = LHSComplexInt->getElementType();
  1077. QualType ScalarType =
  1078. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1079. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1080. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1081. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1082. CK_IntegralRealToComplex);
  1083. return ComplexType;
  1084. }
  1085. assert(RHSComplexInt);
  1086. QualType RHSEltType = RHSComplexInt->getElementType();
  1087. QualType ScalarType =
  1088. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1089. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1090. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1091. if (!IsCompAssign)
  1092. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1093. CK_IntegralRealToComplex);
  1094. return ComplexType;
  1095. }
  1096. /// UsualArithmeticConversions - Performs various conversions that are common to
  1097. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1098. /// routine returns the first non-arithmetic type found. The client is
  1099. /// responsible for emitting appropriate error diagnostics.
  1100. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1101. bool IsCompAssign) {
  1102. if (!IsCompAssign) {
  1103. LHS = UsualUnaryConversions(LHS.get());
  1104. if (LHS.isInvalid())
  1105. return QualType();
  1106. }
  1107. RHS = UsualUnaryConversions(RHS.get());
  1108. if (RHS.isInvalid())
  1109. return QualType();
  1110. // For conversion purposes, we ignore any qualifiers.
  1111. // For example, "const float" and "float" are equivalent.
  1112. QualType LHSType =
  1113. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1114. QualType RHSType =
  1115. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1116. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1117. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1118. LHSType = AtomicLHS->getValueType();
  1119. // If both types are identical, no conversion is needed.
  1120. if (LHSType == RHSType)
  1121. return LHSType;
  1122. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1123. // The caller can deal with this (e.g. pointer + int).
  1124. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1125. return QualType();
  1126. // Apply unary and bitfield promotions to the LHS's type.
  1127. QualType LHSUnpromotedType = LHSType;
  1128. if (LHSType->isPromotableIntegerType())
  1129. LHSType = Context.getPromotedIntegerType(LHSType);
  1130. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1131. if (!LHSBitfieldPromoteTy.isNull())
  1132. LHSType = LHSBitfieldPromoteTy;
  1133. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1134. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1135. // If both types are identical, no conversion is needed.
  1136. if (LHSType == RHSType)
  1137. return LHSType;
  1138. // At this point, we have two different arithmetic types.
  1139. // Handle complex types first (C99 6.3.1.8p1).
  1140. if (LHSType->isComplexType() || RHSType->isComplexType())
  1141. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1142. IsCompAssign);
  1143. // Now handle "real" floating types (i.e. float, double, long double).
  1144. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1145. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1146. IsCompAssign);
  1147. // Handle GCC complex int extension.
  1148. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1149. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1150. IsCompAssign);
  1151. // Finally, we have two differing integer types.
  1152. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1153. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1154. }
  1155. //===----------------------------------------------------------------------===//
  1156. // Semantic Analysis for various Expression Types
  1157. //===----------------------------------------------------------------------===//
  1158. ExprResult
  1159. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1160. SourceLocation DefaultLoc,
  1161. SourceLocation RParenLoc,
  1162. Expr *ControllingExpr,
  1163. ArrayRef<ParsedType> ArgTypes,
  1164. ArrayRef<Expr *> ArgExprs) {
  1165. unsigned NumAssocs = ArgTypes.size();
  1166. assert(NumAssocs == ArgExprs.size());
  1167. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1168. for (unsigned i = 0; i < NumAssocs; ++i) {
  1169. if (ArgTypes[i])
  1170. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1171. else
  1172. Types[i] = nullptr;
  1173. }
  1174. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1175. ControllingExpr,
  1176. llvm::makeArrayRef(Types, NumAssocs),
  1177. ArgExprs);
  1178. delete [] Types;
  1179. return ER;
  1180. }
  1181. ExprResult
  1182. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1183. SourceLocation DefaultLoc,
  1184. SourceLocation RParenLoc,
  1185. Expr *ControllingExpr,
  1186. ArrayRef<TypeSourceInfo *> Types,
  1187. ArrayRef<Expr *> Exprs) {
  1188. unsigned NumAssocs = Types.size();
  1189. assert(NumAssocs == Exprs.size());
  1190. if (ControllingExpr->getType()->isPlaceholderType()) {
  1191. ExprResult result = CheckPlaceholderExpr(ControllingExpr);
  1192. if (result.isInvalid()) return ExprError();
  1193. ControllingExpr = result.get();
  1194. }
  1195. // The controlling expression is an unevaluated operand, so side effects are
  1196. // likely unintended.
  1197. if (ActiveTemplateInstantiations.empty() &&
  1198. ControllingExpr->HasSideEffects(Context, false))
  1199. Diag(ControllingExpr->getExprLoc(),
  1200. diag::warn_side_effects_unevaluated_context);
  1201. bool TypeErrorFound = false,
  1202. IsResultDependent = ControllingExpr->isTypeDependent(),
  1203. ContainsUnexpandedParameterPack
  1204. = ControllingExpr->containsUnexpandedParameterPack();
  1205. for (unsigned i = 0; i < NumAssocs; ++i) {
  1206. if (Exprs[i]->containsUnexpandedParameterPack())
  1207. ContainsUnexpandedParameterPack = true;
  1208. if (Types[i]) {
  1209. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1210. ContainsUnexpandedParameterPack = true;
  1211. if (Types[i]->getType()->isDependentType()) {
  1212. IsResultDependent = true;
  1213. } else {
  1214. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1215. // complete object type other than a variably modified type."
  1216. unsigned D = 0;
  1217. if (Types[i]->getType()->isIncompleteType())
  1218. D = diag::err_assoc_type_incomplete;
  1219. else if (!Types[i]->getType()->isObjectType())
  1220. D = diag::err_assoc_type_nonobject;
  1221. else if (Types[i]->getType()->isVariablyModifiedType())
  1222. D = diag::err_assoc_type_variably_modified;
  1223. if (D != 0) {
  1224. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1225. << Types[i]->getTypeLoc().getSourceRange()
  1226. << Types[i]->getType();
  1227. TypeErrorFound = true;
  1228. }
  1229. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1230. // selection shall specify compatible types."
  1231. for (unsigned j = i+1; j < NumAssocs; ++j)
  1232. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1233. Context.typesAreCompatible(Types[i]->getType(),
  1234. Types[j]->getType())) {
  1235. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1236. diag::err_assoc_compatible_types)
  1237. << Types[j]->getTypeLoc().getSourceRange()
  1238. << Types[j]->getType()
  1239. << Types[i]->getType();
  1240. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1241. diag::note_compat_assoc)
  1242. << Types[i]->getTypeLoc().getSourceRange()
  1243. << Types[i]->getType();
  1244. TypeErrorFound = true;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. if (TypeErrorFound)
  1250. return ExprError();
  1251. // If we determined that the generic selection is result-dependent, don't
  1252. // try to compute the result expression.
  1253. if (IsResultDependent)
  1254. return new (Context) GenericSelectionExpr(
  1255. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1256. ContainsUnexpandedParameterPack);
  1257. SmallVector<unsigned, 1> CompatIndices;
  1258. unsigned DefaultIndex = -1U;
  1259. for (unsigned i = 0; i < NumAssocs; ++i) {
  1260. if (!Types[i])
  1261. DefaultIndex = i;
  1262. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1263. Types[i]->getType()))
  1264. CompatIndices.push_back(i);
  1265. }
  1266. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1267. // type compatible with at most one of the types named in its generic
  1268. // association list."
  1269. if (CompatIndices.size() > 1) {
  1270. // We strip parens here because the controlling expression is typically
  1271. // parenthesized in macro definitions.
  1272. ControllingExpr = ControllingExpr->IgnoreParens();
  1273. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1274. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1275. << (unsigned) CompatIndices.size();
  1276. for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
  1277. E = CompatIndices.end(); I != E; ++I) {
  1278. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1279. diag::note_compat_assoc)
  1280. << Types[*I]->getTypeLoc().getSourceRange()
  1281. << Types[*I]->getType();
  1282. }
  1283. return ExprError();
  1284. }
  1285. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1286. // its controlling expression shall have type compatible with exactly one of
  1287. // the types named in its generic association list."
  1288. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1289. // We strip parens here because the controlling expression is typically
  1290. // parenthesized in macro definitions.
  1291. ControllingExpr = ControllingExpr->IgnoreParens();
  1292. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1293. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1294. return ExprError();
  1295. }
  1296. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1297. // type name that is compatible with the type of the controlling expression,
  1298. // then the result expression of the generic selection is the expression
  1299. // in that generic association. Otherwise, the result expression of the
  1300. // generic selection is the expression in the default generic association."
  1301. unsigned ResultIndex =
  1302. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1303. return new (Context) GenericSelectionExpr(
  1304. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1305. ContainsUnexpandedParameterPack, ResultIndex);
  1306. }
  1307. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1308. /// location of the token and the offset of the ud-suffix within it.
  1309. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1310. unsigned Offset) {
  1311. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1312. S.getLangOpts());
  1313. }
  1314. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1315. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1316. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1317. IdentifierInfo *UDSuffix,
  1318. SourceLocation UDSuffixLoc,
  1319. ArrayRef<Expr*> Args,
  1320. SourceLocation LitEndLoc) {
  1321. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1322. QualType ArgTy[2];
  1323. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1324. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1325. if (ArgTy[ArgIdx]->isArrayType())
  1326. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1327. }
  1328. DeclarationName OpName =
  1329. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1330. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1331. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1332. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1333. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1334. /*AllowRaw*/false, /*AllowTemplate*/false,
  1335. /*AllowStringTemplate*/false) == Sema::LOLR_Error)
  1336. return ExprError();
  1337. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1338. }
  1339. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1340. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1341. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1342. /// multiple tokens. However, the common case is that StringToks points to one
  1343. /// string.
  1344. ///
  1345. ExprResult
  1346. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1347. assert(!StringToks.empty() && "Must have at least one string!");
  1348. StringLiteralParser Literal(StringToks, PP);
  1349. if (Literal.hadError)
  1350. return ExprError();
  1351. SmallVector<SourceLocation, 4> StringTokLocs;
  1352. for (unsigned i = 0; i != StringToks.size(); ++i)
  1353. StringTokLocs.push_back(StringToks[i].getLocation());
  1354. QualType CharTy = Context.CharTy;
  1355. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1356. if (Literal.isWide()) {
  1357. CharTy = Context.getWideCharType();
  1358. Kind = StringLiteral::Wide;
  1359. } else if (Literal.isUTF8()) {
  1360. Kind = StringLiteral::UTF8;
  1361. } else if (Literal.isUTF16()) {
  1362. CharTy = Context.Char16Ty;
  1363. Kind = StringLiteral::UTF16;
  1364. } else if (Literal.isUTF32()) {
  1365. CharTy = Context.Char32Ty;
  1366. Kind = StringLiteral::UTF32;
  1367. } else if (Literal.isPascal()) {
  1368. CharTy = Context.UnsignedCharTy;
  1369. }
  1370. QualType CharTyConst = CharTy;
  1371. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1372. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1373. CharTyConst.addConst();
  1374. // Get an array type for the string, according to C99 6.4.5. This includes
  1375. // the nul terminator character as well as the string length for pascal
  1376. // strings.
  1377. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1378. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1379. ArrayType::Normal, 0);
  1380. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1381. if (getLangOpts().OpenCL) {
  1382. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1383. }
  1384. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1385. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1386. Kind, Literal.Pascal, StrTy,
  1387. &StringTokLocs[0],
  1388. StringTokLocs.size());
  1389. if (Literal.getUDSuffix().empty())
  1390. return Lit;
  1391. // We're building a user-defined literal.
  1392. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1393. SourceLocation UDSuffixLoc =
  1394. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1395. Literal.getUDSuffixOffset());
  1396. // Make sure we're allowed user-defined literals here.
  1397. if (!UDLScope)
  1398. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1399. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1400. // operator "" X (str, len)
  1401. QualType SizeType = Context.getSizeType();
  1402. DeclarationName OpName =
  1403. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1404. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1405. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1406. QualType ArgTy[] = {
  1407. Context.getArrayDecayedType(StrTy), SizeType
  1408. };
  1409. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1410. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1411. /*AllowRaw*/false, /*AllowTemplate*/false,
  1412. /*AllowStringTemplate*/true)) {
  1413. case LOLR_Cooked: {
  1414. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1415. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1416. StringTokLocs[0]);
  1417. Expr *Args[] = { Lit, LenArg };
  1418. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1419. }
  1420. case LOLR_StringTemplate: {
  1421. TemplateArgumentListInfo ExplicitArgs;
  1422. unsigned CharBits = Context.getIntWidth(CharTy);
  1423. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1424. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1425. TemplateArgument TypeArg(CharTy);
  1426. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1427. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1428. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1429. Value = Lit->getCodeUnit(I);
  1430. TemplateArgument Arg(Context, Value, CharTy);
  1431. TemplateArgumentLocInfo ArgInfo;
  1432. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1433. }
  1434. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1435. &ExplicitArgs);
  1436. }
  1437. case LOLR_Raw:
  1438. case LOLR_Template:
  1439. llvm_unreachable("unexpected literal operator lookup result");
  1440. case LOLR_Error:
  1441. return ExprError();
  1442. }
  1443. llvm_unreachable("unexpected literal operator lookup result");
  1444. }
  1445. ExprResult
  1446. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1447. SourceLocation Loc,
  1448. const CXXScopeSpec *SS) {
  1449. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1450. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1451. }
  1452. /// BuildDeclRefExpr - Build an expression that references a
  1453. /// declaration that does not require a closure capture.
  1454. ExprResult
  1455. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1456. const DeclarationNameInfo &NameInfo,
  1457. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1458. const TemplateArgumentListInfo *TemplateArgs) {
  1459. if (getLangOpts().CUDA)
  1460. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1461. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1462. if (CheckCUDATarget(Caller, Callee)) {
  1463. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1464. << IdentifyCUDATarget(Callee) << D->getIdentifier()
  1465. << IdentifyCUDATarget(Caller);
  1466. Diag(D->getLocation(), diag::note_previous_decl)
  1467. << D->getIdentifier();
  1468. return ExprError();
  1469. }
  1470. }
  1471. bool RefersToCapturedVariable =
  1472. isa<VarDecl>(D) &&
  1473. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1474. DeclRefExpr *E;
  1475. if (isa<VarTemplateSpecializationDecl>(D)) {
  1476. VarTemplateSpecializationDecl *VarSpec =
  1477. cast<VarTemplateSpecializationDecl>(D);
  1478. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1479. : NestedNameSpecifierLoc(),
  1480. VarSpec->getTemplateKeywordLoc(), D,
  1481. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1482. FoundD, TemplateArgs);
  1483. } else {
  1484. assert(!TemplateArgs && "No template arguments for non-variable"
  1485. " template specialization references");
  1486. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1487. : NestedNameSpecifierLoc(),
  1488. SourceLocation(), D, RefersToCapturedVariable,
  1489. NameInfo, Ty, VK, FoundD);
  1490. }
  1491. MarkDeclRefReferenced(E);
  1492. if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
  1493. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1494. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1495. recordUseOfEvaluatedWeak(E);
  1496. // Just in case we're building an illegal pointer-to-member.
  1497. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1498. if (FD && FD->isBitField())
  1499. E->setObjectKind(OK_BitField);
  1500. return E;
  1501. }
  1502. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1503. /// possibly a list of template arguments.
  1504. ///
  1505. /// If this produces template arguments, it is permitted to call
  1506. /// DecomposeTemplateName.
  1507. ///
  1508. /// This actually loses a lot of source location information for
  1509. /// non-standard name kinds; we should consider preserving that in
  1510. /// some way.
  1511. void
  1512. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1513. TemplateArgumentListInfo &Buffer,
  1514. DeclarationNameInfo &NameInfo,
  1515. const TemplateArgumentListInfo *&TemplateArgs) {
  1516. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1517. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1518. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1519. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1520. Id.TemplateId->NumArgs);
  1521. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1522. TemplateName TName = Id.TemplateId->Template.get();
  1523. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1524. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1525. TemplateArgs = &Buffer;
  1526. } else {
  1527. NameInfo = GetNameFromUnqualifiedId(Id);
  1528. TemplateArgs = nullptr;
  1529. }
  1530. }
  1531. static void emitEmptyLookupTypoDiagnostic(
  1532. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1533. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1534. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1535. DeclContext *Ctx =
  1536. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1537. if (!TC) {
  1538. // Emit a special diagnostic for failed member lookups.
  1539. // FIXME: computing the declaration context might fail here (?)
  1540. if (Ctx)
  1541. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1542. << SS.getRange();
  1543. else
  1544. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1545. return;
  1546. }
  1547. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1548. bool DroppedSpecifier =
  1549. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1550. unsigned NoteID =
  1551. (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
  1552. ? diag::note_implicit_param_decl
  1553. : diag::note_previous_decl;
  1554. if (!Ctx)
  1555. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1556. SemaRef.PDiag(NoteID));
  1557. else
  1558. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1559. << Typo << Ctx << DroppedSpecifier
  1560. << SS.getRange(),
  1561. SemaRef.PDiag(NoteID));
  1562. }
  1563. /// Diagnose an empty lookup.
  1564. ///
  1565. /// \return false if new lookup candidates were found
  1566. bool
  1567. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1568. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1569. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1570. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1571. DeclarationName Name = R.getLookupName();
  1572. unsigned diagnostic = diag::err_undeclared_var_use;
  1573. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1574. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1575. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1576. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1577. diagnostic = diag::err_undeclared_use;
  1578. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1579. }
  1580. // If the original lookup was an unqualified lookup, fake an
  1581. // unqualified lookup. This is useful when (for example) the
  1582. // original lookup would not have found something because it was a
  1583. // dependent name.
  1584. DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
  1585. ? CurContext : nullptr;
  1586. while (DC) {
  1587. if (isa<CXXRecordDecl>(DC)) {
  1588. LookupQualifiedName(R, DC);
  1589. if (!R.empty()) {
  1590. // Don't give errors about ambiguities in this lookup.
  1591. R.suppressDiagnostics();
  1592. // During a default argument instantiation the CurContext points
  1593. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1594. // function parameter list, hence add an explicit check.
  1595. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1596. ActiveTemplateInstantiations.back().Kind ==
  1597. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1598. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1599. bool isInstance = CurMethod &&
  1600. CurMethod->isInstance() &&
  1601. DC == CurMethod->getParent() && !isDefaultArgument;
  1602. // Give a code modification hint to insert 'this->'.
  1603. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1604. // Actually quite difficult!
  1605. if (getLangOpts().MSVCCompat)
  1606. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1607. if (isInstance) {
  1608. Diag(R.getNameLoc(), diagnostic) << Name
  1609. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1610. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
  1611. CallsUndergoingInstantiation.back()->getCallee());
  1612. CXXMethodDecl *DepMethod;
  1613. if (CurMethod->isDependentContext())
  1614. DepMethod = CurMethod;
  1615. else if (CurMethod->getTemplatedKind() ==
  1616. FunctionDecl::TK_FunctionTemplateSpecialization)
  1617. DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
  1618. getInstantiatedFromMemberTemplate()->getTemplatedDecl());
  1619. else
  1620. DepMethod = cast<CXXMethodDecl>(
  1621. CurMethod->getInstantiatedFromMemberFunction());
  1622. assert(DepMethod && "No template pattern found");
  1623. QualType DepThisType = DepMethod->getThisType(Context);
  1624. CheckCXXThisCapture(R.getNameLoc());
  1625. CXXThisExpr *DepThis = new (Context) CXXThisExpr(
  1626. R.getNameLoc(), DepThisType, false);
  1627. TemplateArgumentListInfo TList;
  1628. if (ULE->hasExplicitTemplateArgs())
  1629. ULE->copyTemplateArgumentsInto(TList);
  1630. CXXScopeSpec SS;
  1631. SS.Adopt(ULE->getQualifierLoc());
  1632. CXXDependentScopeMemberExpr *DepExpr =
  1633. CXXDependentScopeMemberExpr::Create(
  1634. Context, DepThis, DepThisType, true, SourceLocation(),
  1635. SS.getWithLocInContext(Context),
  1636. ULE->getTemplateKeywordLoc(), nullptr,
  1637. R.getLookupNameInfo(),
  1638. ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
  1639. CallsUndergoingInstantiation.back()->setCallee(DepExpr);
  1640. } else {
  1641. Diag(R.getNameLoc(), diagnostic) << Name;
  1642. }
  1643. // Do we really want to note all of these?
  1644. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1645. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1646. // Return true if we are inside a default argument instantiation
  1647. // and the found name refers to an instance member function, otherwise
  1648. // the function calling DiagnoseEmptyLookup will try to create an
  1649. // implicit member call and this is wrong for default argument.
  1650. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1651. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1652. return true;
  1653. }
  1654. // Tell the callee to try to recover.
  1655. return false;
  1656. }
  1657. R.clear();
  1658. }
  1659. // In Microsoft mode, if we are performing lookup from within a friend
  1660. // function definition declared at class scope then we must set
  1661. // DC to the lexical parent to be able to search into the parent
  1662. // class.
  1663. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1664. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1665. DC->getLexicalParent()->isRecord())
  1666. DC = DC->getLexicalParent();
  1667. else
  1668. DC = DC->getParent();
  1669. }
  1670. // We didn't find anything, so try to correct for a typo.
  1671. TypoCorrection Corrected;
  1672. if (S && Out) {
  1673. SourceLocation TypoLoc = R.getNameLoc();
  1674. assert(!ExplicitTemplateArgs &&
  1675. "Diagnosing an empty lookup with explicit template args!");
  1676. *Out = CorrectTypoDelayed(
  1677. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1678. [=](const TypoCorrection &TC) {
  1679. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1680. diagnostic, diagnostic_suggest);
  1681. },
  1682. nullptr, CTK_ErrorRecovery);
  1683. if (*Out)
  1684. return true;
  1685. } else if (S && (Corrected =
  1686. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1687. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1688. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1689. bool DroppedSpecifier =
  1690. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1691. R.setLookupName(Corrected.getCorrection());
  1692. bool AcceptableWithRecovery = false;
  1693. bool AcceptableWithoutRecovery = false;
  1694. NamedDecl *ND = Corrected.getCorrectionDecl();
  1695. if (ND) {
  1696. if (Corrected.isOverloaded()) {
  1697. OverloadCandidateSet OCS(R.getNameLoc(),
  1698. OverloadCandidateSet::CSK_Normal);
  1699. OverloadCandidateSet::iterator Best;
  1700. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1701. CDEnd = Corrected.end();
  1702. CD != CDEnd; ++CD) {
  1703. if (FunctionTemplateDecl *FTD =
  1704. dyn_cast<FunctionTemplateDecl>(*CD))
  1705. AddTemplateOverloadCandidate(
  1706. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1707. Args, OCS);
  1708. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1709. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1710. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1711. Args, OCS);
  1712. }
  1713. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1714. case OR_Success:
  1715. ND = Best->Function;
  1716. Corrected.setCorrectionDecl(ND);
  1717. break;
  1718. default:
  1719. // FIXME: Arbitrarily pick the first declaration for the note.
  1720. Corrected.setCorrectionDecl(ND);
  1721. break;
  1722. }
  1723. }
  1724. R.addDecl(ND);
  1725. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1726. CXXRecordDecl *Record = nullptr;
  1727. if (Corrected.getCorrectionSpecifier()) {
  1728. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1729. Record = Ty->getAsCXXRecordDecl();
  1730. }
  1731. if (!Record)
  1732. Record = cast<CXXRecordDecl>(
  1733. ND->getDeclContext()->getRedeclContext());
  1734. R.setNamingClass(Record);
  1735. }
  1736. AcceptableWithRecovery =
  1737. isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
  1738. // FIXME: If we ended up with a typo for a type name or
  1739. // Objective-C class name, we're in trouble because the parser
  1740. // is in the wrong place to recover. Suggest the typo
  1741. // correction, but don't make it a fix-it since we're not going
  1742. // to recover well anyway.
  1743. AcceptableWithoutRecovery =
  1744. isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1745. } else {
  1746. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1747. // because we aren't able to recover.
  1748. AcceptableWithoutRecovery = true;
  1749. }
  1750. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1751. unsigned NoteID = (Corrected.getCorrectionDecl() &&
  1752. isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
  1753. ? diag::note_implicit_param_decl
  1754. : diag::note_previous_decl;
  1755. if (SS.isEmpty())
  1756. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1757. PDiag(NoteID), AcceptableWithRecovery);
  1758. else
  1759. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1760. << Name << computeDeclContext(SS, false)
  1761. << DroppedSpecifier << SS.getRange(),
  1762. PDiag(NoteID), AcceptableWithRecovery);
  1763. // Tell the callee whether to try to recover.
  1764. return !AcceptableWithRecovery;
  1765. }
  1766. }
  1767. R.clear();
  1768. // Emit a special diagnostic for failed member lookups.
  1769. // FIXME: computing the declaration context might fail here (?)
  1770. if (!SS.isEmpty()) {
  1771. Diag(R.getNameLoc(), diag::err_no_member)
  1772. << Name << computeDeclContext(SS, false)
  1773. << SS.getRange();
  1774. return true;
  1775. }
  1776. // Give up, we can't recover.
  1777. Diag(R.getNameLoc(), diagnostic) << Name;
  1778. return true;
  1779. }
  1780. /// In Microsoft mode, if we are inside a template class whose parent class has
  1781. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1782. /// assume the identifier is a member of a dependent base class. We can only
  1783. /// recover successfully in static methods, instance methods, and other contexts
  1784. /// where 'this' is available. This doesn't precisely match MSVC's
  1785. /// instantiation model, but it's close enough.
  1786. static Expr *
  1787. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1788. DeclarationNameInfo &NameInfo,
  1789. SourceLocation TemplateKWLoc,
  1790. const TemplateArgumentListInfo *TemplateArgs) {
  1791. // Only try to recover from lookup into dependent bases in static methods or
  1792. // contexts where 'this' is available.
  1793. QualType ThisType = S.getCurrentThisType();
  1794. const CXXRecordDecl *RD = nullptr;
  1795. if (!ThisType.isNull())
  1796. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1797. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1798. RD = MD->getParent();
  1799. if (!RD || !RD->hasAnyDependentBases())
  1800. return nullptr;
  1801. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1802. // is available, suggest inserting 'this->' as a fixit.
  1803. SourceLocation Loc = NameInfo.getLoc();
  1804. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1805. DB << NameInfo.getName() << RD;
  1806. if (!ThisType.isNull()) {
  1807. DB << FixItHint::CreateInsertion(Loc, "this->");
  1808. return CXXDependentScopeMemberExpr::Create(
  1809. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1810. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1811. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1812. }
  1813. // Synthesize a fake NNS that points to the derived class. This will
  1814. // perform name lookup during template instantiation.
  1815. CXXScopeSpec SS;
  1816. auto *NNS =
  1817. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1818. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1819. return DependentScopeDeclRefExpr::Create(
  1820. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1821. TemplateArgs);
  1822. }
  1823. ExprResult
  1824. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1825. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1826. bool HasTrailingLParen, bool IsAddressOfOperand,
  1827. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1828. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1829. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1830. "cannot be direct & operand and have a trailing lparen");
  1831. if (SS.isInvalid())
  1832. return ExprError();
  1833. TemplateArgumentListInfo TemplateArgsBuffer;
  1834. // Decompose the UnqualifiedId into the following data.
  1835. DeclarationNameInfo NameInfo;
  1836. const TemplateArgumentListInfo *TemplateArgs;
  1837. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1838. DeclarationName Name = NameInfo.getName();
  1839. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1840. SourceLocation NameLoc = NameInfo.getLoc();
  1841. // C++ [temp.dep.expr]p3:
  1842. // An id-expression is type-dependent if it contains:
  1843. // -- an identifier that was declared with a dependent type,
  1844. // (note: handled after lookup)
  1845. // -- a template-id that is dependent,
  1846. // (note: handled in BuildTemplateIdExpr)
  1847. // -- a conversion-function-id that specifies a dependent type,
  1848. // -- a nested-name-specifier that contains a class-name that
  1849. // names a dependent type.
  1850. // Determine whether this is a member of an unknown specialization;
  1851. // we need to handle these differently.
  1852. bool DependentID = false;
  1853. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1854. Name.getCXXNameType()->isDependentType()) {
  1855. DependentID = true;
  1856. } else if (SS.isSet()) {
  1857. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1858. if (RequireCompleteDeclContext(SS, DC))
  1859. return ExprError();
  1860. } else {
  1861. DependentID = true;
  1862. }
  1863. }
  1864. if (DependentID)
  1865. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1866. IsAddressOfOperand, TemplateArgs);
  1867. // Perform the required lookup.
  1868. LookupResult R(*this, NameInfo,
  1869. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1870. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1871. if (TemplateArgs) {
  1872. // Lookup the template name again to correctly establish the context in
  1873. // which it was found. This is really unfortunate as we already did the
  1874. // lookup to determine that it was a template name in the first place. If
  1875. // this becomes a performance hit, we can work harder to preserve those
  1876. // results until we get here but it's likely not worth it.
  1877. bool MemberOfUnknownSpecialization;
  1878. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1879. MemberOfUnknownSpecialization);
  1880. if (MemberOfUnknownSpecialization ||
  1881. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1882. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1883. IsAddressOfOperand, TemplateArgs);
  1884. } else {
  1885. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1886. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1887. // If the result might be in a dependent base class, this is a dependent
  1888. // id-expression.
  1889. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1890. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1891. IsAddressOfOperand, TemplateArgs);
  1892. // If this reference is in an Objective-C method, then we need to do
  1893. // some special Objective-C lookup, too.
  1894. if (IvarLookupFollowUp) {
  1895. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1896. if (E.isInvalid())
  1897. return ExprError();
  1898. if (Expr *Ex = E.getAs<Expr>())
  1899. return Ex;
  1900. }
  1901. }
  1902. if (R.isAmbiguous())
  1903. return ExprError();
  1904. // This could be an implicitly declared function reference (legal in C90,
  1905. // extension in C99, forbidden in C++).
  1906. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1907. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1908. if (D) R.addDecl(D);
  1909. }
  1910. // Determine whether this name might be a candidate for
  1911. // argument-dependent lookup.
  1912. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1913. if (R.empty() && !ADL) {
  1914. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1915. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1916. TemplateKWLoc, TemplateArgs))
  1917. return E;
  1918. }
  1919. // Don't diagnose an empty lookup for inline assembly.
  1920. if (IsInlineAsmIdentifier)
  1921. return ExprError();
  1922. // If this name wasn't predeclared and if this is not a function
  1923. // call, diagnose the problem.
  1924. TypoExpr *TE = nullptr;
  1925. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1926. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1927. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1928. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1929. "Typo correction callback misconfigured");
  1930. if (CCC) {
  1931. // Make sure the callback knows what the typo being diagnosed is.
  1932. CCC->setTypoName(II);
  1933. if (SS.isValid())
  1934. CCC->setTypoNNS(SS.getScopeRep());
  1935. }
  1936. if (DiagnoseEmptyLookup(S, SS, R,
  1937. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1938. nullptr, None, &TE)) {
  1939. if (TE && KeywordReplacement) {
  1940. auto &State = getTypoExprState(TE);
  1941. auto BestTC = State.Consumer->getNextCorrection();
  1942. if (BestTC.isKeyword()) {
  1943. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1944. if (State.DiagHandler)
  1945. State.DiagHandler(BestTC);
  1946. KeywordReplacement->startToken();
  1947. KeywordReplacement->setKind(II->getTokenID());
  1948. KeywordReplacement->setIdentifierInfo(II);
  1949. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1950. // Clean up the state associated with the TypoExpr, since it has
  1951. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1952. clearDelayedTypo(TE);
  1953. // Signal that a correction to a keyword was performed by returning a
  1954. // valid-but-null ExprResult.
  1955. return (Expr*)nullptr;
  1956. }
  1957. State.Consumer->resetCorrectionStream();
  1958. }
  1959. return TE ? TE : ExprError();
  1960. }
  1961. assert(!R.empty() &&
  1962. "DiagnoseEmptyLookup returned false but added no results");
  1963. // If we found an Objective-C instance variable, let
  1964. // LookupInObjCMethod build the appropriate expression to
  1965. // reference the ivar.
  1966. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1967. R.clear();
  1968. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1969. // In a hopelessly buggy code, Objective-C instance variable
  1970. // lookup fails and no expression will be built to reference it.
  1971. if (!E.isInvalid() && !E.get())
  1972. return ExprError();
  1973. return E;
  1974. }
  1975. }
  1976. // This is guaranteed from this point on.
  1977. assert(!R.empty() || ADL);
  1978. // Check whether this might be a C++ implicit instance member access.
  1979. // C++ [class.mfct.non-static]p3:
  1980. // When an id-expression that is not part of a class member access
  1981. // syntax and not used to form a pointer to member is used in the
  1982. // body of a non-static member function of class X, if name lookup
  1983. // resolves the name in the id-expression to a non-static non-type
  1984. // member of some class C, the id-expression is transformed into a
  1985. // class member access expression using (*this) as the
  1986. // postfix-expression to the left of the . operator.
  1987. //
  1988. // But we don't actually need to do this for '&' operands if R
  1989. // resolved to a function or overloaded function set, because the
  1990. // expression is ill-formed if it actually works out to be a
  1991. // non-static member function:
  1992. //
  1993. // C++ [expr.ref]p4:
  1994. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1995. // [t]he expression can be used only as the left-hand operand of a
  1996. // member function call.
  1997. //
  1998. // There are other safeguards against such uses, but it's important
  1999. // to get this right here so that we don't end up making a
  2000. // spuriously dependent expression if we're inside a dependent
  2001. // instance method.
  2002. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2003. bool MightBeImplicitMember;
  2004. if (!IsAddressOfOperand)
  2005. MightBeImplicitMember = true;
  2006. else if (!SS.isEmpty())
  2007. MightBeImplicitMember = false;
  2008. else if (R.isOverloadedResult())
  2009. MightBeImplicitMember = false;
  2010. else if (R.isUnresolvableResult())
  2011. MightBeImplicitMember = true;
  2012. else
  2013. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2014. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2015. isa<MSPropertyDecl>(R.getFoundDecl());
  2016. if (MightBeImplicitMember)
  2017. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2018. R, TemplateArgs);
  2019. }
  2020. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2021. // In C++1y, if this is a variable template id, then check it
  2022. // in BuildTemplateIdExpr().
  2023. // The single lookup result must be a variable template declaration.
  2024. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  2025. Id.TemplateId->Kind == TNK_Var_template) {
  2026. assert(R.getAsSingle<VarTemplateDecl>() &&
  2027. "There should only be one declaration found.");
  2028. }
  2029. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2030. }
  2031. return BuildDeclarationNameExpr(SS, R, ADL);
  2032. }
  2033. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2034. /// declaration name, generally during template instantiation.
  2035. /// There's a large number of things which don't need to be done along
  2036. /// this path.
  2037. ExprResult
  2038. Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
  2039. const DeclarationNameInfo &NameInfo,
  2040. bool IsAddressOfOperand,
  2041. TypeSourceInfo **RecoveryTSI) {
  2042. DeclContext *DC = computeDeclContext(SS, false);
  2043. if (!DC)
  2044. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2045. NameInfo, /*TemplateArgs=*/nullptr);
  2046. if (RequireCompleteDeclContext(SS, DC))
  2047. return ExprError();
  2048. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2049. LookupQualifiedName(R, DC);
  2050. if (R.isAmbiguous())
  2051. return ExprError();
  2052. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2053. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2054. NameInfo, /*TemplateArgs=*/nullptr);
  2055. if (R.empty()) {
  2056. Diag(NameInfo.getLoc(), diag::err_no_member)
  2057. << NameInfo.getName() << DC << SS.getRange();
  2058. return ExprError();
  2059. }
  2060. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2061. // Diagnose a missing typename if this resolved unambiguously to a type in
  2062. // a dependent context. If we can recover with a type, downgrade this to
  2063. // a warning in Microsoft compatibility mode.
  2064. unsigned DiagID = diag::err_typename_missing;
  2065. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2066. DiagID = diag::ext_typename_missing;
  2067. SourceLocation Loc = SS.getBeginLoc();
  2068. auto D = Diag(Loc, DiagID);
  2069. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2070. << SourceRange(Loc, NameInfo.getEndLoc());
  2071. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2072. // context.
  2073. if (!RecoveryTSI)
  2074. return ExprError();
  2075. // Only issue the fixit if we're prepared to recover.
  2076. D << FixItHint::CreateInsertion(Loc, "typename ");
  2077. // Recover by pretending this was an elaborated type.
  2078. QualType Ty = Context.getTypeDeclType(TD);
  2079. TypeLocBuilder TLB;
  2080. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2081. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2082. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2083. QTL.setElaboratedKeywordLoc(SourceLocation());
  2084. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2085. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2086. return ExprEmpty();
  2087. }
  2088. // Defend against this resolving to an implicit member access. We usually
  2089. // won't get here if this might be a legitimate a class member (we end up in
  2090. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2091. // a pointer-to-member or in an unevaluated context in C++11.
  2092. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2093. return BuildPossibleImplicitMemberExpr(SS,
  2094. /*TemplateKWLoc=*/SourceLocation(),
  2095. R, /*TemplateArgs=*/nullptr);
  2096. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2097. }
  2098. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2099. /// detected that we're currently inside an ObjC method. Perform some
  2100. /// additional lookup.
  2101. ///
  2102. /// Ideally, most of this would be done by lookup, but there's
  2103. /// actually quite a lot of extra work involved.
  2104. ///
  2105. /// Returns a null sentinel to indicate trivial success.
  2106. ExprResult
  2107. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2108. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2109. SourceLocation Loc = Lookup.getNameLoc();
  2110. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2111. // Check for error condition which is already reported.
  2112. if (!CurMethod)
  2113. return ExprError();
  2114. // There are two cases to handle here. 1) scoped lookup could have failed,
  2115. // in which case we should look for an ivar. 2) scoped lookup could have
  2116. // found a decl, but that decl is outside the current instance method (i.e.
  2117. // a global variable). In these two cases, we do a lookup for an ivar with
  2118. // this name, if the lookup sucedes, we replace it our current decl.
  2119. // If we're in a class method, we don't normally want to look for
  2120. // ivars. But if we don't find anything else, and there's an
  2121. // ivar, that's an error.
  2122. bool IsClassMethod = CurMethod->isClassMethod();
  2123. bool LookForIvars;
  2124. if (Lookup.empty())
  2125. LookForIvars = true;
  2126. else if (IsClassMethod)
  2127. LookForIvars = false;
  2128. else
  2129. LookForIvars = (Lookup.isSingleResult() &&
  2130. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2131. ObjCInterfaceDecl *IFace = nullptr;
  2132. if (LookForIvars) {
  2133. IFace = CurMethod->getClassInterface();
  2134. ObjCInterfaceDecl *ClassDeclared;
  2135. ObjCIvarDecl *IV = nullptr;
  2136. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2137. // Diagnose using an ivar in a class method.
  2138. if (IsClassMethod)
  2139. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2140. << IV->getDeclName());
  2141. // If we're referencing an invalid decl, just return this as a silent
  2142. // error node. The error diagnostic was already emitted on the decl.
  2143. if (IV->isInvalidDecl())
  2144. return ExprError();
  2145. // Check if referencing a field with __attribute__((deprecated)).
  2146. if (DiagnoseUseOfDecl(IV, Loc))
  2147. return ExprError();
  2148. // Diagnose the use of an ivar outside of the declaring class.
  2149. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2150. !declaresSameEntity(ClassDeclared, IFace) &&
  2151. !getLangOpts().DebuggerSupport)
  2152. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  2153. // FIXME: This should use a new expr for a direct reference, don't
  2154. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2155. IdentifierInfo &II = Context.Idents.get("self");
  2156. UnqualifiedId SelfName;
  2157. SelfName.setIdentifier(&II, SourceLocation());
  2158. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2159. CXXScopeSpec SelfScopeSpec;
  2160. SourceLocation TemplateKWLoc;
  2161. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2162. SelfName, false, false);
  2163. if (SelfExpr.isInvalid())
  2164. return ExprError();
  2165. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2166. if (SelfExpr.isInvalid())
  2167. return ExprError();
  2168. MarkAnyDeclReferenced(Loc, IV, true);
  2169. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2170. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2171. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2172. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2173. ObjCIvarRefExpr *Result = new (Context)
  2174. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2175. IV->getLocation(), SelfExpr.get(), true, true);
  2176. if (getLangOpts().ObjCAutoRefCount) {
  2177. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2178. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2179. recordUseOfEvaluatedWeak(Result);
  2180. }
  2181. if (CurContext->isClosure())
  2182. Diag(Loc, diag::warn_implicitly_retains_self)
  2183. << FixItHint::CreateInsertion(Loc, "self->");
  2184. }
  2185. return Result;
  2186. }
  2187. } else if (CurMethod->isInstanceMethod()) {
  2188. // We should warn if a local variable hides an ivar.
  2189. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2190. ObjCInterfaceDecl *ClassDeclared;
  2191. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2192. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2193. declaresSameEntity(IFace, ClassDeclared))
  2194. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2195. }
  2196. }
  2197. } else if (Lookup.isSingleResult() &&
  2198. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2199. // If accessing a stand-alone ivar in a class method, this is an error.
  2200. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2201. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2202. << IV->getDeclName());
  2203. }
  2204. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2205. // FIXME. Consolidate this with similar code in LookupName.
  2206. if (unsigned BuiltinID = II->getBuiltinID()) {
  2207. if (!(getLangOpts().CPlusPlus &&
  2208. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2209. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2210. S, Lookup.isForRedeclaration(),
  2211. Lookup.getNameLoc());
  2212. if (D) Lookup.addDecl(D);
  2213. }
  2214. }
  2215. }
  2216. // Sentinel value saying that we didn't do anything special.
  2217. return ExprResult((Expr *)nullptr);
  2218. }
  2219. /// \brief Cast a base object to a member's actual type.
  2220. ///
  2221. /// Logically this happens in three phases:
  2222. ///
  2223. /// * First we cast from the base type to the naming class.
  2224. /// The naming class is the class into which we were looking
  2225. /// when we found the member; it's the qualifier type if a
  2226. /// qualifier was provided, and otherwise it's the base type.
  2227. ///
  2228. /// * Next we cast from the naming class to the declaring class.
  2229. /// If the member we found was brought into a class's scope by
  2230. /// a using declaration, this is that class; otherwise it's
  2231. /// the class declaring the member.
  2232. ///
  2233. /// * Finally we cast from the declaring class to the "true"
  2234. /// declaring class of the member. This conversion does not
  2235. /// obey access control.
  2236. ExprResult
  2237. Sema::PerformObjectMemberConversion(Expr *From,
  2238. NestedNameSpecifier *Qualifier,
  2239. NamedDecl *FoundDecl,
  2240. NamedDecl *Member) {
  2241. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2242. if (!RD)
  2243. return From;
  2244. QualType DestRecordType;
  2245. QualType DestType;
  2246. QualType FromRecordType;
  2247. QualType FromType = From->getType();
  2248. bool PointerConversions = false;
  2249. if (isa<FieldDecl>(Member)) {
  2250. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2251. if (FromType->getAs<PointerType>()) {
  2252. DestType = Context.getPointerType(DestRecordType);
  2253. FromRecordType = FromType->getPointeeType();
  2254. PointerConversions = true;
  2255. } else {
  2256. DestType = DestRecordType;
  2257. FromRecordType = FromType;
  2258. }
  2259. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2260. if (Method->isStatic())
  2261. return From;
  2262. DestType = Method->getThisType(Context);
  2263. DestRecordType = DestType->getPointeeType();
  2264. if (FromType->getAs<PointerType>()) {
  2265. FromRecordType = FromType->getPointeeType();
  2266. PointerConversions = true;
  2267. } else {
  2268. FromRecordType = FromType;
  2269. DestType = DestRecordType;
  2270. }
  2271. } else {
  2272. // No conversion necessary.
  2273. return From;
  2274. }
  2275. if (DestType->isDependentType() || FromType->isDependentType())
  2276. return From;
  2277. // If the unqualified types are the same, no conversion is necessary.
  2278. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2279. return From;
  2280. SourceRange FromRange = From->getSourceRange();
  2281. SourceLocation FromLoc = FromRange.getBegin();
  2282. ExprValueKind VK = From->getValueKind();
  2283. // C++ [class.member.lookup]p8:
  2284. // [...] Ambiguities can often be resolved by qualifying a name with its
  2285. // class name.
  2286. //
  2287. // If the member was a qualified name and the qualified referred to a
  2288. // specific base subobject type, we'll cast to that intermediate type
  2289. // first and then to the object in which the member is declared. That allows
  2290. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2291. //
  2292. // class Base { public: int x; };
  2293. // class Derived1 : public Base { };
  2294. // class Derived2 : public Base { };
  2295. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2296. //
  2297. // void VeryDerived::f() {
  2298. // x = 17; // error: ambiguous base subobjects
  2299. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2300. // }
  2301. if (Qualifier && Qualifier->getAsType()) {
  2302. QualType QType = QualType(Qualifier->getAsType(), 0);
  2303. assert(QType->isRecordType() && "lookup done with non-record type");
  2304. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2305. // In C++98, the qualifier type doesn't actually have to be a base
  2306. // type of the object type, in which case we just ignore it.
  2307. // Otherwise build the appropriate casts.
  2308. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  2309. CXXCastPath BasePath;
  2310. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2311. FromLoc, FromRange, &BasePath))
  2312. return ExprError();
  2313. if (PointerConversions)
  2314. QType = Context.getPointerType(QType);
  2315. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2316. VK, &BasePath).get();
  2317. FromType = QType;
  2318. FromRecordType = QRecordType;
  2319. // If the qualifier type was the same as the destination type,
  2320. // we're done.
  2321. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2322. return From;
  2323. }
  2324. }
  2325. bool IgnoreAccess = false;
  2326. // If we actually found the member through a using declaration, cast
  2327. // down to the using declaration's type.
  2328. //
  2329. // Pointer equality is fine here because only one declaration of a
  2330. // class ever has member declarations.
  2331. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2332. assert(isa<UsingShadowDecl>(FoundDecl));
  2333. QualType URecordType = Context.getTypeDeclType(
  2334. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2335. // We only need to do this if the naming-class to declaring-class
  2336. // conversion is non-trivial.
  2337. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2338. assert(IsDerivedFrom(FromRecordType, URecordType));
  2339. CXXCastPath BasePath;
  2340. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2341. FromLoc, FromRange, &BasePath))
  2342. return ExprError();
  2343. QualType UType = URecordType;
  2344. if (PointerConversions)
  2345. UType = Context.getPointerType(UType);
  2346. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2347. VK, &BasePath).get();
  2348. FromType = UType;
  2349. FromRecordType = URecordType;
  2350. }
  2351. // We don't do access control for the conversion from the
  2352. // declaring class to the true declaring class.
  2353. IgnoreAccess = true;
  2354. }
  2355. CXXCastPath BasePath;
  2356. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2357. FromLoc, FromRange, &BasePath,
  2358. IgnoreAccess))
  2359. return ExprError();
  2360. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2361. VK, &BasePath);
  2362. }
  2363. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2364. const LookupResult &R,
  2365. bool HasTrailingLParen) {
  2366. // Only when used directly as the postfix-expression of a call.
  2367. if (!HasTrailingLParen)
  2368. return false;
  2369. // Never if a scope specifier was provided.
  2370. if (SS.isSet())
  2371. return false;
  2372. // Only in C++ or ObjC++.
  2373. if (!getLangOpts().CPlusPlus)
  2374. return false;
  2375. // Turn off ADL when we find certain kinds of declarations during
  2376. // normal lookup:
  2377. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2378. NamedDecl *D = *I;
  2379. // C++0x [basic.lookup.argdep]p3:
  2380. // -- a declaration of a class member
  2381. // Since using decls preserve this property, we check this on the
  2382. // original decl.
  2383. if (D->isCXXClassMember())
  2384. return false;
  2385. // C++0x [basic.lookup.argdep]p3:
  2386. // -- a block-scope function declaration that is not a
  2387. // using-declaration
  2388. // NOTE: we also trigger this for function templates (in fact, we
  2389. // don't check the decl type at all, since all other decl types
  2390. // turn off ADL anyway).
  2391. if (isa<UsingShadowDecl>(D))
  2392. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2393. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2394. return false;
  2395. // C++0x [basic.lookup.argdep]p3:
  2396. // -- a declaration that is neither a function or a function
  2397. // template
  2398. // And also for builtin functions.
  2399. if (isa<FunctionDecl>(D)) {
  2400. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2401. // But also builtin functions.
  2402. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2403. return false;
  2404. } else if (!isa<FunctionTemplateDecl>(D))
  2405. return false;
  2406. }
  2407. return true;
  2408. }
  2409. /// Diagnoses obvious problems with the use of the given declaration
  2410. /// as an expression. This is only actually called for lookups that
  2411. /// were not overloaded, and it doesn't promise that the declaration
  2412. /// will in fact be used.
  2413. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2414. if (isa<TypedefNameDecl>(D)) {
  2415. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2416. return true;
  2417. }
  2418. if (isa<ObjCInterfaceDecl>(D)) {
  2419. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2420. return true;
  2421. }
  2422. if (isa<NamespaceDecl>(D)) {
  2423. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2424. return true;
  2425. }
  2426. return false;
  2427. }
  2428. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2429. LookupResult &R, bool NeedsADL,
  2430. bool AcceptInvalidDecl) {
  2431. // If this is a single, fully-resolved result and we don't need ADL,
  2432. // just build an ordinary singleton decl ref.
  2433. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2434. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2435. R.getRepresentativeDecl(), nullptr,
  2436. AcceptInvalidDecl);
  2437. // We only need to check the declaration if there's exactly one
  2438. // result, because in the overloaded case the results can only be
  2439. // functions and function templates.
  2440. if (R.isSingleResult() &&
  2441. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2442. return ExprError();
  2443. // Otherwise, just build an unresolved lookup expression. Suppress
  2444. // any lookup-related diagnostics; we'll hash these out later, when
  2445. // we've picked a target.
  2446. R.suppressDiagnostics();
  2447. UnresolvedLookupExpr *ULE
  2448. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2449. SS.getWithLocInContext(Context),
  2450. R.getLookupNameInfo(),
  2451. NeedsADL, R.isOverloadedResult(),
  2452. R.begin(), R.end());
  2453. return ULE;
  2454. }
  2455. /// \brief Complete semantic analysis for a reference to the given declaration.
  2456. ExprResult Sema::BuildDeclarationNameExpr(
  2457. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2458. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2459. bool AcceptInvalidDecl) {
  2460. assert(D && "Cannot refer to a NULL declaration");
  2461. assert(!isa<FunctionTemplateDecl>(D) &&
  2462. "Cannot refer unambiguously to a function template");
  2463. SourceLocation Loc = NameInfo.getLoc();
  2464. if (CheckDeclInExpr(*this, Loc, D))
  2465. return ExprError();
  2466. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2467. // Specifically diagnose references to class templates that are missing
  2468. // a template argument list.
  2469. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2470. << Template << SS.getRange();
  2471. Diag(Template->getLocation(), diag::note_template_decl_here);
  2472. return ExprError();
  2473. }
  2474. // Make sure that we're referring to a value.
  2475. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2476. if (!VD) {
  2477. Diag(Loc, diag::err_ref_non_value)
  2478. << D << SS.getRange();
  2479. Diag(D->getLocation(), diag::note_declared_at);
  2480. return ExprError();
  2481. }
  2482. // Check whether this declaration can be used. Note that we suppress
  2483. // this check when we're going to perform argument-dependent lookup
  2484. // on this function name, because this might not be the function
  2485. // that overload resolution actually selects.
  2486. if (DiagnoseUseOfDecl(VD, Loc))
  2487. return ExprError();
  2488. // Only create DeclRefExpr's for valid Decl's.
  2489. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2490. return ExprError();
  2491. // Handle members of anonymous structs and unions. If we got here,
  2492. // and the reference is to a class member indirect field, then this
  2493. // must be the subject of a pointer-to-member expression.
  2494. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2495. if (!indirectField->isCXXClassMember())
  2496. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2497. indirectField);
  2498. {
  2499. QualType type = VD->getType();
  2500. ExprValueKind valueKind = VK_RValue;
  2501. switch (D->getKind()) {
  2502. // Ignore all the non-ValueDecl kinds.
  2503. #define ABSTRACT_DECL(kind)
  2504. #define VALUE(type, base)
  2505. #define DECL(type, base) \
  2506. case Decl::type:
  2507. #include "clang/AST/DeclNodes.inc"
  2508. llvm_unreachable("invalid value decl kind");
  2509. // These shouldn't make it here.
  2510. case Decl::ObjCAtDefsField:
  2511. case Decl::ObjCIvar:
  2512. llvm_unreachable("forming non-member reference to ivar?");
  2513. // Enum constants are always r-values and never references.
  2514. // Unresolved using declarations are dependent.
  2515. case Decl::EnumConstant:
  2516. case Decl::UnresolvedUsingValue:
  2517. valueKind = VK_RValue;
  2518. break;
  2519. // Fields and indirect fields that got here must be for
  2520. // pointer-to-member expressions; we just call them l-values for
  2521. // internal consistency, because this subexpression doesn't really
  2522. // exist in the high-level semantics.
  2523. case Decl::Field:
  2524. case Decl::IndirectField:
  2525. assert(getLangOpts().CPlusPlus &&
  2526. "building reference to field in C?");
  2527. // These can't have reference type in well-formed programs, but
  2528. // for internal consistency we do this anyway.
  2529. type = type.getNonReferenceType();
  2530. valueKind = VK_LValue;
  2531. break;
  2532. // Non-type template parameters are either l-values or r-values
  2533. // depending on the type.
  2534. case Decl::NonTypeTemplateParm: {
  2535. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2536. type = reftype->getPointeeType();
  2537. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2538. break;
  2539. }
  2540. // For non-references, we need to strip qualifiers just in case
  2541. // the template parameter was declared as 'const int' or whatever.
  2542. valueKind = VK_RValue;
  2543. type = type.getUnqualifiedType();
  2544. break;
  2545. }
  2546. case Decl::Var:
  2547. case Decl::VarTemplateSpecialization:
  2548. case Decl::VarTemplatePartialSpecialization:
  2549. // In C, "extern void blah;" is valid and is an r-value.
  2550. if (!getLangOpts().CPlusPlus &&
  2551. !type.hasQualifiers() &&
  2552. type->isVoidType()) {
  2553. valueKind = VK_RValue;
  2554. break;
  2555. }
  2556. // fallthrough
  2557. case Decl::ImplicitParam:
  2558. case Decl::ParmVar: {
  2559. // These are always l-values.
  2560. valueKind = VK_LValue;
  2561. type = type.getNonReferenceType();
  2562. // FIXME: Does the addition of const really only apply in
  2563. // potentially-evaluated contexts? Since the variable isn't actually
  2564. // captured in an unevaluated context, it seems that the answer is no.
  2565. if (!isUnevaluatedContext()) {
  2566. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2567. if (!CapturedType.isNull())
  2568. type = CapturedType;
  2569. }
  2570. break;
  2571. }
  2572. case Decl::Function: {
  2573. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2574. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2575. type = Context.BuiltinFnTy;
  2576. valueKind = VK_RValue;
  2577. break;
  2578. }
  2579. }
  2580. const FunctionType *fty = type->castAs<FunctionType>();
  2581. // If we're referring to a function with an __unknown_anytype
  2582. // result type, make the entire expression __unknown_anytype.
  2583. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2584. type = Context.UnknownAnyTy;
  2585. valueKind = VK_RValue;
  2586. break;
  2587. }
  2588. // Functions are l-values in C++.
  2589. if (getLangOpts().CPlusPlus) {
  2590. valueKind = VK_LValue;
  2591. break;
  2592. }
  2593. // C99 DR 316 says that, if a function type comes from a
  2594. // function definition (without a prototype), that type is only
  2595. // used for checking compatibility. Therefore, when referencing
  2596. // the function, we pretend that we don't have the full function
  2597. // type.
  2598. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2599. isa<FunctionProtoType>(fty))
  2600. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2601. fty->getExtInfo());
  2602. // Functions are r-values in C.
  2603. valueKind = VK_RValue;
  2604. break;
  2605. }
  2606. case Decl::MSProperty:
  2607. valueKind = VK_LValue;
  2608. break;
  2609. case Decl::CXXMethod:
  2610. // If we're referring to a method with an __unknown_anytype
  2611. // result type, make the entire expression __unknown_anytype.
  2612. // This should only be possible with a type written directly.
  2613. if (const FunctionProtoType *proto
  2614. = dyn_cast<FunctionProtoType>(VD->getType()))
  2615. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2616. type = Context.UnknownAnyTy;
  2617. valueKind = VK_RValue;
  2618. break;
  2619. }
  2620. // C++ methods are l-values if static, r-values if non-static.
  2621. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2622. valueKind = VK_LValue;
  2623. break;
  2624. }
  2625. // fallthrough
  2626. case Decl::CXXConversion:
  2627. case Decl::CXXDestructor:
  2628. case Decl::CXXConstructor:
  2629. valueKind = VK_RValue;
  2630. break;
  2631. }
  2632. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2633. TemplateArgs);
  2634. }
  2635. }
  2636. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2637. SmallString<32> &Target) {
  2638. Target.resize(CharByteWidth * (Source.size() + 1));
  2639. char *ResultPtr = &Target[0];
  2640. const UTF8 *ErrorPtr;
  2641. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2642. (void)success;
  2643. assert(success);
  2644. Target.resize(ResultPtr - &Target[0]);
  2645. }
  2646. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2647. PredefinedExpr::IdentType IT) {
  2648. // Pick the current block, lambda, captured statement or function.
  2649. Decl *currentDecl = nullptr;
  2650. if (const BlockScopeInfo *BSI = getCurBlock())
  2651. currentDecl = BSI->TheDecl;
  2652. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2653. currentDecl = LSI->CallOperator;
  2654. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2655. currentDecl = CSI->TheCapturedDecl;
  2656. else
  2657. currentDecl = getCurFunctionOrMethodDecl();
  2658. if (!currentDecl) {
  2659. Diag(Loc, diag::ext_predef_outside_function);
  2660. currentDecl = Context.getTranslationUnitDecl();
  2661. }
  2662. QualType ResTy;
  2663. StringLiteral *SL = nullptr;
  2664. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2665. ResTy = Context.DependentTy;
  2666. else {
  2667. // Pre-defined identifiers are of type char[x], where x is the length of
  2668. // the string.
  2669. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2670. unsigned Length = Str.length();
  2671. llvm::APInt LengthI(32, Length + 1);
  2672. if (IT == PredefinedExpr::LFunction) {
  2673. ResTy = Context.WideCharTy.withConst();
  2674. SmallString<32> RawChars;
  2675. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2676. Str, RawChars);
  2677. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2678. /*IndexTypeQuals*/ 0);
  2679. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2680. /*Pascal*/ false, ResTy, Loc);
  2681. } else {
  2682. ResTy = Context.CharTy.withConst();
  2683. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2684. /*IndexTypeQuals*/ 0);
  2685. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2686. /*Pascal*/ false, ResTy, Loc);
  2687. }
  2688. }
  2689. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2690. }
  2691. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2692. PredefinedExpr::IdentType IT;
  2693. switch (Kind) {
  2694. default: llvm_unreachable("Unknown simple primary expr!");
  2695. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2696. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2697. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2698. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2699. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2700. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2701. }
  2702. return BuildPredefinedExpr(Loc, IT);
  2703. }
  2704. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2705. SmallString<16> CharBuffer;
  2706. bool Invalid = false;
  2707. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2708. if (Invalid)
  2709. return ExprError();
  2710. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2711. PP, Tok.getKind());
  2712. if (Literal.hadError())
  2713. return ExprError();
  2714. QualType Ty;
  2715. if (Literal.isWide())
  2716. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2717. else if (Literal.isUTF16())
  2718. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2719. else if (Literal.isUTF32())
  2720. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2721. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2722. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2723. else
  2724. Ty = Context.CharTy; // 'x' -> char in C++
  2725. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2726. if (Literal.isWide())
  2727. Kind = CharacterLiteral::Wide;
  2728. else if (Literal.isUTF16())
  2729. Kind = CharacterLiteral::UTF16;
  2730. else if (Literal.isUTF32())
  2731. Kind = CharacterLiteral::UTF32;
  2732. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2733. Tok.getLocation());
  2734. if (Literal.getUDSuffix().empty())
  2735. return Lit;
  2736. // We're building a user-defined literal.
  2737. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2738. SourceLocation UDSuffixLoc =
  2739. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2740. // Make sure we're allowed user-defined literals here.
  2741. if (!UDLScope)
  2742. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2743. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2744. // operator "" X (ch)
  2745. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2746. Lit, Tok.getLocation());
  2747. }
  2748. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2749. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2750. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2751. Context.IntTy, Loc);
  2752. }
  2753. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2754. QualType Ty, SourceLocation Loc) {
  2755. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2756. using llvm::APFloat;
  2757. APFloat Val(Format);
  2758. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2759. // Overflow is always an error, but underflow is only an error if
  2760. // we underflowed to zero (APFloat reports denormals as underflow).
  2761. if ((result & APFloat::opOverflow) ||
  2762. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2763. unsigned diagnostic;
  2764. SmallString<20> buffer;
  2765. if (result & APFloat::opOverflow) {
  2766. diagnostic = diag::warn_float_overflow;
  2767. APFloat::getLargest(Format).toString(buffer);
  2768. } else {
  2769. diagnostic = diag::warn_float_underflow;
  2770. APFloat::getSmallest(Format).toString(buffer);
  2771. }
  2772. S.Diag(Loc, diagnostic)
  2773. << Ty
  2774. << StringRef(buffer.data(), buffer.size());
  2775. }
  2776. bool isExact = (result == APFloat::opOK);
  2777. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2778. }
  2779. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2780. assert(E && "Invalid expression");
  2781. if (E->isValueDependent())
  2782. return false;
  2783. QualType QT = E->getType();
  2784. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2785. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2786. return true;
  2787. }
  2788. llvm::APSInt ValueAPS;
  2789. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2790. if (R.isInvalid())
  2791. return true;
  2792. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2793. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2794. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2795. << ValueAPS.toString(10) << ValueIsPositive;
  2796. return true;
  2797. }
  2798. return false;
  2799. }
  2800. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2801. // Fast path for a single digit (which is quite common). A single digit
  2802. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2803. if (Tok.getLength() == 1) {
  2804. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2805. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2806. }
  2807. SmallString<128> SpellingBuffer;
  2808. // NumericLiteralParser wants to overread by one character. Add padding to
  2809. // the buffer in case the token is copied to the buffer. If getSpelling()
  2810. // returns a StringRef to the memory buffer, it should have a null char at
  2811. // the EOF, so it is also safe.
  2812. SpellingBuffer.resize(Tok.getLength() + 1);
  2813. // Get the spelling of the token, which eliminates trigraphs, etc.
  2814. bool Invalid = false;
  2815. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2816. if (Invalid)
  2817. return ExprError();
  2818. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2819. if (Literal.hadError)
  2820. return ExprError();
  2821. if (Literal.hasUDSuffix()) {
  2822. // We're building a user-defined literal.
  2823. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2824. SourceLocation UDSuffixLoc =
  2825. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2826. // Make sure we're allowed user-defined literals here.
  2827. if (!UDLScope)
  2828. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2829. QualType CookedTy;
  2830. if (Literal.isFloatingLiteral()) {
  2831. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2832. // long double, the literal is treated as a call of the form
  2833. // operator "" X (f L)
  2834. CookedTy = Context.LongDoubleTy;
  2835. } else {
  2836. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2837. // unsigned long long, the literal is treated as a call of the form
  2838. // operator "" X (n ULL)
  2839. CookedTy = Context.UnsignedLongLongTy;
  2840. }
  2841. DeclarationName OpName =
  2842. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2843. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2844. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2845. SourceLocation TokLoc = Tok.getLocation();
  2846. // Perform literal operator lookup to determine if we're building a raw
  2847. // literal or a cooked one.
  2848. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2849. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2850. /*AllowRaw*/true, /*AllowTemplate*/true,
  2851. /*AllowStringTemplate*/false)) {
  2852. case LOLR_Error:
  2853. return ExprError();
  2854. case LOLR_Cooked: {
  2855. Expr *Lit;
  2856. if (Literal.isFloatingLiteral()) {
  2857. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2858. } else {
  2859. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2860. if (Literal.GetIntegerValue(ResultVal))
  2861. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2862. << /* Unsigned */ 1;
  2863. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2864. Tok.getLocation());
  2865. }
  2866. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2867. }
  2868. case LOLR_Raw: {
  2869. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2870. // literal is treated as a call of the form
  2871. // operator "" X ("n")
  2872. unsigned Length = Literal.getUDSuffixOffset();
  2873. QualType StrTy = Context.getConstantArrayType(
  2874. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2875. ArrayType::Normal, 0);
  2876. Expr *Lit = StringLiteral::Create(
  2877. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2878. /*Pascal*/false, StrTy, &TokLoc, 1);
  2879. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2880. }
  2881. case LOLR_Template: {
  2882. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2883. // template), L is treated as a call fo the form
  2884. // operator "" X <'c1', 'c2', ... 'ck'>()
  2885. // where n is the source character sequence c1 c2 ... ck.
  2886. TemplateArgumentListInfo ExplicitArgs;
  2887. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2888. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2889. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2890. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2891. Value = TokSpelling[I];
  2892. TemplateArgument Arg(Context, Value, Context.CharTy);
  2893. TemplateArgumentLocInfo ArgInfo;
  2894. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2895. }
  2896. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2897. &ExplicitArgs);
  2898. }
  2899. case LOLR_StringTemplate:
  2900. llvm_unreachable("unexpected literal operator lookup result");
  2901. }
  2902. }
  2903. Expr *Res;
  2904. if (Literal.isFloatingLiteral()) {
  2905. QualType Ty;
  2906. if (Literal.isFloat)
  2907. Ty = Context.FloatTy;
  2908. else if (!Literal.isLong)
  2909. Ty = Context.DoubleTy;
  2910. else
  2911. Ty = Context.LongDoubleTy;
  2912. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2913. if (Ty == Context.DoubleTy) {
  2914. if (getLangOpts().SinglePrecisionConstants) {
  2915. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2916. } else if (getLangOpts().OpenCL &&
  2917. !((getLangOpts().OpenCLVersion >= 120) ||
  2918. getOpenCLOptions().cl_khr_fp64)) {
  2919. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2920. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2921. }
  2922. }
  2923. } else if (!Literal.isIntegerLiteral()) {
  2924. return ExprError();
  2925. } else {
  2926. QualType Ty;
  2927. // 'long long' is a C99 or C++11 feature.
  2928. if (!getLangOpts().C99 && Literal.isLongLong) {
  2929. if (getLangOpts().CPlusPlus)
  2930. Diag(Tok.getLocation(),
  2931. getLangOpts().CPlusPlus11 ?
  2932. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  2933. else
  2934. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  2935. }
  2936. // Get the value in the widest-possible width.
  2937. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  2938. llvm::APInt ResultVal(MaxWidth, 0);
  2939. if (Literal.GetIntegerValue(ResultVal)) {
  2940. // If this value didn't fit into uintmax_t, error and force to ull.
  2941. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2942. << /* Unsigned */ 1;
  2943. Ty = Context.UnsignedLongLongTy;
  2944. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  2945. "long long is not intmax_t?");
  2946. } else {
  2947. // If this value fits into a ULL, try to figure out what else it fits into
  2948. // according to the rules of C99 6.4.4.1p5.
  2949. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  2950. // be an unsigned int.
  2951. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  2952. // Check from smallest to largest, picking the smallest type we can.
  2953. unsigned Width = 0;
  2954. // Microsoft specific integer suffixes are explicitly sized.
  2955. if (Literal.MicrosoftInteger) {
  2956. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  2957. Width = 8;
  2958. Ty = Context.CharTy;
  2959. } else {
  2960. Width = Literal.MicrosoftInteger;
  2961. Ty = Context.getIntTypeForBitwidth(Width,
  2962. /*Signed=*/!Literal.isUnsigned);
  2963. }
  2964. }
  2965. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  2966. // Are int/unsigned possibilities?
  2967. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2968. // Does it fit in a unsigned int?
  2969. if (ResultVal.isIntN(IntSize)) {
  2970. // Does it fit in a signed int?
  2971. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  2972. Ty = Context.IntTy;
  2973. else if (AllowUnsigned)
  2974. Ty = Context.UnsignedIntTy;
  2975. Width = IntSize;
  2976. }
  2977. }
  2978. // Are long/unsigned long possibilities?
  2979. if (Ty.isNull() && !Literal.isLongLong) {
  2980. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  2981. // Does it fit in a unsigned long?
  2982. if (ResultVal.isIntN(LongSize)) {
  2983. // Does it fit in a signed long?
  2984. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  2985. Ty = Context.LongTy;
  2986. else if (AllowUnsigned)
  2987. Ty = Context.UnsignedLongTy;
  2988. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  2989. // is compatible.
  2990. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  2991. const unsigned LongLongSize =
  2992. Context.getTargetInfo().getLongLongWidth();
  2993. Diag(Tok.getLocation(),
  2994. getLangOpts().CPlusPlus
  2995. ? Literal.isLong
  2996. ? diag::warn_old_implicitly_unsigned_long_cxx
  2997. : /*C++98 UB*/ diag::
  2998. ext_old_implicitly_unsigned_long_cxx
  2999. : diag::warn_old_implicitly_unsigned_long)
  3000. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3001. : /*will be ill-formed*/ 1);
  3002. Ty = Context.UnsignedLongTy;
  3003. }
  3004. Width = LongSize;
  3005. }
  3006. }
  3007. // Check long long if needed.
  3008. if (Ty.isNull()) {
  3009. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3010. // Does it fit in a unsigned long long?
  3011. if (ResultVal.isIntN(LongLongSize)) {
  3012. // Does it fit in a signed long long?
  3013. // To be compatible with MSVC, hex integer literals ending with the
  3014. // LL or i64 suffix are always signed in Microsoft mode.
  3015. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3016. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  3017. Ty = Context.LongLongTy;
  3018. else if (AllowUnsigned)
  3019. Ty = Context.UnsignedLongLongTy;
  3020. Width = LongLongSize;
  3021. }
  3022. }
  3023. // If we still couldn't decide a type, we probably have something that
  3024. // does not fit in a signed long long, but has no U suffix.
  3025. if (Ty.isNull()) {
  3026. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3027. Ty = Context.UnsignedLongLongTy;
  3028. Width = Context.getTargetInfo().getLongLongWidth();
  3029. }
  3030. if (ResultVal.getBitWidth() != Width)
  3031. ResultVal = ResultVal.trunc(Width);
  3032. }
  3033. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3034. }
  3035. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3036. if (Literal.isImaginary)
  3037. Res = new (Context) ImaginaryLiteral(Res,
  3038. Context.getComplexType(Res->getType()));
  3039. return Res;
  3040. }
  3041. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3042. assert(E && "ActOnParenExpr() missing expr");
  3043. return new (Context) ParenExpr(L, R, E);
  3044. }
  3045. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3046. SourceLocation Loc,
  3047. SourceRange ArgRange) {
  3048. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3049. // scalar or vector data type argument..."
  3050. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3051. // type (C99 6.2.5p18) or void.
  3052. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3053. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3054. << T << ArgRange;
  3055. return true;
  3056. }
  3057. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3058. "Scalar types should always be complete");
  3059. return false;
  3060. }
  3061. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3062. SourceLocation Loc,
  3063. SourceRange ArgRange,
  3064. UnaryExprOrTypeTrait TraitKind) {
  3065. // Invalid types must be hard errors for SFINAE in C++.
  3066. if (S.LangOpts.CPlusPlus)
  3067. return true;
  3068. // C99 6.5.3.4p1:
  3069. if (T->isFunctionType() &&
  3070. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3071. // sizeof(function)/alignof(function) is allowed as an extension.
  3072. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3073. << TraitKind << ArgRange;
  3074. return false;
  3075. }
  3076. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3077. // this is an error (OpenCL v1.1 s6.3.k)
  3078. if (T->isVoidType()) {
  3079. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3080. : diag::ext_sizeof_alignof_void_type;
  3081. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3082. return false;
  3083. }
  3084. return true;
  3085. }
  3086. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3087. SourceLocation Loc,
  3088. SourceRange ArgRange,
  3089. UnaryExprOrTypeTrait TraitKind) {
  3090. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3091. // runtime doesn't allow it.
  3092. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3093. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3094. << T << (TraitKind == UETT_SizeOf)
  3095. << ArgRange;
  3096. return true;
  3097. }
  3098. return false;
  3099. }
  3100. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3101. /// pointer type is equal to T) and emit a warning if it is.
  3102. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3103. Expr *E) {
  3104. // Don't warn if the operation changed the type.
  3105. if (T != E->getType())
  3106. return;
  3107. // Now look for array decays.
  3108. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3109. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3110. return;
  3111. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3112. << ICE->getType()
  3113. << ICE->getSubExpr()->getType();
  3114. }
  3115. /// \brief Check the constraints on expression operands to unary type expression
  3116. /// and type traits.
  3117. ///
  3118. /// Completes any types necessary and validates the constraints on the operand
  3119. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3120. /// the expression as it completes the type for that expression through template
  3121. /// instantiation, etc.
  3122. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3123. UnaryExprOrTypeTrait ExprKind) {
  3124. QualType ExprTy = E->getType();
  3125. assert(!ExprTy->isReferenceType());
  3126. if (ExprKind == UETT_VecStep)
  3127. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3128. E->getSourceRange());
  3129. // Whitelist some types as extensions
  3130. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3131. E->getSourceRange(), ExprKind))
  3132. return false;
  3133. // 'alignof' applied to an expression only requires the base element type of
  3134. // the expression to be complete. 'sizeof' requires the expression's type to
  3135. // be complete (and will attempt to complete it if it's an array of unknown
  3136. // bound).
  3137. if (ExprKind == UETT_AlignOf) {
  3138. if (RequireCompleteType(E->getExprLoc(),
  3139. Context.getBaseElementType(E->getType()),
  3140. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3141. E->getSourceRange()))
  3142. return true;
  3143. } else {
  3144. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3145. ExprKind, E->getSourceRange()))
  3146. return true;
  3147. }
  3148. // Completing the expression's type may have changed it.
  3149. ExprTy = E->getType();
  3150. assert(!ExprTy->isReferenceType());
  3151. if (ExprTy->isFunctionType()) {
  3152. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3153. << ExprKind << E->getSourceRange();
  3154. return true;
  3155. }
  3156. // The operand for sizeof and alignof is in an unevaluated expression context,
  3157. // so side effects could result in unintended consequences.
  3158. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3159. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3160. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3161. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3162. E->getSourceRange(), ExprKind))
  3163. return true;
  3164. if (ExprKind == UETT_SizeOf) {
  3165. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3166. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3167. QualType OType = PVD->getOriginalType();
  3168. QualType Type = PVD->getType();
  3169. if (Type->isPointerType() && OType->isArrayType()) {
  3170. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3171. << Type << OType;
  3172. Diag(PVD->getLocation(), diag::note_declared_at);
  3173. }
  3174. }
  3175. }
  3176. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3177. // decays into a pointer and returns an unintended result. This is most
  3178. // likely a typo for "sizeof(array) op x".
  3179. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3180. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3181. BO->getLHS());
  3182. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3183. BO->getRHS());
  3184. }
  3185. }
  3186. return false;
  3187. }
  3188. /// \brief Check the constraints on operands to unary expression and type
  3189. /// traits.
  3190. ///
  3191. /// This will complete any types necessary, and validate the various constraints
  3192. /// on those operands.
  3193. ///
  3194. /// The UsualUnaryConversions() function is *not* called by this routine.
  3195. /// C99 6.3.2.1p[2-4] all state:
  3196. /// Except when it is the operand of the sizeof operator ...
  3197. ///
  3198. /// C++ [expr.sizeof]p4
  3199. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3200. /// standard conversions are not applied to the operand of sizeof.
  3201. ///
  3202. /// This policy is followed for all of the unary trait expressions.
  3203. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3204. SourceLocation OpLoc,
  3205. SourceRange ExprRange,
  3206. UnaryExprOrTypeTrait ExprKind) {
  3207. if (ExprType->isDependentType())
  3208. return false;
  3209. // C++ [expr.sizeof]p2:
  3210. // When applied to a reference or a reference type, the result
  3211. // is the size of the referenced type.
  3212. // C++11 [expr.alignof]p3:
  3213. // When alignof is applied to a reference type, the result
  3214. // shall be the alignment of the referenced type.
  3215. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3216. ExprType = Ref->getPointeeType();
  3217. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3218. // When alignof or _Alignof is applied to an array type, the result
  3219. // is the alignment of the element type.
  3220. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3221. ExprType = Context.getBaseElementType(ExprType);
  3222. if (ExprKind == UETT_VecStep)
  3223. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3224. // Whitelist some types as extensions
  3225. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3226. ExprKind))
  3227. return false;
  3228. if (RequireCompleteType(OpLoc, ExprType,
  3229. diag::err_sizeof_alignof_incomplete_type,
  3230. ExprKind, ExprRange))
  3231. return true;
  3232. if (ExprType->isFunctionType()) {
  3233. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3234. << ExprKind << ExprRange;
  3235. return true;
  3236. }
  3237. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3238. ExprKind))
  3239. return true;
  3240. return false;
  3241. }
  3242. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3243. E = E->IgnoreParens();
  3244. // Cannot know anything else if the expression is dependent.
  3245. if (E->isTypeDependent())
  3246. return false;
  3247. if (E->getObjectKind() == OK_BitField) {
  3248. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  3249. << 1 << E->getSourceRange();
  3250. return true;
  3251. }
  3252. ValueDecl *D = nullptr;
  3253. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3254. D = DRE->getDecl();
  3255. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3256. D = ME->getMemberDecl();
  3257. }
  3258. // If it's a field, require the containing struct to have a
  3259. // complete definition so that we can compute the layout.
  3260. //
  3261. // This can happen in C++11 onwards, either by naming the member
  3262. // in a way that is not transformed into a member access expression
  3263. // (in an unevaluated operand, for instance), or by naming the member
  3264. // in a trailing-return-type.
  3265. //
  3266. // For the record, since __alignof__ on expressions is a GCC
  3267. // extension, GCC seems to permit this but always gives the
  3268. // nonsensical answer 0.
  3269. //
  3270. // We don't really need the layout here --- we could instead just
  3271. // directly check for all the appropriate alignment-lowing
  3272. // attributes --- but that would require duplicating a lot of
  3273. // logic that just isn't worth duplicating for such a marginal
  3274. // use-case.
  3275. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3276. // Fast path this check, since we at least know the record has a
  3277. // definition if we can find a member of it.
  3278. if (!FD->getParent()->isCompleteDefinition()) {
  3279. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3280. << E->getSourceRange();
  3281. return true;
  3282. }
  3283. // Otherwise, if it's a field, and the field doesn't have
  3284. // reference type, then it must have a complete type (or be a
  3285. // flexible array member, which we explicitly want to
  3286. // white-list anyway), which makes the following checks trivial.
  3287. if (!FD->getType()->isReferenceType())
  3288. return false;
  3289. }
  3290. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3291. }
  3292. bool Sema::CheckVecStepExpr(Expr *E) {
  3293. E = E->IgnoreParens();
  3294. // Cannot know anything else if the expression is dependent.
  3295. if (E->isTypeDependent())
  3296. return false;
  3297. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3298. }
  3299. /// \brief Build a sizeof or alignof expression given a type operand.
  3300. ExprResult
  3301. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3302. SourceLocation OpLoc,
  3303. UnaryExprOrTypeTrait ExprKind,
  3304. SourceRange R) {
  3305. if (!TInfo)
  3306. return ExprError();
  3307. QualType T = TInfo->getType();
  3308. if (!T->isDependentType() &&
  3309. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3310. return ExprError();
  3311. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3312. return new (Context) UnaryExprOrTypeTraitExpr(
  3313. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3314. }
  3315. /// \brief Build a sizeof or alignof expression given an expression
  3316. /// operand.
  3317. ExprResult
  3318. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3319. UnaryExprOrTypeTrait ExprKind) {
  3320. ExprResult PE = CheckPlaceholderExpr(E);
  3321. if (PE.isInvalid())
  3322. return ExprError();
  3323. E = PE.get();
  3324. // Verify that the operand is valid.
  3325. bool isInvalid = false;
  3326. if (E->isTypeDependent()) {
  3327. // Delay type-checking for type-dependent expressions.
  3328. } else if (ExprKind == UETT_AlignOf) {
  3329. isInvalid = CheckAlignOfExpr(*this, E);
  3330. } else if (ExprKind == UETT_VecStep) {
  3331. isInvalid = CheckVecStepExpr(E);
  3332. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3333. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3334. isInvalid = true;
  3335. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3336. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  3337. isInvalid = true;
  3338. } else {
  3339. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3340. }
  3341. if (isInvalid)
  3342. return ExprError();
  3343. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3344. PE = TransformToPotentiallyEvaluated(E);
  3345. if (PE.isInvalid()) return ExprError();
  3346. E = PE.get();
  3347. }
  3348. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3349. return new (Context) UnaryExprOrTypeTraitExpr(
  3350. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3351. }
  3352. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3353. /// expr and the same for @c alignof and @c __alignof
  3354. /// Note that the ArgRange is invalid if isType is false.
  3355. ExprResult
  3356. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3357. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3358. void *TyOrEx, const SourceRange &ArgRange) {
  3359. // If error parsing type, ignore.
  3360. if (!TyOrEx) return ExprError();
  3361. if (IsType) {
  3362. TypeSourceInfo *TInfo;
  3363. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3364. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3365. }
  3366. Expr *ArgEx = (Expr *)TyOrEx;
  3367. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3368. return Result;
  3369. }
  3370. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3371. bool IsReal) {
  3372. if (V.get()->isTypeDependent())
  3373. return S.Context.DependentTy;
  3374. // _Real and _Imag are only l-values for normal l-values.
  3375. if (V.get()->getObjectKind() != OK_Ordinary) {
  3376. V = S.DefaultLvalueConversion(V.get());
  3377. if (V.isInvalid())
  3378. return QualType();
  3379. }
  3380. // These operators return the element type of a complex type.
  3381. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3382. return CT->getElementType();
  3383. // Otherwise they pass through real integer and floating point types here.
  3384. if (V.get()->getType()->isArithmeticType())
  3385. return V.get()->getType();
  3386. // Test for placeholders.
  3387. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3388. if (PR.isInvalid()) return QualType();
  3389. if (PR.get() != V.get()) {
  3390. V = PR;
  3391. return CheckRealImagOperand(S, V, Loc, IsReal);
  3392. }
  3393. // Reject anything else.
  3394. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3395. << (IsReal ? "__real" : "__imag");
  3396. return QualType();
  3397. }
  3398. ExprResult
  3399. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3400. tok::TokenKind Kind, Expr *Input) {
  3401. UnaryOperatorKind Opc;
  3402. switch (Kind) {
  3403. default: llvm_unreachable("Unknown unary op!");
  3404. case tok::plusplus: Opc = UO_PostInc; break;
  3405. case tok::minusminus: Opc = UO_PostDec; break;
  3406. }
  3407. // Since this might is a postfix expression, get rid of ParenListExprs.
  3408. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3409. if (Result.isInvalid()) return ExprError();
  3410. Input = Result.get();
  3411. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3412. }
  3413. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3414. ///
  3415. /// \return true on error
  3416. static bool checkArithmeticOnObjCPointer(Sema &S,
  3417. SourceLocation opLoc,
  3418. Expr *op) {
  3419. assert(op->getType()->isObjCObjectPointerType());
  3420. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3421. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3422. return false;
  3423. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3424. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3425. << op->getSourceRange();
  3426. return true;
  3427. }
  3428. ExprResult
  3429. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3430. Expr *idx, SourceLocation rbLoc) {
  3431. // Since this might be a postfix expression, get rid of ParenListExprs.
  3432. if (isa<ParenListExpr>(base)) {
  3433. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3434. if (result.isInvalid()) return ExprError();
  3435. base = result.get();
  3436. }
  3437. // Handle any non-overload placeholder types in the base and index
  3438. // expressions. We can't handle overloads here because the other
  3439. // operand might be an overloadable type, in which case the overload
  3440. // resolution for the operator overload should get the first crack
  3441. // at the overload.
  3442. if (base->getType()->isNonOverloadPlaceholderType()) {
  3443. ExprResult result = CheckPlaceholderExpr(base);
  3444. if (result.isInvalid()) return ExprError();
  3445. base = result.get();
  3446. }
  3447. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3448. ExprResult result = CheckPlaceholderExpr(idx);
  3449. if (result.isInvalid()) return ExprError();
  3450. idx = result.get();
  3451. }
  3452. // Build an unanalyzed expression if either operand is type-dependent.
  3453. if (getLangOpts().CPlusPlus &&
  3454. (base->isTypeDependent() || idx->isTypeDependent())) {
  3455. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3456. VK_LValue, OK_Ordinary, rbLoc);
  3457. }
  3458. // Use C++ overloaded-operator rules if either operand has record
  3459. // type. The spec says to do this if either type is *overloadable*,
  3460. // but enum types can't declare subscript operators or conversion
  3461. // operators, so there's nothing interesting for overload resolution
  3462. // to do if there aren't any record types involved.
  3463. //
  3464. // ObjC pointers have their own subscripting logic that is not tied
  3465. // to overload resolution and so should not take this path.
  3466. if (getLangOpts().CPlusPlus &&
  3467. (base->getType()->isRecordType() ||
  3468. (!base->getType()->isObjCObjectPointerType() &&
  3469. idx->getType()->isRecordType()))) {
  3470. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3471. }
  3472. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3473. }
  3474. ExprResult
  3475. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3476. Expr *Idx, SourceLocation RLoc) {
  3477. Expr *LHSExp = Base;
  3478. Expr *RHSExp = Idx;
  3479. // Perform default conversions.
  3480. if (!LHSExp->getType()->getAs<VectorType>()) {
  3481. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3482. if (Result.isInvalid())
  3483. return ExprError();
  3484. LHSExp = Result.get();
  3485. }
  3486. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3487. if (Result.isInvalid())
  3488. return ExprError();
  3489. RHSExp = Result.get();
  3490. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3491. ExprValueKind VK = VK_LValue;
  3492. ExprObjectKind OK = OK_Ordinary;
  3493. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3494. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3495. // in the subscript position. As a result, we need to derive the array base
  3496. // and index from the expression types.
  3497. Expr *BaseExpr, *IndexExpr;
  3498. QualType ResultType;
  3499. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3500. BaseExpr = LHSExp;
  3501. IndexExpr = RHSExp;
  3502. ResultType = Context.DependentTy;
  3503. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3504. BaseExpr = LHSExp;
  3505. IndexExpr = RHSExp;
  3506. ResultType = PTy->getPointeeType();
  3507. } else if (const ObjCObjectPointerType *PTy =
  3508. LHSTy->getAs<ObjCObjectPointerType>()) {
  3509. BaseExpr = LHSExp;
  3510. IndexExpr = RHSExp;
  3511. // Use custom logic if this should be the pseudo-object subscript
  3512. // expression.
  3513. if (!LangOpts.isSubscriptPointerArithmetic())
  3514. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3515. nullptr);
  3516. ResultType = PTy->getPointeeType();
  3517. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3518. // Handle the uncommon case of "123[Ptr]".
  3519. BaseExpr = RHSExp;
  3520. IndexExpr = LHSExp;
  3521. ResultType = PTy->getPointeeType();
  3522. } else if (const ObjCObjectPointerType *PTy =
  3523. RHSTy->getAs<ObjCObjectPointerType>()) {
  3524. // Handle the uncommon case of "123[Ptr]".
  3525. BaseExpr = RHSExp;
  3526. IndexExpr = LHSExp;
  3527. ResultType = PTy->getPointeeType();
  3528. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3529. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3530. << ResultType << BaseExpr->getSourceRange();
  3531. return ExprError();
  3532. }
  3533. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3534. BaseExpr = LHSExp; // vectors: V[123]
  3535. IndexExpr = RHSExp;
  3536. VK = LHSExp->getValueKind();
  3537. if (VK != VK_RValue)
  3538. OK = OK_VectorComponent;
  3539. // FIXME: need to deal with const...
  3540. ResultType = VTy->getElementType();
  3541. } else if (LHSTy->isArrayType()) {
  3542. // If we see an array that wasn't promoted by
  3543. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3544. // wasn't promoted because of the C90 rule that doesn't
  3545. // allow promoting non-lvalue arrays. Warn, then
  3546. // force the promotion here.
  3547. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3548. LHSExp->getSourceRange();
  3549. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3550. CK_ArrayToPointerDecay).get();
  3551. LHSTy = LHSExp->getType();
  3552. BaseExpr = LHSExp;
  3553. IndexExpr = RHSExp;
  3554. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3555. } else if (RHSTy->isArrayType()) {
  3556. // Same as previous, except for 123[f().a] case
  3557. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3558. RHSExp->getSourceRange();
  3559. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3560. CK_ArrayToPointerDecay).get();
  3561. RHSTy = RHSExp->getType();
  3562. BaseExpr = RHSExp;
  3563. IndexExpr = LHSExp;
  3564. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3565. } else {
  3566. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  3567. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3568. }
  3569. // C99 6.5.2.1p1
  3570. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3571. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3572. << IndexExpr->getSourceRange());
  3573. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3574. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3575. && !IndexExpr->isTypeDependent())
  3576. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3577. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3578. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3579. // type. Note that Functions are not objects, and that (in C99 parlance)
  3580. // incomplete types are not object types.
  3581. if (ResultType->isFunctionType()) {
  3582. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3583. << ResultType << BaseExpr->getSourceRange();
  3584. return ExprError();
  3585. }
  3586. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3587. // GNU extension: subscripting on pointer to void
  3588. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3589. << BaseExpr->getSourceRange();
  3590. // C forbids expressions of unqualified void type from being l-values.
  3591. // See IsCForbiddenLValueType.
  3592. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3593. } else if (!ResultType->isDependentType() &&
  3594. RequireCompleteType(LLoc, ResultType,
  3595. diag::err_subscript_incomplete_type, BaseExpr))
  3596. return ExprError();
  3597. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3598. !ResultType.isCForbiddenLValueType());
  3599. return new (Context)
  3600. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3601. }
  3602. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3603. FunctionDecl *FD,
  3604. ParmVarDecl *Param) {
  3605. if (Param->hasUnparsedDefaultArg()) {
  3606. Diag(CallLoc,
  3607. diag::err_use_of_default_argument_to_function_declared_later) <<
  3608. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3609. Diag(UnparsedDefaultArgLocs[Param],
  3610. diag::note_default_argument_declared_here);
  3611. return ExprError();
  3612. }
  3613. if (Param->hasUninstantiatedDefaultArg()) {
  3614. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3615. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3616. Param);
  3617. // Instantiate the expression.
  3618. MultiLevelTemplateArgumentList MutiLevelArgList
  3619. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3620. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3621. MutiLevelArgList.getInnermost());
  3622. if (Inst.isInvalid())
  3623. return ExprError();
  3624. ExprResult Result;
  3625. {
  3626. // C++ [dcl.fct.default]p5:
  3627. // The names in the [default argument] expression are bound, and
  3628. // the semantic constraints are checked, at the point where the
  3629. // default argument expression appears.
  3630. ContextRAII SavedContext(*this, FD);
  3631. LocalInstantiationScope Local(*this);
  3632. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3633. }
  3634. if (Result.isInvalid())
  3635. return ExprError();
  3636. // Check the expression as an initializer for the parameter.
  3637. InitializedEntity Entity
  3638. = InitializedEntity::InitializeParameter(Context, Param);
  3639. InitializationKind Kind
  3640. = InitializationKind::CreateCopy(Param->getLocation(),
  3641. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3642. Expr *ResultE = Result.getAs<Expr>();
  3643. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3644. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3645. if (Result.isInvalid())
  3646. return ExprError();
  3647. Expr *Arg = Result.getAs<Expr>();
  3648. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3649. // Build the default argument expression.
  3650. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3651. }
  3652. // If the default expression creates temporaries, we need to
  3653. // push them to the current stack of expression temporaries so they'll
  3654. // be properly destroyed.
  3655. // FIXME: We should really be rebuilding the default argument with new
  3656. // bound temporaries; see the comment in PR5810.
  3657. // We don't need to do that with block decls, though, because
  3658. // blocks in default argument expression can never capture anything.
  3659. if (isa<ExprWithCleanups>(Param->getInit())) {
  3660. // Set the "needs cleanups" bit regardless of whether there are
  3661. // any explicit objects.
  3662. ExprNeedsCleanups = true;
  3663. // Append all the objects to the cleanup list. Right now, this
  3664. // should always be a no-op, because blocks in default argument
  3665. // expressions should never be able to capture anything.
  3666. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3667. "default argument expression has capturing blocks?");
  3668. }
  3669. // We already type-checked the argument, so we know it works.
  3670. // Just mark all of the declarations in this potentially-evaluated expression
  3671. // as being "referenced".
  3672. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3673. /*SkipLocalVariables=*/true);
  3674. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3675. }
  3676. Sema::VariadicCallType
  3677. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3678. Expr *Fn) {
  3679. if (Proto && Proto->isVariadic()) {
  3680. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3681. return VariadicConstructor;
  3682. else if (Fn && Fn->getType()->isBlockPointerType())
  3683. return VariadicBlock;
  3684. else if (FDecl) {
  3685. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3686. if (Method->isInstance())
  3687. return VariadicMethod;
  3688. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3689. return VariadicMethod;
  3690. return VariadicFunction;
  3691. }
  3692. return VariadicDoesNotApply;
  3693. }
  3694. namespace {
  3695. class FunctionCallCCC : public FunctionCallFilterCCC {
  3696. public:
  3697. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3698. unsigned NumArgs, MemberExpr *ME)
  3699. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3700. FunctionName(FuncName) {}
  3701. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3702. if (!candidate.getCorrectionSpecifier() ||
  3703. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3704. return false;
  3705. }
  3706. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3707. }
  3708. private:
  3709. const IdentifierInfo *const FunctionName;
  3710. };
  3711. }
  3712. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3713. FunctionDecl *FDecl,
  3714. ArrayRef<Expr *> Args) {
  3715. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3716. DeclarationName FuncName = FDecl->getDeclName();
  3717. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3718. if (TypoCorrection Corrected = S.CorrectTypo(
  3719. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3720. S.getScopeForContext(S.CurContext), nullptr,
  3721. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3722. Args.size(), ME),
  3723. Sema::CTK_ErrorRecovery)) {
  3724. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3725. if (Corrected.isOverloaded()) {
  3726. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3727. OverloadCandidateSet::iterator Best;
  3728. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3729. CDEnd = Corrected.end();
  3730. CD != CDEnd; ++CD) {
  3731. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3732. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3733. OCS);
  3734. }
  3735. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3736. case OR_Success:
  3737. ND = Best->Function;
  3738. Corrected.setCorrectionDecl(ND);
  3739. break;
  3740. default:
  3741. break;
  3742. }
  3743. }
  3744. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3745. return Corrected;
  3746. }
  3747. }
  3748. }
  3749. return TypoCorrection();
  3750. }
  3751. /// ConvertArgumentsForCall - Converts the arguments specified in
  3752. /// Args/NumArgs to the parameter types of the function FDecl with
  3753. /// function prototype Proto. Call is the call expression itself, and
  3754. /// Fn is the function expression. For a C++ member function, this
  3755. /// routine does not attempt to convert the object argument. Returns
  3756. /// true if the call is ill-formed.
  3757. bool
  3758. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3759. FunctionDecl *FDecl,
  3760. const FunctionProtoType *Proto,
  3761. ArrayRef<Expr *> Args,
  3762. SourceLocation RParenLoc,
  3763. bool IsExecConfig) {
  3764. // Bail out early if calling a builtin with custom typechecking.
  3765. if (FDecl)
  3766. if (unsigned ID = FDecl->getBuiltinID())
  3767. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3768. return false;
  3769. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3770. // assignment, to the types of the corresponding parameter, ...
  3771. unsigned NumParams = Proto->getNumParams();
  3772. bool Invalid = false;
  3773. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3774. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3775. ? 1 /* block */
  3776. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3777. : 0 /* function */);
  3778. // If too few arguments are available (and we don't have default
  3779. // arguments for the remaining parameters), don't make the call.
  3780. if (Args.size() < NumParams) {
  3781. if (Args.size() < MinArgs) {
  3782. TypoCorrection TC;
  3783. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3784. unsigned diag_id =
  3785. MinArgs == NumParams && !Proto->isVariadic()
  3786. ? diag::err_typecheck_call_too_few_args_suggest
  3787. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3788. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3789. << static_cast<unsigned>(Args.size())
  3790. << TC.getCorrectionRange());
  3791. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3792. Diag(RParenLoc,
  3793. MinArgs == NumParams && !Proto->isVariadic()
  3794. ? diag::err_typecheck_call_too_few_args_one
  3795. : diag::err_typecheck_call_too_few_args_at_least_one)
  3796. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3797. else
  3798. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3799. ? diag::err_typecheck_call_too_few_args
  3800. : diag::err_typecheck_call_too_few_args_at_least)
  3801. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3802. << Fn->getSourceRange();
  3803. // Emit the location of the prototype.
  3804. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3805. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3806. << FDecl;
  3807. return true;
  3808. }
  3809. Call->setNumArgs(Context, NumParams);
  3810. }
  3811. // If too many are passed and not variadic, error on the extras and drop
  3812. // them.
  3813. if (Args.size() > NumParams) {
  3814. if (!Proto->isVariadic()) {
  3815. TypoCorrection TC;
  3816. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3817. unsigned diag_id =
  3818. MinArgs == NumParams && !Proto->isVariadic()
  3819. ? diag::err_typecheck_call_too_many_args_suggest
  3820. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  3821. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  3822. << static_cast<unsigned>(Args.size())
  3823. << TC.getCorrectionRange());
  3824. } else if (NumParams == 1 && FDecl &&
  3825. FDecl->getParamDecl(0)->getDeclName())
  3826. Diag(Args[NumParams]->getLocStart(),
  3827. MinArgs == NumParams
  3828. ? diag::err_typecheck_call_too_many_args_one
  3829. : diag::err_typecheck_call_too_many_args_at_most_one)
  3830. << FnKind << FDecl->getParamDecl(0)
  3831. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  3832. << SourceRange(Args[NumParams]->getLocStart(),
  3833. Args.back()->getLocEnd());
  3834. else
  3835. Diag(Args[NumParams]->getLocStart(),
  3836. MinArgs == NumParams
  3837. ? diag::err_typecheck_call_too_many_args
  3838. : diag::err_typecheck_call_too_many_args_at_most)
  3839. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  3840. << Fn->getSourceRange()
  3841. << SourceRange(Args[NumParams]->getLocStart(),
  3842. Args.back()->getLocEnd());
  3843. // Emit the location of the prototype.
  3844. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3845. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3846. << FDecl;
  3847. // This deletes the extra arguments.
  3848. Call->setNumArgs(Context, NumParams);
  3849. return true;
  3850. }
  3851. }
  3852. SmallVector<Expr *, 8> AllArgs;
  3853. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  3854. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  3855. Proto, 0, Args, AllArgs, CallType);
  3856. if (Invalid)
  3857. return true;
  3858. unsigned TotalNumArgs = AllArgs.size();
  3859. for (unsigned i = 0; i < TotalNumArgs; ++i)
  3860. Call->setArg(i, AllArgs[i]);
  3861. return false;
  3862. }
  3863. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  3864. const FunctionProtoType *Proto,
  3865. unsigned FirstParam, ArrayRef<Expr *> Args,
  3866. SmallVectorImpl<Expr *> &AllArgs,
  3867. VariadicCallType CallType, bool AllowExplicit,
  3868. bool IsListInitialization) {
  3869. unsigned NumParams = Proto->getNumParams();
  3870. bool Invalid = false;
  3871. unsigned ArgIx = 0;
  3872. // Continue to check argument types (even if we have too few/many args).
  3873. for (unsigned i = FirstParam; i < NumParams; i++) {
  3874. QualType ProtoArgType = Proto->getParamType(i);
  3875. Expr *Arg;
  3876. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  3877. if (ArgIx < Args.size()) {
  3878. Arg = Args[ArgIx++];
  3879. if (RequireCompleteType(Arg->getLocStart(),
  3880. ProtoArgType,
  3881. diag::err_call_incomplete_argument, Arg))
  3882. return true;
  3883. // Strip the unbridged-cast placeholder expression off, if applicable.
  3884. bool CFAudited = false;
  3885. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  3886. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  3887. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  3888. Arg = stripARCUnbridgedCast(Arg);
  3889. else if (getLangOpts().ObjCAutoRefCount &&
  3890. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  3891. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  3892. CFAudited = true;
  3893. InitializedEntity Entity =
  3894. Param ? InitializedEntity::InitializeParameter(Context, Param,
  3895. ProtoArgType)
  3896. : InitializedEntity::InitializeParameter(
  3897. Context, ProtoArgType, Proto->isParamConsumed(i));
  3898. // Remember that parameter belongs to a CF audited API.
  3899. if (CFAudited)
  3900. Entity.setParameterCFAudited();
  3901. ExprResult ArgE = PerformCopyInitialization(
  3902. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  3903. if (ArgE.isInvalid())
  3904. return true;
  3905. Arg = ArgE.getAs<Expr>();
  3906. } else {
  3907. assert(Param && "can't use default arguments without a known callee");
  3908. ExprResult ArgExpr =
  3909. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  3910. if (ArgExpr.isInvalid())
  3911. return true;
  3912. Arg = ArgExpr.getAs<Expr>();
  3913. }
  3914. // Check for array bounds violations for each argument to the call. This
  3915. // check only triggers warnings when the argument isn't a more complex Expr
  3916. // with its own checking, such as a BinaryOperator.
  3917. CheckArrayAccess(Arg);
  3918. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  3919. CheckStaticArrayArgument(CallLoc, Param, Arg);
  3920. AllArgs.push_back(Arg);
  3921. }
  3922. // If this is a variadic call, handle args passed through "...".
  3923. if (CallType != VariadicDoesNotApply) {
  3924. // Assume that extern "C" functions with variadic arguments that
  3925. // return __unknown_anytype aren't *really* variadic.
  3926. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  3927. FDecl->isExternC()) {
  3928. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  3929. QualType paramType; // ignored
  3930. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  3931. Invalid |= arg.isInvalid();
  3932. AllArgs.push_back(arg.get());
  3933. }
  3934. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  3935. } else {
  3936. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  3937. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  3938. FDecl);
  3939. Invalid |= Arg.isInvalid();
  3940. AllArgs.push_back(Arg.get());
  3941. }
  3942. }
  3943. // Check for array bounds violations.
  3944. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  3945. CheckArrayAccess(Args[i]);
  3946. }
  3947. return Invalid;
  3948. }
  3949. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  3950. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  3951. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  3952. TL = DTL.getOriginalLoc();
  3953. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  3954. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  3955. << ATL.getLocalSourceRange();
  3956. }
  3957. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  3958. /// array parameter, check that it is non-null, and that if it is formed by
  3959. /// array-to-pointer decay, the underlying array is sufficiently large.
  3960. ///
  3961. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  3962. /// array type derivation, then for each call to the function, the value of the
  3963. /// corresponding actual argument shall provide access to the first element of
  3964. /// an array with at least as many elements as specified by the size expression.
  3965. void
  3966. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  3967. ParmVarDecl *Param,
  3968. const Expr *ArgExpr) {
  3969. // Static array parameters are not supported in C++.
  3970. if (!Param || getLangOpts().CPlusPlus)
  3971. return;
  3972. QualType OrigTy = Param->getOriginalType();
  3973. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  3974. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  3975. return;
  3976. if (ArgExpr->isNullPointerConstant(Context,
  3977. Expr::NPC_NeverValueDependent)) {
  3978. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  3979. DiagnoseCalleeStaticArrayParam(*this, Param);
  3980. return;
  3981. }
  3982. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  3983. if (!CAT)
  3984. return;
  3985. const ConstantArrayType *ArgCAT =
  3986. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  3987. if (!ArgCAT)
  3988. return;
  3989. if (ArgCAT->getSize().ult(CAT->getSize())) {
  3990. Diag(CallLoc, diag::warn_static_array_too_small)
  3991. << ArgExpr->getSourceRange()
  3992. << (unsigned) ArgCAT->getSize().getZExtValue()
  3993. << (unsigned) CAT->getSize().getZExtValue();
  3994. DiagnoseCalleeStaticArrayParam(*this, Param);
  3995. }
  3996. }
  3997. /// Given a function expression of unknown-any type, try to rebuild it
  3998. /// to have a function type.
  3999. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4000. /// Is the given type a placeholder that we need to lower out
  4001. /// immediately during argument processing?
  4002. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4003. // Placeholders are never sugared.
  4004. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4005. if (!placeholder) return false;
  4006. switch (placeholder->getKind()) {
  4007. // Ignore all the non-placeholder types.
  4008. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4009. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4010. #include "clang/AST/BuiltinTypes.def"
  4011. return false;
  4012. // We cannot lower out overload sets; they might validly be resolved
  4013. // by the call machinery.
  4014. case BuiltinType::Overload:
  4015. return false;
  4016. // Unbridged casts in ARC can be handled in some call positions and
  4017. // should be left in place.
  4018. case BuiltinType::ARCUnbridgedCast:
  4019. return false;
  4020. // Pseudo-objects should be converted as soon as possible.
  4021. case BuiltinType::PseudoObject:
  4022. return true;
  4023. // The debugger mode could theoretically but currently does not try
  4024. // to resolve unknown-typed arguments based on known parameter types.
  4025. case BuiltinType::UnknownAny:
  4026. return true;
  4027. // These are always invalid as call arguments and should be reported.
  4028. case BuiltinType::BoundMember:
  4029. case BuiltinType::BuiltinFn:
  4030. return true;
  4031. }
  4032. llvm_unreachable("bad builtin type kind");
  4033. }
  4034. /// Check an argument list for placeholders that we won't try to
  4035. /// handle later.
  4036. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4037. // Apply this processing to all the arguments at once instead of
  4038. // dying at the first failure.
  4039. bool hasInvalid = false;
  4040. for (size_t i = 0, e = args.size(); i != e; i++) {
  4041. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4042. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4043. if (result.isInvalid()) hasInvalid = true;
  4044. else args[i] = result.get();
  4045. } else if (hasInvalid) {
  4046. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4047. }
  4048. }
  4049. return hasInvalid;
  4050. }
  4051. /// If a builtin function has a pointer argument with no explicit address
  4052. /// space, than it should be able to accept a pointer to any address
  4053. /// space as input. In order to do this, we need to replace the
  4054. /// standard builtin declaration with one that uses the same address space
  4055. /// as the call.
  4056. ///
  4057. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4058. /// it does not contain any pointer arguments without
  4059. /// an address space qualifer. Otherwise the rewritten
  4060. /// FunctionDecl is returned.
  4061. /// TODO: Handle pointer return types.
  4062. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4063. const FunctionDecl *FDecl,
  4064. MultiExprArg ArgExprs) {
  4065. QualType DeclType = FDecl->getType();
  4066. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4067. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4068. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4069. return nullptr;
  4070. bool NeedsNewDecl = false;
  4071. unsigned i = 0;
  4072. SmallVector<QualType, 8> OverloadParams;
  4073. for (QualType ParamType : FT->param_types()) {
  4074. // Convert array arguments to pointer to simplify type lookup.
  4075. Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
  4076. QualType ArgType = Arg->getType();
  4077. if (!ParamType->isPointerType() ||
  4078. ParamType.getQualifiers().hasAddressSpace() ||
  4079. !ArgType->isPointerType() ||
  4080. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4081. OverloadParams.push_back(ParamType);
  4082. continue;
  4083. }
  4084. NeedsNewDecl = true;
  4085. unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
  4086. QualType PointeeType = ParamType->getPointeeType();
  4087. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4088. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4089. }
  4090. if (!NeedsNewDecl)
  4091. return nullptr;
  4092. FunctionProtoType::ExtProtoInfo EPI;
  4093. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4094. OverloadParams, EPI);
  4095. DeclContext *Parent = Context.getTranslationUnitDecl();
  4096. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4097. FDecl->getLocation(),
  4098. FDecl->getLocation(),
  4099. FDecl->getIdentifier(),
  4100. OverloadTy,
  4101. /*TInfo=*/nullptr,
  4102. SC_Extern, false,
  4103. /*hasPrototype=*/true);
  4104. SmallVector<ParmVarDecl*, 16> Params;
  4105. FT = cast<FunctionProtoType>(OverloadTy);
  4106. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4107. QualType ParamType = FT->getParamType(i);
  4108. ParmVarDecl *Parm =
  4109. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4110. SourceLocation(), nullptr, ParamType,
  4111. /*TInfo=*/nullptr, SC_None, nullptr);
  4112. Parm->setScopeInfo(0, i);
  4113. Params.push_back(Parm);
  4114. }
  4115. OverloadDecl->setParams(Params);
  4116. return OverloadDecl;
  4117. }
  4118. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4119. /// This provides the location of the left/right parens and a list of comma
  4120. /// locations.
  4121. ExprResult
  4122. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  4123. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4124. Expr *ExecConfig, bool IsExecConfig) {
  4125. // Since this might be a postfix expression, get rid of ParenListExprs.
  4126. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  4127. if (Result.isInvalid()) return ExprError();
  4128. Fn = Result.get();
  4129. if (checkArgsForPlaceholders(*this, ArgExprs))
  4130. return ExprError();
  4131. if (getLangOpts().CPlusPlus) {
  4132. // If this is a pseudo-destructor expression, build the call immediately.
  4133. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4134. if (!ArgExprs.empty()) {
  4135. // Pseudo-destructor calls should not have any arguments.
  4136. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4137. << FixItHint::CreateRemoval(
  4138. SourceRange(ArgExprs[0]->getLocStart(),
  4139. ArgExprs.back()->getLocEnd()));
  4140. }
  4141. return new (Context)
  4142. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4143. }
  4144. if (Fn->getType() == Context.PseudoObjectTy) {
  4145. ExprResult result = CheckPlaceholderExpr(Fn);
  4146. if (result.isInvalid()) return ExprError();
  4147. Fn = result.get();
  4148. }
  4149. // Determine whether this is a dependent call inside a C++ template,
  4150. // in which case we won't do any semantic analysis now.
  4151. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4152. // Fn.
  4153. bool Dependent = false;
  4154. if (Fn->isTypeDependent())
  4155. Dependent = true;
  4156. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4157. Dependent = true;
  4158. if (Dependent) {
  4159. if (ExecConfig) {
  4160. return new (Context) CUDAKernelCallExpr(
  4161. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4162. Context.DependentTy, VK_RValue, RParenLoc);
  4163. } else {
  4164. return new (Context) CallExpr(
  4165. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4166. }
  4167. }
  4168. // Determine whether this is a call to an object (C++ [over.call.object]).
  4169. if (Fn->getType()->isRecordType())
  4170. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4171. RParenLoc);
  4172. if (Fn->getType() == Context.UnknownAnyTy) {
  4173. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4174. if (result.isInvalid()) return ExprError();
  4175. Fn = result.get();
  4176. }
  4177. if (Fn->getType() == Context.BoundMemberTy) {
  4178. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4179. }
  4180. }
  4181. // Check for overloaded calls. This can happen even in C due to extensions.
  4182. if (Fn->getType() == Context.OverloadTy) {
  4183. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4184. // We aren't supposed to apply this logic for if there's an '&' involved.
  4185. if (!find.HasFormOfMemberPointer) {
  4186. OverloadExpr *ovl = find.Expression;
  4187. if (isa<UnresolvedLookupExpr>(ovl)) {
  4188. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4189. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4190. RParenLoc, ExecConfig);
  4191. } else {
  4192. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4193. RParenLoc);
  4194. }
  4195. }
  4196. }
  4197. // If we're directly calling a function, get the appropriate declaration.
  4198. if (Fn->getType() == Context.UnknownAnyTy) {
  4199. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4200. if (result.isInvalid()) return ExprError();
  4201. Fn = result.get();
  4202. }
  4203. Expr *NakedFn = Fn->IgnoreParens();
  4204. NamedDecl *NDecl = nullptr;
  4205. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4206. if (UnOp->getOpcode() == UO_AddrOf)
  4207. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4208. if (isa<DeclRefExpr>(NakedFn)) {
  4209. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4210. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4211. if (FDecl && FDecl->getBuiltinID()) {
  4212. // Rewrite the function decl for this builtin by replacing paramaters
  4213. // with no explicit address space with the address space of the arguments
  4214. // in ArgExprs.
  4215. if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4216. NDecl = FDecl;
  4217. Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
  4218. SourceLocation(), FDecl, false,
  4219. SourceLocation(), FDecl->getType(),
  4220. Fn->getValueKind(), FDecl);
  4221. }
  4222. }
  4223. } else if (isa<MemberExpr>(NakedFn))
  4224. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4225. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4226. if (FD->hasAttr<EnableIfAttr>()) {
  4227. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4228. Diag(Fn->getLocStart(),
  4229. isa<CXXMethodDecl>(FD) ?
  4230. diag::err_ovl_no_viable_member_function_in_call :
  4231. diag::err_ovl_no_viable_function_in_call)
  4232. << FD << FD->getSourceRange();
  4233. Diag(FD->getLocation(),
  4234. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4235. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4236. }
  4237. }
  4238. }
  4239. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4240. ExecConfig, IsExecConfig);
  4241. }
  4242. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4243. ///
  4244. /// __builtin_astype( value, dst type )
  4245. ///
  4246. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4247. SourceLocation BuiltinLoc,
  4248. SourceLocation RParenLoc) {
  4249. ExprValueKind VK = VK_RValue;
  4250. ExprObjectKind OK = OK_Ordinary;
  4251. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4252. QualType SrcTy = E->getType();
  4253. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4254. return ExprError(Diag(BuiltinLoc,
  4255. diag::err_invalid_astype_of_different_size)
  4256. << DstTy
  4257. << SrcTy
  4258. << E->getSourceRange());
  4259. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4260. }
  4261. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4262. /// provided arguments.
  4263. ///
  4264. /// __builtin_convertvector( value, dst type )
  4265. ///
  4266. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4267. SourceLocation BuiltinLoc,
  4268. SourceLocation RParenLoc) {
  4269. TypeSourceInfo *TInfo;
  4270. GetTypeFromParser(ParsedDestTy, &TInfo);
  4271. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4272. }
  4273. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4274. /// i.e. an expression not of \p OverloadTy. The expression should
  4275. /// unary-convert to an expression of function-pointer or
  4276. /// block-pointer type.
  4277. ///
  4278. /// \param NDecl the declaration being called, if available
  4279. ExprResult
  4280. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4281. SourceLocation LParenLoc,
  4282. ArrayRef<Expr *> Args,
  4283. SourceLocation RParenLoc,
  4284. Expr *Config, bool IsExecConfig) {
  4285. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4286. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4287. // Promote the function operand.
  4288. // We special-case function promotion here because we only allow promoting
  4289. // builtin functions to function pointers in the callee of a call.
  4290. ExprResult Result;
  4291. if (BuiltinID &&
  4292. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4293. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4294. CK_BuiltinFnToFnPtr).get();
  4295. } else {
  4296. Result = CallExprUnaryConversions(Fn);
  4297. }
  4298. if (Result.isInvalid())
  4299. return ExprError();
  4300. Fn = Result.get();
  4301. // Make the call expr early, before semantic checks. This guarantees cleanup
  4302. // of arguments and function on error.
  4303. CallExpr *TheCall;
  4304. if (Config)
  4305. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4306. cast<CallExpr>(Config), Args,
  4307. Context.BoolTy, VK_RValue,
  4308. RParenLoc);
  4309. else
  4310. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4311. VK_RValue, RParenLoc);
  4312. if (!getLangOpts().CPlusPlus) {
  4313. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4314. // function calls as their argument checking don't necessarily handle
  4315. // dependent types properly, so make sure any TypoExprs have been
  4316. // dealt with.
  4317. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4318. if (!Result.isUsable()) return ExprError();
  4319. TheCall = dyn_cast<CallExpr>(Result.get());
  4320. if (!TheCall) return Result;
  4321. }
  4322. // Bail out early if calling a builtin with custom typechecking.
  4323. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4324. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4325. retry:
  4326. const FunctionType *FuncT;
  4327. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4328. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4329. // have type pointer to function".
  4330. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4331. if (!FuncT)
  4332. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4333. << Fn->getType() << Fn->getSourceRange());
  4334. } else if (const BlockPointerType *BPT =
  4335. Fn->getType()->getAs<BlockPointerType>()) {
  4336. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4337. } else {
  4338. // Handle calls to expressions of unknown-any type.
  4339. if (Fn->getType() == Context.UnknownAnyTy) {
  4340. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4341. if (rewrite.isInvalid()) return ExprError();
  4342. Fn = rewrite.get();
  4343. TheCall->setCallee(Fn);
  4344. goto retry;
  4345. }
  4346. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4347. << Fn->getType() << Fn->getSourceRange());
  4348. }
  4349. if (getLangOpts().CUDA) {
  4350. if (Config) {
  4351. // CUDA: Kernel calls must be to global functions
  4352. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4353. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4354. << FDecl->getName() << Fn->getSourceRange());
  4355. // CUDA: Kernel function must have 'void' return type
  4356. if (!FuncT->getReturnType()->isVoidType())
  4357. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4358. << Fn->getType() << Fn->getSourceRange());
  4359. } else {
  4360. // CUDA: Calls to global functions must be configured
  4361. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4362. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4363. << FDecl->getName() << Fn->getSourceRange());
  4364. }
  4365. }
  4366. // Check for a valid return type
  4367. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4368. FDecl))
  4369. return ExprError();
  4370. // We know the result type of the call, set it.
  4371. TheCall->setType(FuncT->getCallResultType(Context));
  4372. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4373. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4374. if (Proto) {
  4375. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4376. IsExecConfig))
  4377. return ExprError();
  4378. } else {
  4379. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4380. if (FDecl) {
  4381. // Check if we have too few/too many template arguments, based
  4382. // on our knowledge of the function definition.
  4383. const FunctionDecl *Def = nullptr;
  4384. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4385. Proto = Def->getType()->getAs<FunctionProtoType>();
  4386. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4387. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4388. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4389. }
  4390. // If the function we're calling isn't a function prototype, but we have
  4391. // a function prototype from a prior declaratiom, use that prototype.
  4392. if (!FDecl->hasPrototype())
  4393. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4394. }
  4395. // Promote the arguments (C99 6.5.2.2p6).
  4396. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4397. Expr *Arg = Args[i];
  4398. if (Proto && i < Proto->getNumParams()) {
  4399. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4400. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4401. ExprResult ArgE =
  4402. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4403. if (ArgE.isInvalid())
  4404. return true;
  4405. Arg = ArgE.getAs<Expr>();
  4406. } else {
  4407. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4408. if (ArgE.isInvalid())
  4409. return true;
  4410. Arg = ArgE.getAs<Expr>();
  4411. }
  4412. if (RequireCompleteType(Arg->getLocStart(),
  4413. Arg->getType(),
  4414. diag::err_call_incomplete_argument, Arg))
  4415. return ExprError();
  4416. TheCall->setArg(i, Arg);
  4417. }
  4418. }
  4419. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4420. if (!Method->isStatic())
  4421. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4422. << Fn->getSourceRange());
  4423. // Check for sentinels
  4424. if (NDecl)
  4425. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4426. // Do special checking on direct calls to functions.
  4427. if (FDecl) {
  4428. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4429. return ExprError();
  4430. if (BuiltinID)
  4431. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4432. } else if (NDecl) {
  4433. if (CheckPointerCall(NDecl, TheCall, Proto))
  4434. return ExprError();
  4435. } else {
  4436. if (CheckOtherCall(TheCall, Proto))
  4437. return ExprError();
  4438. }
  4439. return MaybeBindToTemporary(TheCall);
  4440. }
  4441. ExprResult
  4442. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4443. SourceLocation RParenLoc, Expr *InitExpr) {
  4444. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4445. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  4446. TypeSourceInfo *TInfo;
  4447. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4448. if (!TInfo)
  4449. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4450. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4451. }
  4452. ExprResult
  4453. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4454. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4455. QualType literalType = TInfo->getType();
  4456. if (literalType->isArrayType()) {
  4457. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4458. diag::err_illegal_decl_array_incomplete_type,
  4459. SourceRange(LParenLoc,
  4460. LiteralExpr->getSourceRange().getEnd())))
  4461. return ExprError();
  4462. if (literalType->isVariableArrayType())
  4463. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4464. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4465. } else if (!literalType->isDependentType() &&
  4466. RequireCompleteType(LParenLoc, literalType,
  4467. diag::err_typecheck_decl_incomplete_type,
  4468. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4469. return ExprError();
  4470. InitializedEntity Entity
  4471. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4472. InitializationKind Kind
  4473. = InitializationKind::CreateCStyleCast(LParenLoc,
  4474. SourceRange(LParenLoc, RParenLoc),
  4475. /*InitList=*/true);
  4476. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4477. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4478. &literalType);
  4479. if (Result.isInvalid())
  4480. return ExprError();
  4481. LiteralExpr = Result.get();
  4482. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4483. if (isFileScope &&
  4484. !LiteralExpr->isTypeDependent() &&
  4485. !LiteralExpr->isValueDependent() &&
  4486. !literalType->isDependentType()) { // 6.5.2.5p3
  4487. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4488. return ExprError();
  4489. }
  4490. // In C, compound literals are l-values for some reason.
  4491. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4492. return MaybeBindToTemporary(
  4493. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4494. VK, LiteralExpr, isFileScope));
  4495. }
  4496. ExprResult
  4497. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4498. SourceLocation RBraceLoc) {
  4499. // Immediately handle non-overload placeholders. Overloads can be
  4500. // resolved contextually, but everything else here can't.
  4501. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4502. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4503. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4504. // Ignore failures; dropping the entire initializer list because
  4505. // of one failure would be terrible for indexing/etc.
  4506. if (result.isInvalid()) continue;
  4507. InitArgList[I] = result.get();
  4508. }
  4509. }
  4510. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4511. // CheckInitializer() - it requires knowledge of the object being intialized.
  4512. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4513. RBraceLoc);
  4514. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4515. return E;
  4516. }
  4517. /// Do an explicit extend of the given block pointer if we're in ARC.
  4518. void Sema::maybeExtendBlockObject(ExprResult &E) {
  4519. assert(E.get()->getType()->isBlockPointerType());
  4520. assert(E.get()->isRValue());
  4521. // Only do this in an r-value context.
  4522. if (!getLangOpts().ObjCAutoRefCount) return;
  4523. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  4524. CK_ARCExtendBlockObject, E.get(),
  4525. /*base path*/ nullptr, VK_RValue);
  4526. ExprNeedsCleanups = true;
  4527. }
  4528. /// Prepare a conversion of the given expression to an ObjC object
  4529. /// pointer type.
  4530. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4531. QualType type = E.get()->getType();
  4532. if (type->isObjCObjectPointerType()) {
  4533. return CK_BitCast;
  4534. } else if (type->isBlockPointerType()) {
  4535. maybeExtendBlockObject(E);
  4536. return CK_BlockPointerToObjCPointerCast;
  4537. } else {
  4538. assert(type->isPointerType());
  4539. return CK_CPointerToObjCPointerCast;
  4540. }
  4541. }
  4542. /// Prepares for a scalar cast, performing all the necessary stages
  4543. /// except the final cast and returning the kind required.
  4544. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4545. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4546. // Also, callers should have filtered out the invalid cases with
  4547. // pointers. Everything else should be possible.
  4548. QualType SrcTy = Src.get()->getType();
  4549. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4550. return CK_NoOp;
  4551. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4552. case Type::STK_MemberPointer:
  4553. llvm_unreachable("member pointer type in C");
  4554. case Type::STK_CPointer:
  4555. case Type::STK_BlockPointer:
  4556. case Type::STK_ObjCObjectPointer:
  4557. switch (DestTy->getScalarTypeKind()) {
  4558. case Type::STK_CPointer: {
  4559. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4560. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4561. if (SrcAS != DestAS)
  4562. return CK_AddressSpaceConversion;
  4563. return CK_BitCast;
  4564. }
  4565. case Type::STK_BlockPointer:
  4566. return (SrcKind == Type::STK_BlockPointer
  4567. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4568. case Type::STK_ObjCObjectPointer:
  4569. if (SrcKind == Type::STK_ObjCObjectPointer)
  4570. return CK_BitCast;
  4571. if (SrcKind == Type::STK_CPointer)
  4572. return CK_CPointerToObjCPointerCast;
  4573. maybeExtendBlockObject(Src);
  4574. return CK_BlockPointerToObjCPointerCast;
  4575. case Type::STK_Bool:
  4576. return CK_PointerToBoolean;
  4577. case Type::STK_Integral:
  4578. return CK_PointerToIntegral;
  4579. case Type::STK_Floating:
  4580. case Type::STK_FloatingComplex:
  4581. case Type::STK_IntegralComplex:
  4582. case Type::STK_MemberPointer:
  4583. llvm_unreachable("illegal cast from pointer");
  4584. }
  4585. llvm_unreachable("Should have returned before this");
  4586. case Type::STK_Bool: // casting from bool is like casting from an integer
  4587. case Type::STK_Integral:
  4588. switch (DestTy->getScalarTypeKind()) {
  4589. case Type::STK_CPointer:
  4590. case Type::STK_ObjCObjectPointer:
  4591. case Type::STK_BlockPointer:
  4592. if (Src.get()->isNullPointerConstant(Context,
  4593. Expr::NPC_ValueDependentIsNull))
  4594. return CK_NullToPointer;
  4595. return CK_IntegralToPointer;
  4596. case Type::STK_Bool:
  4597. return CK_IntegralToBoolean;
  4598. case Type::STK_Integral:
  4599. return CK_IntegralCast;
  4600. case Type::STK_Floating:
  4601. return CK_IntegralToFloating;
  4602. case Type::STK_IntegralComplex:
  4603. Src = ImpCastExprToType(Src.get(),
  4604. DestTy->castAs<ComplexType>()->getElementType(),
  4605. CK_IntegralCast);
  4606. return CK_IntegralRealToComplex;
  4607. case Type::STK_FloatingComplex:
  4608. Src = ImpCastExprToType(Src.get(),
  4609. DestTy->castAs<ComplexType>()->getElementType(),
  4610. CK_IntegralToFloating);
  4611. return CK_FloatingRealToComplex;
  4612. case Type::STK_MemberPointer:
  4613. llvm_unreachable("member pointer type in C");
  4614. }
  4615. llvm_unreachable("Should have returned before this");
  4616. case Type::STK_Floating:
  4617. switch (DestTy->getScalarTypeKind()) {
  4618. case Type::STK_Floating:
  4619. return CK_FloatingCast;
  4620. case Type::STK_Bool:
  4621. return CK_FloatingToBoolean;
  4622. case Type::STK_Integral:
  4623. return CK_FloatingToIntegral;
  4624. case Type::STK_FloatingComplex:
  4625. Src = ImpCastExprToType(Src.get(),
  4626. DestTy->castAs<ComplexType>()->getElementType(),
  4627. CK_FloatingCast);
  4628. return CK_FloatingRealToComplex;
  4629. case Type::STK_IntegralComplex:
  4630. Src = ImpCastExprToType(Src.get(),
  4631. DestTy->castAs<ComplexType>()->getElementType(),
  4632. CK_FloatingToIntegral);
  4633. return CK_IntegralRealToComplex;
  4634. case Type::STK_CPointer:
  4635. case Type::STK_ObjCObjectPointer:
  4636. case Type::STK_BlockPointer:
  4637. llvm_unreachable("valid float->pointer cast?");
  4638. case Type::STK_MemberPointer:
  4639. llvm_unreachable("member pointer type in C");
  4640. }
  4641. llvm_unreachable("Should have returned before this");
  4642. case Type::STK_FloatingComplex:
  4643. switch (DestTy->getScalarTypeKind()) {
  4644. case Type::STK_FloatingComplex:
  4645. return CK_FloatingComplexCast;
  4646. case Type::STK_IntegralComplex:
  4647. return CK_FloatingComplexToIntegralComplex;
  4648. case Type::STK_Floating: {
  4649. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4650. if (Context.hasSameType(ET, DestTy))
  4651. return CK_FloatingComplexToReal;
  4652. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4653. return CK_FloatingCast;
  4654. }
  4655. case Type::STK_Bool:
  4656. return CK_FloatingComplexToBoolean;
  4657. case Type::STK_Integral:
  4658. Src = ImpCastExprToType(Src.get(),
  4659. SrcTy->castAs<ComplexType>()->getElementType(),
  4660. CK_FloatingComplexToReal);
  4661. return CK_FloatingToIntegral;
  4662. case Type::STK_CPointer:
  4663. case Type::STK_ObjCObjectPointer:
  4664. case Type::STK_BlockPointer:
  4665. llvm_unreachable("valid complex float->pointer cast?");
  4666. case Type::STK_MemberPointer:
  4667. llvm_unreachable("member pointer type in C");
  4668. }
  4669. llvm_unreachable("Should have returned before this");
  4670. case Type::STK_IntegralComplex:
  4671. switch (DestTy->getScalarTypeKind()) {
  4672. case Type::STK_FloatingComplex:
  4673. return CK_IntegralComplexToFloatingComplex;
  4674. case Type::STK_IntegralComplex:
  4675. return CK_IntegralComplexCast;
  4676. case Type::STK_Integral: {
  4677. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4678. if (Context.hasSameType(ET, DestTy))
  4679. return CK_IntegralComplexToReal;
  4680. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4681. return CK_IntegralCast;
  4682. }
  4683. case Type::STK_Bool:
  4684. return CK_IntegralComplexToBoolean;
  4685. case Type::STK_Floating:
  4686. Src = ImpCastExprToType(Src.get(),
  4687. SrcTy->castAs<ComplexType>()->getElementType(),
  4688. CK_IntegralComplexToReal);
  4689. return CK_IntegralToFloating;
  4690. case Type::STK_CPointer:
  4691. case Type::STK_ObjCObjectPointer:
  4692. case Type::STK_BlockPointer:
  4693. llvm_unreachable("valid complex int->pointer cast?");
  4694. case Type::STK_MemberPointer:
  4695. llvm_unreachable("member pointer type in C");
  4696. }
  4697. llvm_unreachable("Should have returned before this");
  4698. }
  4699. llvm_unreachable("Unhandled scalar cast");
  4700. }
  4701. static bool breakDownVectorType(QualType type, uint64_t &len,
  4702. QualType &eltType) {
  4703. // Vectors are simple.
  4704. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4705. len = vecType->getNumElements();
  4706. eltType = vecType->getElementType();
  4707. assert(eltType->isScalarType());
  4708. return true;
  4709. }
  4710. // We allow lax conversion to and from non-vector types, but only if
  4711. // they're real types (i.e. non-complex, non-pointer scalar types).
  4712. if (!type->isRealType()) return false;
  4713. len = 1;
  4714. eltType = type;
  4715. return true;
  4716. }
  4717. /// Are the two types lax-compatible vector types? That is, given
  4718. /// that one of them is a vector, do they have equal storage sizes,
  4719. /// where the storage size is the number of elements times the element
  4720. /// size?
  4721. ///
  4722. /// This will also return false if either of the types is neither a
  4723. /// vector nor a real type.
  4724. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  4725. assert(destTy->isVectorType() || srcTy->isVectorType());
  4726. uint64_t srcLen, destLen;
  4727. QualType srcElt, destElt;
  4728. if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
  4729. if (!breakDownVectorType(destTy, destLen, destElt)) return false;
  4730. // ASTContext::getTypeSize will return the size rounded up to a
  4731. // power of 2, so instead of using that, we need to use the raw
  4732. // element size multiplied by the element count.
  4733. uint64_t srcEltSize = Context.getTypeSize(srcElt);
  4734. uint64_t destEltSize = Context.getTypeSize(destElt);
  4735. return (srcLen * srcEltSize == destLen * destEltSize);
  4736. }
  4737. /// Is this a legal conversion between two types, one of which is
  4738. /// known to be a vector type?
  4739. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4740. assert(destTy->isVectorType() || srcTy->isVectorType());
  4741. if (!Context.getLangOpts().LaxVectorConversions)
  4742. return false;
  4743. return areLaxCompatibleVectorTypes(srcTy, destTy);
  4744. }
  4745. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4746. CastKind &Kind) {
  4747. assert(VectorTy->isVectorType() && "Not a vector type!");
  4748. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  4749. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  4750. return Diag(R.getBegin(),
  4751. Ty->isVectorType() ?
  4752. diag::err_invalid_conversion_between_vectors :
  4753. diag::err_invalid_conversion_between_vector_and_integer)
  4754. << VectorTy << Ty << R;
  4755. } else
  4756. return Diag(R.getBegin(),
  4757. diag::err_invalid_conversion_between_vector_and_scalar)
  4758. << VectorTy << Ty << R;
  4759. Kind = CK_BitCast;
  4760. return false;
  4761. }
  4762. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4763. Expr *CastExpr, CastKind &Kind) {
  4764. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4765. QualType SrcTy = CastExpr->getType();
  4766. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4767. // an ExtVectorType.
  4768. // In OpenCL, casts between vectors of different types are not allowed.
  4769. // (See OpenCL 6.2).
  4770. if (SrcTy->isVectorType()) {
  4771. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
  4772. || (getLangOpts().OpenCL &&
  4773. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4774. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4775. << DestTy << SrcTy << R;
  4776. return ExprError();
  4777. }
  4778. Kind = CK_BitCast;
  4779. return CastExpr;
  4780. }
  4781. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4782. // conversion will take place first from scalar to elt type, and then
  4783. // splat from elt type to vector.
  4784. if (SrcTy->isPointerType())
  4785. return Diag(R.getBegin(),
  4786. diag::err_invalid_conversion_between_vector_and_scalar)
  4787. << DestTy << SrcTy << R;
  4788. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4789. ExprResult CastExprRes = CastExpr;
  4790. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4791. if (CastExprRes.isInvalid())
  4792. return ExprError();
  4793. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4794. Kind = CK_VectorSplat;
  4795. return CastExpr;
  4796. }
  4797. ExprResult
  4798. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4799. Declarator &D, ParsedType &Ty,
  4800. SourceLocation RParenLoc, Expr *CastExpr) {
  4801. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4802. "ActOnCastExpr(): missing type or expr");
  4803. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4804. if (D.isInvalidType())
  4805. return ExprError();
  4806. if (getLangOpts().CPlusPlus) {
  4807. // Check that there are no default arguments (C++ only).
  4808. CheckExtraCXXDefaultArguments(D);
  4809. } else {
  4810. // Make sure any TypoExprs have been dealt with.
  4811. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4812. if (!Res.isUsable())
  4813. return ExprError();
  4814. CastExpr = Res.get();
  4815. }
  4816. checkUnusedDeclAttributes(D);
  4817. QualType castType = castTInfo->getType();
  4818. Ty = CreateParsedType(castType, castTInfo);
  4819. bool isVectorLiteral = false;
  4820. // Check for an altivec or OpenCL literal,
  4821. // i.e. all the elements are integer constants.
  4822. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  4823. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  4824. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  4825. && castType->isVectorType() && (PE || PLE)) {
  4826. if (PLE && PLE->getNumExprs() == 0) {
  4827. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  4828. return ExprError();
  4829. }
  4830. if (PE || PLE->getNumExprs() == 1) {
  4831. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  4832. if (!E->getType()->isVectorType())
  4833. isVectorLiteral = true;
  4834. }
  4835. else
  4836. isVectorLiteral = true;
  4837. }
  4838. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  4839. // then handle it as such.
  4840. if (isVectorLiteral)
  4841. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  4842. // If the Expr being casted is a ParenListExpr, handle it specially.
  4843. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  4844. // sequence of BinOp comma operators.
  4845. if (isa<ParenListExpr>(CastExpr)) {
  4846. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  4847. if (Result.isInvalid()) return ExprError();
  4848. CastExpr = Result.get();
  4849. }
  4850. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  4851. !getSourceManager().isInSystemMacro(LParenLoc))
  4852. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  4853. CheckTollFreeBridgeCast(castType, CastExpr);
  4854. CheckObjCBridgeRelatedCast(castType, CastExpr);
  4855. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  4856. }
  4857. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  4858. SourceLocation RParenLoc, Expr *E,
  4859. TypeSourceInfo *TInfo) {
  4860. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  4861. "Expected paren or paren list expression");
  4862. Expr **exprs;
  4863. unsigned numExprs;
  4864. Expr *subExpr;
  4865. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  4866. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  4867. LiteralLParenLoc = PE->getLParenLoc();
  4868. LiteralRParenLoc = PE->getRParenLoc();
  4869. exprs = PE->getExprs();
  4870. numExprs = PE->getNumExprs();
  4871. } else { // isa<ParenExpr> by assertion at function entrance
  4872. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  4873. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  4874. subExpr = cast<ParenExpr>(E)->getSubExpr();
  4875. exprs = &subExpr;
  4876. numExprs = 1;
  4877. }
  4878. QualType Ty = TInfo->getType();
  4879. assert(Ty->isVectorType() && "Expected vector type");
  4880. SmallVector<Expr *, 8> initExprs;
  4881. const VectorType *VTy = Ty->getAs<VectorType>();
  4882. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  4883. // '(...)' form of vector initialization in AltiVec: the number of
  4884. // initializers must be one or must match the size of the vector.
  4885. // If a single value is specified in the initializer then it will be
  4886. // replicated to all the components of the vector
  4887. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  4888. // The number of initializers must be one or must match the size of the
  4889. // vector. If a single value is specified in the initializer then it will
  4890. // be replicated to all the components of the vector
  4891. if (numExprs == 1) {
  4892. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  4893. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  4894. if (Literal.isInvalid())
  4895. return ExprError();
  4896. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  4897. PrepareScalarCast(Literal, ElemTy));
  4898. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  4899. }
  4900. else if (numExprs < numElems) {
  4901. Diag(E->getExprLoc(),
  4902. diag::err_incorrect_number_of_vector_initializers);
  4903. return ExprError();
  4904. }
  4905. else
  4906. initExprs.append(exprs, exprs + numExprs);
  4907. }
  4908. else {
  4909. // For OpenCL, when the number of initializers is a single value,
  4910. // it will be replicated to all components of the vector.
  4911. if (getLangOpts().OpenCL &&
  4912. VTy->getVectorKind() == VectorType::GenericVector &&
  4913. numExprs == 1) {
  4914. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  4915. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  4916. if (Literal.isInvalid())
  4917. return ExprError();
  4918. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  4919. PrepareScalarCast(Literal, ElemTy));
  4920. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  4921. }
  4922. initExprs.append(exprs, exprs + numExprs);
  4923. }
  4924. // FIXME: This means that pretty-printing the final AST will produce curly
  4925. // braces instead of the original commas.
  4926. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  4927. initExprs, LiteralRParenLoc);
  4928. initE->setType(Ty);
  4929. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  4930. }
  4931. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  4932. /// the ParenListExpr into a sequence of comma binary operators.
  4933. ExprResult
  4934. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  4935. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  4936. if (!E)
  4937. return OrigExpr;
  4938. ExprResult Result(E->getExpr(0));
  4939. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  4940. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  4941. E->getExpr(i));
  4942. if (Result.isInvalid()) return ExprError();
  4943. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  4944. }
  4945. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  4946. SourceLocation R,
  4947. MultiExprArg Val) {
  4948. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  4949. return expr;
  4950. }
  4951. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  4952. /// constant and the other is not a pointer. Returns true if a diagnostic is
  4953. /// emitted.
  4954. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  4955. SourceLocation QuestionLoc) {
  4956. Expr *NullExpr = LHSExpr;
  4957. Expr *NonPointerExpr = RHSExpr;
  4958. Expr::NullPointerConstantKind NullKind =
  4959. NullExpr->isNullPointerConstant(Context,
  4960. Expr::NPC_ValueDependentIsNotNull);
  4961. if (NullKind == Expr::NPCK_NotNull) {
  4962. NullExpr = RHSExpr;
  4963. NonPointerExpr = LHSExpr;
  4964. NullKind =
  4965. NullExpr->isNullPointerConstant(Context,
  4966. Expr::NPC_ValueDependentIsNotNull);
  4967. }
  4968. if (NullKind == Expr::NPCK_NotNull)
  4969. return false;
  4970. if (NullKind == Expr::NPCK_ZeroExpression)
  4971. return false;
  4972. if (NullKind == Expr::NPCK_ZeroLiteral) {
  4973. // In this case, check to make sure that we got here from a "NULL"
  4974. // string in the source code.
  4975. NullExpr = NullExpr->IgnoreParenImpCasts();
  4976. SourceLocation loc = NullExpr->getExprLoc();
  4977. if (!findMacroSpelling(loc, "NULL"))
  4978. return false;
  4979. }
  4980. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  4981. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  4982. << NonPointerExpr->getType() << DiagType
  4983. << NonPointerExpr->getSourceRange();
  4984. return true;
  4985. }
  4986. /// \brief Return false if the condition expression is valid, true otherwise.
  4987. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  4988. QualType CondTy = Cond->getType();
  4989. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  4990. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  4991. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  4992. << CondTy << Cond->getSourceRange();
  4993. return true;
  4994. }
  4995. // C99 6.5.15p2
  4996. if (CondTy->isScalarType()) return false;
  4997. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  4998. << CondTy << Cond->getSourceRange();
  4999. return true;
  5000. }
  5001. /// \brief Handle when one or both operands are void type.
  5002. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5003. ExprResult &RHS) {
  5004. Expr *LHSExpr = LHS.get();
  5005. Expr *RHSExpr = RHS.get();
  5006. if (!LHSExpr->getType()->isVoidType())
  5007. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5008. << RHSExpr->getSourceRange();
  5009. if (!RHSExpr->getType()->isVoidType())
  5010. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5011. << LHSExpr->getSourceRange();
  5012. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5013. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5014. return S.Context.VoidTy;
  5015. }
  5016. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5017. /// true otherwise.
  5018. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5019. QualType PointerTy) {
  5020. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5021. !NullExpr.get()->isNullPointerConstant(S.Context,
  5022. Expr::NPC_ValueDependentIsNull))
  5023. return true;
  5024. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5025. return false;
  5026. }
  5027. /// \brief Checks compatibility between two pointers and return the resulting
  5028. /// type.
  5029. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5030. ExprResult &RHS,
  5031. SourceLocation Loc) {
  5032. QualType LHSTy = LHS.get()->getType();
  5033. QualType RHSTy = RHS.get()->getType();
  5034. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5035. // Two identical pointers types are always compatible.
  5036. return LHSTy;
  5037. }
  5038. QualType lhptee, rhptee;
  5039. // Get the pointee types.
  5040. bool IsBlockPointer = false;
  5041. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5042. lhptee = LHSBTy->getPointeeType();
  5043. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5044. IsBlockPointer = true;
  5045. } else {
  5046. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5047. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5048. }
  5049. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5050. // differently qualified versions of compatible types, the result type is
  5051. // a pointer to an appropriately qualified version of the composite
  5052. // type.
  5053. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5054. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5055. // be incompatible with address space 3: they may live on different devices or
  5056. // anything.
  5057. Qualifiers lhQual = lhptee.getQualifiers();
  5058. Qualifiers rhQual = rhptee.getQualifiers();
  5059. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5060. lhQual.removeCVRQualifiers();
  5061. rhQual.removeCVRQualifiers();
  5062. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5063. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5064. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5065. if (CompositeTy.isNull()) {
  5066. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5067. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5068. << RHS.get()->getSourceRange();
  5069. // In this situation, we assume void* type. No especially good
  5070. // reason, but this is what gcc does, and we do have to pick
  5071. // to get a consistent AST.
  5072. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  5073. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5074. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5075. return incompatTy;
  5076. }
  5077. // The pointer types are compatible.
  5078. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  5079. if (IsBlockPointer)
  5080. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5081. else
  5082. ResultTy = S.Context.getPointerType(ResultTy);
  5083. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  5084. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  5085. return ResultTy;
  5086. }
  5087. /// \brief Return the resulting type when the operands are both block pointers.
  5088. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5089. ExprResult &LHS,
  5090. ExprResult &RHS,
  5091. SourceLocation Loc) {
  5092. QualType LHSTy = LHS.get()->getType();
  5093. QualType RHSTy = RHS.get()->getType();
  5094. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5095. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5096. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5097. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5098. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5099. return destType;
  5100. }
  5101. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5102. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5103. << RHS.get()->getSourceRange();
  5104. return QualType();
  5105. }
  5106. // We have 2 block pointer types.
  5107. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5108. }
  5109. /// \brief Return the resulting type when the operands are both pointers.
  5110. static QualType
  5111. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5112. ExprResult &RHS,
  5113. SourceLocation Loc) {
  5114. // get the pointer types
  5115. QualType LHSTy = LHS.get()->getType();
  5116. QualType RHSTy = RHS.get()->getType();
  5117. // get the "pointed to" types
  5118. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5119. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5120. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5121. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5122. // Figure out necessary qualifiers (C99 6.5.15p6)
  5123. QualType destPointee
  5124. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5125. QualType destType = S.Context.getPointerType(destPointee);
  5126. // Add qualifiers if necessary.
  5127. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5128. // Promote to void*.
  5129. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5130. return destType;
  5131. }
  5132. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5133. QualType destPointee
  5134. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5135. QualType destType = S.Context.getPointerType(destPointee);
  5136. // Add qualifiers if necessary.
  5137. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5138. // Promote to void*.
  5139. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5140. return destType;
  5141. }
  5142. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5143. }
  5144. /// \brief Return false if the first expression is not an integer and the second
  5145. /// expression is not a pointer, true otherwise.
  5146. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5147. Expr* PointerExpr, SourceLocation Loc,
  5148. bool IsIntFirstExpr) {
  5149. if (!PointerExpr->getType()->isPointerType() ||
  5150. !Int.get()->getType()->isIntegerType())
  5151. return false;
  5152. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5153. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5154. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5155. << Expr1->getType() << Expr2->getType()
  5156. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5157. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5158. CK_IntegralToPointer);
  5159. return true;
  5160. }
  5161. /// \brief Simple conversion between integer and floating point types.
  5162. ///
  5163. /// Used when handling the OpenCL conditional operator where the
  5164. /// condition is a vector while the other operands are scalar.
  5165. ///
  5166. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5167. /// types are either integer or floating type. Between the two
  5168. /// operands, the type with the higher rank is defined as the "result
  5169. /// type". The other operand needs to be promoted to the same type. No
  5170. /// other type promotion is allowed. We cannot use
  5171. /// UsualArithmeticConversions() for this purpose, since it always
  5172. /// promotes promotable types.
  5173. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5174. ExprResult &RHS,
  5175. SourceLocation QuestionLoc) {
  5176. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5177. if (LHS.isInvalid())
  5178. return QualType();
  5179. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5180. if (RHS.isInvalid())
  5181. return QualType();
  5182. // For conversion purposes, we ignore any qualifiers.
  5183. // For example, "const float" and "float" are equivalent.
  5184. QualType LHSType =
  5185. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5186. QualType RHSType =
  5187. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5188. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5189. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5190. << LHSType << LHS.get()->getSourceRange();
  5191. return QualType();
  5192. }
  5193. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5194. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5195. << RHSType << RHS.get()->getSourceRange();
  5196. return QualType();
  5197. }
  5198. // If both types are identical, no conversion is needed.
  5199. if (LHSType == RHSType)
  5200. return LHSType;
  5201. // Now handle "real" floating types (i.e. float, double, long double).
  5202. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5203. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5204. /*IsCompAssign = */ false);
  5205. // Finally, we have two differing integer types.
  5206. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5207. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5208. }
  5209. /// \brief Convert scalar operands to a vector that matches the
  5210. /// condition in length.
  5211. ///
  5212. /// Used when handling the OpenCL conditional operator where the
  5213. /// condition is a vector while the other operands are scalar.
  5214. ///
  5215. /// We first compute the "result type" for the scalar operands
  5216. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5217. /// into a vector of that type where the length matches the condition
  5218. /// vector type. s6.11.6 requires that the element types of the result
  5219. /// and the condition must have the same number of bits.
  5220. static QualType
  5221. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5222. QualType CondTy, SourceLocation QuestionLoc) {
  5223. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5224. if (ResTy.isNull()) return QualType();
  5225. const VectorType *CV = CondTy->getAs<VectorType>();
  5226. assert(CV);
  5227. // Determine the vector result type
  5228. unsigned NumElements = CV->getNumElements();
  5229. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5230. // Ensure that all types have the same number of bits
  5231. if (S.Context.getTypeSize(CV->getElementType())
  5232. != S.Context.getTypeSize(ResTy)) {
  5233. // Since VectorTy is created internally, it does not pretty print
  5234. // with an OpenCL name. Instead, we just print a description.
  5235. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5236. SmallString<64> Str;
  5237. llvm::raw_svector_ostream OS(Str);
  5238. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5239. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5240. << CondTy << OS.str();
  5241. return QualType();
  5242. }
  5243. // Convert operands to the vector result type
  5244. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5245. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5246. return VectorTy;
  5247. }
  5248. /// \brief Return false if this is a valid OpenCL condition vector
  5249. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5250. SourceLocation QuestionLoc) {
  5251. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5252. // integral type.
  5253. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5254. assert(CondTy);
  5255. QualType EleTy = CondTy->getElementType();
  5256. if (EleTy->isIntegerType()) return false;
  5257. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5258. << Cond->getType() << Cond->getSourceRange();
  5259. return true;
  5260. }
  5261. /// \brief Return false if the vector condition type and the vector
  5262. /// result type are compatible.
  5263. ///
  5264. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5265. /// number of elements, and their element types have the same number
  5266. /// of bits.
  5267. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5268. SourceLocation QuestionLoc) {
  5269. const VectorType *CV = CondTy->getAs<VectorType>();
  5270. const VectorType *RV = VecResTy->getAs<VectorType>();
  5271. assert(CV && RV);
  5272. if (CV->getNumElements() != RV->getNumElements()) {
  5273. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5274. << CondTy << VecResTy;
  5275. return true;
  5276. }
  5277. QualType CVE = CV->getElementType();
  5278. QualType RVE = RV->getElementType();
  5279. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5280. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5281. << CondTy << VecResTy;
  5282. return true;
  5283. }
  5284. return false;
  5285. }
  5286. /// \brief Return the resulting type for the conditional operator in
  5287. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5288. /// s6.3.i) when the condition is a vector type.
  5289. static QualType
  5290. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5291. ExprResult &LHS, ExprResult &RHS,
  5292. SourceLocation QuestionLoc) {
  5293. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5294. if (Cond.isInvalid())
  5295. return QualType();
  5296. QualType CondTy = Cond.get()->getType();
  5297. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5298. return QualType();
  5299. // If either operand is a vector then find the vector type of the
  5300. // result as specified in OpenCL v1.1 s6.3.i.
  5301. if (LHS.get()->getType()->isVectorType() ||
  5302. RHS.get()->getType()->isVectorType()) {
  5303. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5304. /*isCompAssign*/false,
  5305. /*AllowBothBool*/true,
  5306. /*AllowBoolConversions*/false);
  5307. if (VecResTy.isNull()) return QualType();
  5308. // The result type must match the condition type as specified in
  5309. // OpenCL v1.1 s6.11.6.
  5310. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5311. return QualType();
  5312. return VecResTy;
  5313. }
  5314. // Both operands are scalar.
  5315. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5316. }
  5317. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5318. /// In that case, LHS = cond.
  5319. /// C99 6.5.15
  5320. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5321. ExprResult &RHS, ExprValueKind &VK,
  5322. ExprObjectKind &OK,
  5323. SourceLocation QuestionLoc) {
  5324. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5325. if (!LHSResult.isUsable()) return QualType();
  5326. LHS = LHSResult;
  5327. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5328. if (!RHSResult.isUsable()) return QualType();
  5329. RHS = RHSResult;
  5330. // C++ is sufficiently different to merit its own checker.
  5331. if (getLangOpts().CPlusPlus)
  5332. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5333. VK = VK_RValue;
  5334. OK = OK_Ordinary;
  5335. // The OpenCL operator with a vector condition is sufficiently
  5336. // different to merit its own checker.
  5337. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5338. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5339. // First, check the condition.
  5340. Cond = UsualUnaryConversions(Cond.get());
  5341. if (Cond.isInvalid())
  5342. return QualType();
  5343. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5344. return QualType();
  5345. // Now check the two expressions.
  5346. if (LHS.get()->getType()->isVectorType() ||
  5347. RHS.get()->getType()->isVectorType())
  5348. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5349. /*AllowBothBool*/true,
  5350. /*AllowBoolConversions*/false);
  5351. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5352. if (LHS.isInvalid() || RHS.isInvalid())
  5353. return QualType();
  5354. QualType LHSTy = LHS.get()->getType();
  5355. QualType RHSTy = RHS.get()->getType();
  5356. // If both operands have arithmetic type, do the usual arithmetic conversions
  5357. // to find a common type: C99 6.5.15p3,5.
  5358. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5359. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5360. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5361. return ResTy;
  5362. }
  5363. // If both operands are the same structure or union type, the result is that
  5364. // type.
  5365. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5366. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5367. if (LHSRT->getDecl() == RHSRT->getDecl())
  5368. // "If both the operands have structure or union type, the result has
  5369. // that type." This implies that CV qualifiers are dropped.
  5370. return LHSTy.getUnqualifiedType();
  5371. // FIXME: Type of conditional expression must be complete in C mode.
  5372. }
  5373. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5374. // The following || allows only one side to be void (a GCC-ism).
  5375. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5376. return checkConditionalVoidType(*this, LHS, RHS);
  5377. }
  5378. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5379. // the type of the other operand."
  5380. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5381. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5382. // All objective-c pointer type analysis is done here.
  5383. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5384. QuestionLoc);
  5385. if (LHS.isInvalid() || RHS.isInvalid())
  5386. return QualType();
  5387. if (!compositeType.isNull())
  5388. return compositeType;
  5389. // Handle block pointer types.
  5390. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5391. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5392. QuestionLoc);
  5393. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5394. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5395. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5396. QuestionLoc);
  5397. // GCC compatibility: soften pointer/integer mismatch. Note that
  5398. // null pointers have been filtered out by this point.
  5399. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5400. /*isIntFirstExpr=*/true))
  5401. return RHSTy;
  5402. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5403. /*isIntFirstExpr=*/false))
  5404. return LHSTy;
  5405. // Emit a better diagnostic if one of the expressions is a null pointer
  5406. // constant and the other is not a pointer type. In this case, the user most
  5407. // likely forgot to take the address of the other expression.
  5408. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5409. return QualType();
  5410. // Otherwise, the operands are not compatible.
  5411. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5412. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5413. << RHS.get()->getSourceRange();
  5414. return QualType();
  5415. }
  5416. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5417. /// two objective-c pointer types of the two input expressions.
  5418. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5419. SourceLocation QuestionLoc) {
  5420. QualType LHSTy = LHS.get()->getType();
  5421. QualType RHSTy = RHS.get()->getType();
  5422. // Handle things like Class and struct objc_class*. Here we case the result
  5423. // to the pseudo-builtin, because that will be implicitly cast back to the
  5424. // redefinition type if an attempt is made to access its fields.
  5425. if (LHSTy->isObjCClassType() &&
  5426. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5427. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5428. return LHSTy;
  5429. }
  5430. if (RHSTy->isObjCClassType() &&
  5431. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5432. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5433. return RHSTy;
  5434. }
  5435. // And the same for struct objc_object* / id
  5436. if (LHSTy->isObjCIdType() &&
  5437. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5438. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5439. return LHSTy;
  5440. }
  5441. if (RHSTy->isObjCIdType() &&
  5442. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5443. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5444. return RHSTy;
  5445. }
  5446. // And the same for struct objc_selector* / SEL
  5447. if (Context.isObjCSelType(LHSTy) &&
  5448. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5449. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5450. return LHSTy;
  5451. }
  5452. if (Context.isObjCSelType(RHSTy) &&
  5453. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5454. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5455. return RHSTy;
  5456. }
  5457. // Check constraints for Objective-C object pointers types.
  5458. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5459. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5460. // Two identical object pointer types are always compatible.
  5461. return LHSTy;
  5462. }
  5463. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5464. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5465. QualType compositeType = LHSTy;
  5466. // If both operands are interfaces and either operand can be
  5467. // assigned to the other, use that type as the composite
  5468. // type. This allows
  5469. // xxx ? (A*) a : (B*) b
  5470. // where B is a subclass of A.
  5471. //
  5472. // Additionally, as for assignment, if either type is 'id'
  5473. // allow silent coercion. Finally, if the types are
  5474. // incompatible then make sure to use 'id' as the composite
  5475. // type so the result is acceptable for sending messages to.
  5476. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5477. // It could return the composite type.
  5478. if (!(compositeType =
  5479. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  5480. // Nothing more to do.
  5481. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5482. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5483. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5484. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5485. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5486. RHSTy->isObjCQualifiedIdType()) &&
  5487. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5488. // Need to handle "id<xx>" explicitly.
  5489. // GCC allows qualified id and any Objective-C type to devolve to
  5490. // id. Currently localizing to here until clear this should be
  5491. // part of ObjCQualifiedIdTypesAreCompatible.
  5492. compositeType = Context.getObjCIdType();
  5493. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5494. compositeType = Context.getObjCIdType();
  5495. } else {
  5496. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5497. << LHSTy << RHSTy
  5498. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5499. QualType incompatTy = Context.getObjCIdType();
  5500. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5501. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5502. return incompatTy;
  5503. }
  5504. // The object pointer types are compatible.
  5505. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5506. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5507. return compositeType;
  5508. }
  5509. // Check Objective-C object pointer types and 'void *'
  5510. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5511. if (getLangOpts().ObjCAutoRefCount) {
  5512. // ARC forbids the implicit conversion of object pointers to 'void *',
  5513. // so these types are not compatible.
  5514. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5515. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5516. LHS = RHS = true;
  5517. return QualType();
  5518. }
  5519. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5520. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5521. QualType destPointee
  5522. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5523. QualType destType = Context.getPointerType(destPointee);
  5524. // Add qualifiers if necessary.
  5525. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5526. // Promote to void*.
  5527. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5528. return destType;
  5529. }
  5530. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5531. if (getLangOpts().ObjCAutoRefCount) {
  5532. // ARC forbids the implicit conversion of object pointers to 'void *',
  5533. // so these types are not compatible.
  5534. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5535. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5536. LHS = RHS = true;
  5537. return QualType();
  5538. }
  5539. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5540. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5541. QualType destPointee
  5542. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5543. QualType destType = Context.getPointerType(destPointee);
  5544. // Add qualifiers if necessary.
  5545. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5546. // Promote to void*.
  5547. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5548. return destType;
  5549. }
  5550. return QualType();
  5551. }
  5552. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5553. /// ParenRange in parentheses.
  5554. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5555. const PartialDiagnostic &Note,
  5556. SourceRange ParenRange) {
  5557. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  5558. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5559. EndLoc.isValid()) {
  5560. Self.Diag(Loc, Note)
  5561. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5562. << FixItHint::CreateInsertion(EndLoc, ")");
  5563. } else {
  5564. // We can't display the parentheses, so just show the bare note.
  5565. Self.Diag(Loc, Note) << ParenRange;
  5566. }
  5567. }
  5568. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5569. return Opc >= BO_Mul && Opc <= BO_Shr;
  5570. }
  5571. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5572. /// expression, either using a built-in or overloaded operator,
  5573. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5574. /// expression.
  5575. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5576. Expr **RHSExprs) {
  5577. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5578. E = E->IgnoreImpCasts();
  5579. E = E->IgnoreConversionOperator();
  5580. E = E->IgnoreImpCasts();
  5581. // Built-in binary operator.
  5582. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5583. if (IsArithmeticOp(OP->getOpcode())) {
  5584. *Opcode = OP->getOpcode();
  5585. *RHSExprs = OP->getRHS();
  5586. return true;
  5587. }
  5588. }
  5589. // Overloaded operator.
  5590. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5591. if (Call->getNumArgs() != 2)
  5592. return false;
  5593. // Make sure this is really a binary operator that is safe to pass into
  5594. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5595. OverloadedOperatorKind OO = Call->getOperator();
  5596. if (OO < OO_Plus || OO > OO_Arrow ||
  5597. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5598. return false;
  5599. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5600. if (IsArithmeticOp(OpKind)) {
  5601. *Opcode = OpKind;
  5602. *RHSExprs = Call->getArg(1);
  5603. return true;
  5604. }
  5605. }
  5606. return false;
  5607. }
  5608. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5609. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5610. }
  5611. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5612. /// or is a logical expression such as (x==y) which has int type, but is
  5613. /// commonly interpreted as boolean.
  5614. static bool ExprLooksBoolean(Expr *E) {
  5615. E = E->IgnoreParenImpCasts();
  5616. if (E->getType()->isBooleanType())
  5617. return true;
  5618. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5619. return IsLogicOp(OP->getOpcode());
  5620. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5621. return OP->getOpcode() == UO_LNot;
  5622. if (E->getType()->isPointerType())
  5623. return true;
  5624. return false;
  5625. }
  5626. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5627. /// and binary operator are mixed in a way that suggests the programmer assumed
  5628. /// the conditional operator has higher precedence, for example:
  5629. /// "int x = a + someBinaryCondition ? 1 : 2".
  5630. static void DiagnoseConditionalPrecedence(Sema &Self,
  5631. SourceLocation OpLoc,
  5632. Expr *Condition,
  5633. Expr *LHSExpr,
  5634. Expr *RHSExpr) {
  5635. BinaryOperatorKind CondOpcode;
  5636. Expr *CondRHS;
  5637. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5638. return;
  5639. if (!ExprLooksBoolean(CondRHS))
  5640. return;
  5641. // The condition is an arithmetic binary expression, with a right-
  5642. // hand side that looks boolean, so warn.
  5643. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5644. << Condition->getSourceRange()
  5645. << BinaryOperator::getOpcodeStr(CondOpcode);
  5646. SuggestParentheses(Self, OpLoc,
  5647. Self.PDiag(diag::note_precedence_silence)
  5648. << BinaryOperator::getOpcodeStr(CondOpcode),
  5649. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5650. SuggestParentheses(Self, OpLoc,
  5651. Self.PDiag(diag::note_precedence_conditional_first),
  5652. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5653. }
  5654. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5655. /// in the case of a the GNU conditional expr extension.
  5656. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5657. SourceLocation ColonLoc,
  5658. Expr *CondExpr, Expr *LHSExpr,
  5659. Expr *RHSExpr) {
  5660. if (!getLangOpts().CPlusPlus) {
  5661. // C cannot handle TypoExpr nodes in the condition because it
  5662. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5663. // been dealt with before checking the operands.
  5664. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5665. if (!CondResult.isUsable()) return ExprError();
  5666. CondExpr = CondResult.get();
  5667. }
  5668. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5669. // was the condition.
  5670. OpaqueValueExpr *opaqueValue = nullptr;
  5671. Expr *commonExpr = nullptr;
  5672. if (!LHSExpr) {
  5673. commonExpr = CondExpr;
  5674. // Lower out placeholder types first. This is important so that we don't
  5675. // try to capture a placeholder. This happens in few cases in C++; such
  5676. // as Objective-C++'s dictionary subscripting syntax.
  5677. if (commonExpr->hasPlaceholderType()) {
  5678. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5679. if (!result.isUsable()) return ExprError();
  5680. commonExpr = result.get();
  5681. }
  5682. // We usually want to apply unary conversions *before* saving, except
  5683. // in the special case of a C++ l-value conditional.
  5684. if (!(getLangOpts().CPlusPlus
  5685. && !commonExpr->isTypeDependent()
  5686. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5687. && commonExpr->isGLValue()
  5688. && commonExpr->isOrdinaryOrBitFieldObject()
  5689. && RHSExpr->isOrdinaryOrBitFieldObject()
  5690. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5691. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5692. if (commonRes.isInvalid())
  5693. return ExprError();
  5694. commonExpr = commonRes.get();
  5695. }
  5696. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5697. commonExpr->getType(),
  5698. commonExpr->getValueKind(),
  5699. commonExpr->getObjectKind(),
  5700. commonExpr);
  5701. LHSExpr = CondExpr = opaqueValue;
  5702. }
  5703. ExprValueKind VK = VK_RValue;
  5704. ExprObjectKind OK = OK_Ordinary;
  5705. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5706. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5707. VK, OK, QuestionLoc);
  5708. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5709. RHS.isInvalid())
  5710. return ExprError();
  5711. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5712. RHS.get());
  5713. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  5714. if (!commonExpr)
  5715. return new (Context)
  5716. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5717. RHS.get(), result, VK, OK);
  5718. return new (Context) BinaryConditionalOperator(
  5719. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5720. ColonLoc, result, VK, OK);
  5721. }
  5722. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5723. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5724. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5725. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5726. // FIXME: add a couple examples in this comment.
  5727. static Sema::AssignConvertType
  5728. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5729. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5730. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5731. // get the "pointed to" type (ignoring qualifiers at the top level)
  5732. const Type *lhptee, *rhptee;
  5733. Qualifiers lhq, rhq;
  5734. std::tie(lhptee, lhq) =
  5735. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5736. std::tie(rhptee, rhq) =
  5737. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5738. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5739. // C99 6.5.16.1p1: This following citation is common to constraints
  5740. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5741. // qualifiers of the type *pointed to* by the right;
  5742. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5743. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5744. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5745. // Ignore lifetime for further calculation.
  5746. lhq.removeObjCLifetime();
  5747. rhq.removeObjCLifetime();
  5748. }
  5749. if (!lhq.compatiblyIncludes(rhq)) {
  5750. // Treat address-space mismatches as fatal. TODO: address subspaces
  5751. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5752. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5753. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5754. // and from void*.
  5755. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5756. .compatiblyIncludes(
  5757. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5758. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5759. ; // keep old
  5760. // Treat lifetime mismatches as fatal.
  5761. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5762. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5763. // For GCC compatibility, other qualifier mismatches are treated
  5764. // as still compatible in C.
  5765. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5766. }
  5767. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5768. // incomplete type and the other is a pointer to a qualified or unqualified
  5769. // version of void...
  5770. if (lhptee->isVoidType()) {
  5771. if (rhptee->isIncompleteOrObjectType())
  5772. return ConvTy;
  5773. // As an extension, we allow cast to/from void* to function pointer.
  5774. assert(rhptee->isFunctionType());
  5775. return Sema::FunctionVoidPointer;
  5776. }
  5777. if (rhptee->isVoidType()) {
  5778. if (lhptee->isIncompleteOrObjectType())
  5779. return ConvTy;
  5780. // As an extension, we allow cast to/from void* to function pointer.
  5781. assert(lhptee->isFunctionType());
  5782. return Sema::FunctionVoidPointer;
  5783. }
  5784. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5785. // unqualified versions of compatible types, ...
  5786. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5787. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5788. // Check if the pointee types are compatible ignoring the sign.
  5789. // We explicitly check for char so that we catch "char" vs
  5790. // "unsigned char" on systems where "char" is unsigned.
  5791. if (lhptee->isCharType())
  5792. ltrans = S.Context.UnsignedCharTy;
  5793. else if (lhptee->hasSignedIntegerRepresentation())
  5794. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5795. if (rhptee->isCharType())
  5796. rtrans = S.Context.UnsignedCharTy;
  5797. else if (rhptee->hasSignedIntegerRepresentation())
  5798. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5799. if (ltrans == rtrans) {
  5800. // Types are compatible ignoring the sign. Qualifier incompatibility
  5801. // takes priority over sign incompatibility because the sign
  5802. // warning can be disabled.
  5803. if (ConvTy != Sema::Compatible)
  5804. return ConvTy;
  5805. return Sema::IncompatiblePointerSign;
  5806. }
  5807. // If we are a multi-level pointer, it's possible that our issue is simply
  5808. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5809. // the eventual target type is the same and the pointers have the same
  5810. // level of indirection, this must be the issue.
  5811. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5812. do {
  5813. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  5814. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  5815. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  5816. if (lhptee == rhptee)
  5817. return Sema::IncompatibleNestedPointerQualifiers;
  5818. }
  5819. // General pointer incompatibility takes priority over qualifiers.
  5820. return Sema::IncompatiblePointer;
  5821. }
  5822. if (!S.getLangOpts().CPlusPlus &&
  5823. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  5824. return Sema::IncompatiblePointer;
  5825. return ConvTy;
  5826. }
  5827. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  5828. /// block pointer types are compatible or whether a block and normal pointer
  5829. /// are compatible. It is more restrict than comparing two function pointer
  5830. // types.
  5831. static Sema::AssignConvertType
  5832. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  5833. QualType RHSType) {
  5834. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5835. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5836. QualType lhptee, rhptee;
  5837. // get the "pointed to" type (ignoring qualifiers at the top level)
  5838. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  5839. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  5840. // In C++, the types have to match exactly.
  5841. if (S.getLangOpts().CPlusPlus)
  5842. return Sema::IncompatibleBlockPointer;
  5843. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5844. // For blocks we enforce that qualifiers are identical.
  5845. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  5846. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5847. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  5848. return Sema::IncompatibleBlockPointer;
  5849. return ConvTy;
  5850. }
  5851. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  5852. /// for assignment compatibility.
  5853. static Sema::AssignConvertType
  5854. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  5855. QualType RHSType) {
  5856. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  5857. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  5858. if (LHSType->isObjCBuiltinType()) {
  5859. // Class is not compatible with ObjC object pointers.
  5860. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  5861. !RHSType->isObjCQualifiedClassType())
  5862. return Sema::IncompatiblePointer;
  5863. return Sema::Compatible;
  5864. }
  5865. if (RHSType->isObjCBuiltinType()) {
  5866. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  5867. !LHSType->isObjCQualifiedClassType())
  5868. return Sema::IncompatiblePointer;
  5869. return Sema::Compatible;
  5870. }
  5871. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5872. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5873. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  5874. // make an exception for id<P>
  5875. !LHSType->isObjCQualifiedIdType())
  5876. return Sema::CompatiblePointerDiscardsQualifiers;
  5877. if (S.Context.typesAreCompatible(LHSType, RHSType))
  5878. return Sema::Compatible;
  5879. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  5880. return Sema::IncompatibleObjCQualifiedId;
  5881. return Sema::IncompatiblePointer;
  5882. }
  5883. Sema::AssignConvertType
  5884. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  5885. QualType LHSType, QualType RHSType) {
  5886. // Fake up an opaque expression. We don't actually care about what
  5887. // cast operations are required, so if CheckAssignmentConstraints
  5888. // adds casts to this they'll be wasted, but fortunately that doesn't
  5889. // usually happen on valid code.
  5890. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  5891. ExprResult RHSPtr = &RHSExpr;
  5892. CastKind K = CK_Invalid;
  5893. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  5894. }
  5895. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  5896. /// has code to accommodate several GCC extensions when type checking
  5897. /// pointers. Here are some objectionable examples that GCC considers warnings:
  5898. ///
  5899. /// int a, *pint;
  5900. /// short *pshort;
  5901. /// struct foo *pfoo;
  5902. ///
  5903. /// pint = pshort; // warning: assignment from incompatible pointer type
  5904. /// a = pint; // warning: assignment makes integer from pointer without a cast
  5905. /// pint = a; // warning: assignment makes pointer from integer without a cast
  5906. /// pint = pfoo; // warning: assignment from incompatible pointer type
  5907. ///
  5908. /// As a result, the code for dealing with pointers is more complex than the
  5909. /// C99 spec dictates.
  5910. ///
  5911. /// Sets 'Kind' for any result kind except Incompatible.
  5912. Sema::AssignConvertType
  5913. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  5914. CastKind &Kind) {
  5915. QualType RHSType = RHS.get()->getType();
  5916. QualType OrigLHSType = LHSType;
  5917. // Get canonical types. We're not formatting these types, just comparing
  5918. // them.
  5919. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  5920. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  5921. // Common case: no conversion required.
  5922. if (LHSType == RHSType) {
  5923. Kind = CK_NoOp;
  5924. return Compatible;
  5925. }
  5926. // If we have an atomic type, try a non-atomic assignment, then just add an
  5927. // atomic qualification step.
  5928. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  5929. Sema::AssignConvertType result =
  5930. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  5931. if (result != Compatible)
  5932. return result;
  5933. if (Kind != CK_NoOp)
  5934. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  5935. Kind = CK_NonAtomicToAtomic;
  5936. return Compatible;
  5937. }
  5938. // If the left-hand side is a reference type, then we are in a
  5939. // (rare!) case where we've allowed the use of references in C,
  5940. // e.g., as a parameter type in a built-in function. In this case,
  5941. // just make sure that the type referenced is compatible with the
  5942. // right-hand side type. The caller is responsible for adjusting
  5943. // LHSType so that the resulting expression does not have reference
  5944. // type.
  5945. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  5946. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  5947. Kind = CK_LValueBitCast;
  5948. return Compatible;
  5949. }
  5950. return Incompatible;
  5951. }
  5952. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  5953. // to the same ExtVector type.
  5954. if (LHSType->isExtVectorType()) {
  5955. if (RHSType->isExtVectorType())
  5956. return Incompatible;
  5957. if (RHSType->isArithmeticType()) {
  5958. // CK_VectorSplat does T -> vector T, so first cast to the
  5959. // element type.
  5960. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  5961. if (elType != RHSType) {
  5962. Kind = PrepareScalarCast(RHS, elType);
  5963. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  5964. }
  5965. Kind = CK_VectorSplat;
  5966. return Compatible;
  5967. }
  5968. }
  5969. // Conversions to or from vector type.
  5970. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  5971. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  5972. // Allow assignments of an AltiVec vector type to an equivalent GCC
  5973. // vector type and vice versa
  5974. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  5975. Kind = CK_BitCast;
  5976. return Compatible;
  5977. }
  5978. // If we are allowing lax vector conversions, and LHS and RHS are both
  5979. // vectors, the total size only needs to be the same. This is a bitcast;
  5980. // no bits are changed but the result type is different.
  5981. if (isLaxVectorConversion(RHSType, LHSType)) {
  5982. Kind = CK_BitCast;
  5983. return IncompatibleVectors;
  5984. }
  5985. }
  5986. return Incompatible;
  5987. }
  5988. // Arithmetic conversions.
  5989. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  5990. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  5991. Kind = PrepareScalarCast(RHS, LHSType);
  5992. return Compatible;
  5993. }
  5994. // Conversions to normal pointers.
  5995. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  5996. // U* -> T*
  5997. if (isa<PointerType>(RHSType)) {
  5998. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  5999. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6000. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6001. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6002. }
  6003. // int -> T*
  6004. if (RHSType->isIntegerType()) {
  6005. Kind = CK_IntegralToPointer; // FIXME: null?
  6006. return IntToPointer;
  6007. }
  6008. // C pointers are not compatible with ObjC object pointers,
  6009. // with two exceptions:
  6010. if (isa<ObjCObjectPointerType>(RHSType)) {
  6011. // - conversions to void*
  6012. if (LHSPointer->getPointeeType()->isVoidType()) {
  6013. Kind = CK_BitCast;
  6014. return Compatible;
  6015. }
  6016. // - conversions from 'Class' to the redefinition type
  6017. if (RHSType->isObjCClassType() &&
  6018. Context.hasSameType(LHSType,
  6019. Context.getObjCClassRedefinitionType())) {
  6020. Kind = CK_BitCast;
  6021. return Compatible;
  6022. }
  6023. Kind = CK_BitCast;
  6024. return IncompatiblePointer;
  6025. }
  6026. // U^ -> void*
  6027. if (RHSType->getAs<BlockPointerType>()) {
  6028. if (LHSPointer->getPointeeType()->isVoidType()) {
  6029. Kind = CK_BitCast;
  6030. return Compatible;
  6031. }
  6032. }
  6033. return Incompatible;
  6034. }
  6035. // Conversions to block pointers.
  6036. if (isa<BlockPointerType>(LHSType)) {
  6037. // U^ -> T^
  6038. if (RHSType->isBlockPointerType()) {
  6039. Kind = CK_BitCast;
  6040. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6041. }
  6042. // int or null -> T^
  6043. if (RHSType->isIntegerType()) {
  6044. Kind = CK_IntegralToPointer; // FIXME: null
  6045. return IntToBlockPointer;
  6046. }
  6047. // id -> T^
  6048. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6049. Kind = CK_AnyPointerToBlockPointerCast;
  6050. return Compatible;
  6051. }
  6052. // void* -> T^
  6053. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6054. if (RHSPT->getPointeeType()->isVoidType()) {
  6055. Kind = CK_AnyPointerToBlockPointerCast;
  6056. return Compatible;
  6057. }
  6058. return Incompatible;
  6059. }
  6060. // Conversions to Objective-C pointers.
  6061. if (isa<ObjCObjectPointerType>(LHSType)) {
  6062. // A* -> B*
  6063. if (RHSType->isObjCObjectPointerType()) {
  6064. Kind = CK_BitCast;
  6065. Sema::AssignConvertType result =
  6066. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6067. if (getLangOpts().ObjCAutoRefCount &&
  6068. result == Compatible &&
  6069. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6070. result = IncompatibleObjCWeakRef;
  6071. return result;
  6072. }
  6073. // int or null -> A*
  6074. if (RHSType->isIntegerType()) {
  6075. Kind = CK_IntegralToPointer; // FIXME: null
  6076. return IntToPointer;
  6077. }
  6078. // In general, C pointers are not compatible with ObjC object pointers,
  6079. // with two exceptions:
  6080. if (isa<PointerType>(RHSType)) {
  6081. Kind = CK_CPointerToObjCPointerCast;
  6082. // - conversions from 'void*'
  6083. if (RHSType->isVoidPointerType()) {
  6084. return Compatible;
  6085. }
  6086. // - conversions to 'Class' from its redefinition type
  6087. if (LHSType->isObjCClassType() &&
  6088. Context.hasSameType(RHSType,
  6089. Context.getObjCClassRedefinitionType())) {
  6090. return Compatible;
  6091. }
  6092. return IncompatiblePointer;
  6093. }
  6094. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6095. if (RHSType->isBlockPointerType() &&
  6096. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6097. maybeExtendBlockObject(RHS);
  6098. Kind = CK_BlockPointerToObjCPointerCast;
  6099. return Compatible;
  6100. }
  6101. return Incompatible;
  6102. }
  6103. // Conversions from pointers that are not covered by the above.
  6104. if (isa<PointerType>(RHSType)) {
  6105. // T* -> _Bool
  6106. if (LHSType == Context.BoolTy) {
  6107. Kind = CK_PointerToBoolean;
  6108. return Compatible;
  6109. }
  6110. // T* -> int
  6111. if (LHSType->isIntegerType()) {
  6112. Kind = CK_PointerToIntegral;
  6113. return PointerToInt;
  6114. }
  6115. return Incompatible;
  6116. }
  6117. // Conversions from Objective-C pointers that are not covered by the above.
  6118. if (isa<ObjCObjectPointerType>(RHSType)) {
  6119. // T* -> _Bool
  6120. if (LHSType == Context.BoolTy) {
  6121. Kind = CK_PointerToBoolean;
  6122. return Compatible;
  6123. }
  6124. // T* -> int
  6125. if (LHSType->isIntegerType()) {
  6126. Kind = CK_PointerToIntegral;
  6127. return PointerToInt;
  6128. }
  6129. return Incompatible;
  6130. }
  6131. // struct A -> struct B
  6132. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6133. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6134. Kind = CK_NoOp;
  6135. return Compatible;
  6136. }
  6137. }
  6138. return Incompatible;
  6139. }
  6140. /// \brief Constructs a transparent union from an expression that is
  6141. /// used to initialize the transparent union.
  6142. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6143. ExprResult &EResult, QualType UnionType,
  6144. FieldDecl *Field) {
  6145. // Build an initializer list that designates the appropriate member
  6146. // of the transparent union.
  6147. Expr *E = EResult.get();
  6148. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6149. E, SourceLocation());
  6150. Initializer->setType(UnionType);
  6151. Initializer->setInitializedFieldInUnion(Field);
  6152. // Build a compound literal constructing a value of the transparent
  6153. // union type from this initializer list.
  6154. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6155. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6156. VK_RValue, Initializer, false);
  6157. }
  6158. Sema::AssignConvertType
  6159. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6160. ExprResult &RHS) {
  6161. QualType RHSType = RHS.get()->getType();
  6162. // If the ArgType is a Union type, we want to handle a potential
  6163. // transparent_union GCC extension.
  6164. const RecordType *UT = ArgType->getAsUnionType();
  6165. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6166. return Incompatible;
  6167. // The field to initialize within the transparent union.
  6168. RecordDecl *UD = UT->getDecl();
  6169. FieldDecl *InitField = nullptr;
  6170. // It's compatible if the expression matches any of the fields.
  6171. for (auto *it : UD->fields()) {
  6172. if (it->getType()->isPointerType()) {
  6173. // If the transparent union contains a pointer type, we allow:
  6174. // 1) void pointer
  6175. // 2) null pointer constant
  6176. if (RHSType->isPointerType())
  6177. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6178. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6179. InitField = it;
  6180. break;
  6181. }
  6182. if (RHS.get()->isNullPointerConstant(Context,
  6183. Expr::NPC_ValueDependentIsNull)) {
  6184. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6185. CK_NullToPointer);
  6186. InitField = it;
  6187. break;
  6188. }
  6189. }
  6190. CastKind Kind = CK_Invalid;
  6191. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6192. == Compatible) {
  6193. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6194. InitField = it;
  6195. break;
  6196. }
  6197. }
  6198. if (!InitField)
  6199. return Incompatible;
  6200. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6201. return Compatible;
  6202. }
  6203. Sema::AssignConvertType
  6204. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6205. bool Diagnose,
  6206. bool DiagnoseCFAudited) {
  6207. if (getLangOpts().CPlusPlus) {
  6208. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6209. // C++ 5.17p3: If the left operand is not of class type, the
  6210. // expression is implicitly converted (C++ 4) to the
  6211. // cv-unqualified type of the left operand.
  6212. ExprResult Res;
  6213. if (Diagnose) {
  6214. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6215. AA_Assigning);
  6216. } else {
  6217. ImplicitConversionSequence ICS =
  6218. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6219. /*SuppressUserConversions=*/false,
  6220. /*AllowExplicit=*/false,
  6221. /*InOverloadResolution=*/false,
  6222. /*CStyle=*/false,
  6223. /*AllowObjCWritebackConversion=*/false);
  6224. if (ICS.isFailure())
  6225. return Incompatible;
  6226. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6227. ICS, AA_Assigning);
  6228. }
  6229. if (Res.isInvalid())
  6230. return Incompatible;
  6231. Sema::AssignConvertType result = Compatible;
  6232. if (getLangOpts().ObjCAutoRefCount &&
  6233. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6234. RHS.get()->getType()))
  6235. result = IncompatibleObjCWeakRef;
  6236. RHS = Res;
  6237. return result;
  6238. }
  6239. // FIXME: Currently, we fall through and treat C++ classes like C
  6240. // structures.
  6241. // FIXME: We also fall through for atomics; not sure what should
  6242. // happen there, though.
  6243. }
  6244. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6245. // a null pointer constant.
  6246. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6247. LHSType->isBlockPointerType()) &&
  6248. RHS.get()->isNullPointerConstant(Context,
  6249. Expr::NPC_ValueDependentIsNull)) {
  6250. CastKind Kind;
  6251. CXXCastPath Path;
  6252. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6253. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6254. return Compatible;
  6255. }
  6256. // This check seems unnatural, however it is necessary to ensure the proper
  6257. // conversion of functions/arrays. If the conversion were done for all
  6258. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6259. // expressions that suppress this implicit conversion (&, sizeof).
  6260. //
  6261. // Suppress this for references: C++ 8.5.3p5.
  6262. if (!LHSType->isReferenceType()) {
  6263. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6264. if (RHS.isInvalid())
  6265. return Incompatible;
  6266. }
  6267. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6268. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6269. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6270. if (PDecl && !PDecl->hasDefinition()) {
  6271. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6272. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6273. }
  6274. }
  6275. CastKind Kind = CK_Invalid;
  6276. Sema::AssignConvertType result =
  6277. CheckAssignmentConstraints(LHSType, RHS, Kind);
  6278. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6279. // type of the assignment expression.
  6280. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6281. // so that we can use references in built-in functions even in C.
  6282. // The getNonReferenceType() call makes sure that the resulting expression
  6283. // does not have reference type.
  6284. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6285. QualType Ty = LHSType.getNonLValueExprType(Context);
  6286. Expr *E = RHS.get();
  6287. if (getLangOpts().ObjCAutoRefCount)
  6288. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6289. DiagnoseCFAudited);
  6290. if (getLangOpts().ObjC1 &&
  6291. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6292. LHSType, E->getType(), E) ||
  6293. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6294. RHS = E;
  6295. return Compatible;
  6296. }
  6297. RHS = ImpCastExprToType(E, Ty, Kind);
  6298. }
  6299. return result;
  6300. }
  6301. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6302. ExprResult &RHS) {
  6303. Diag(Loc, diag::err_typecheck_invalid_operands)
  6304. << LHS.get()->getType() << RHS.get()->getType()
  6305. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6306. return QualType();
  6307. }
  6308. /// Try to convert a value of non-vector type to a vector type by converting
  6309. /// the type to the element type of the vector and then performing a splat.
  6310. /// If the language is OpenCL, we only use conversions that promote scalar
  6311. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6312. /// for float->int.
  6313. ///
  6314. /// \param scalar - if non-null, actually perform the conversions
  6315. /// \return true if the operation fails (but without diagnosing the failure)
  6316. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6317. QualType scalarTy,
  6318. QualType vectorEltTy,
  6319. QualType vectorTy) {
  6320. // The conversion to apply to the scalar before splatting it,
  6321. // if necessary.
  6322. CastKind scalarCast = CK_Invalid;
  6323. if (vectorEltTy->isIntegralType(S.Context)) {
  6324. if (!scalarTy->isIntegralType(S.Context))
  6325. return true;
  6326. if (S.getLangOpts().OpenCL &&
  6327. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6328. return true;
  6329. scalarCast = CK_IntegralCast;
  6330. } else if (vectorEltTy->isRealFloatingType()) {
  6331. if (scalarTy->isRealFloatingType()) {
  6332. if (S.getLangOpts().OpenCL &&
  6333. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6334. return true;
  6335. scalarCast = CK_FloatingCast;
  6336. }
  6337. else if (scalarTy->isIntegralType(S.Context))
  6338. scalarCast = CK_IntegralToFloating;
  6339. else
  6340. return true;
  6341. } else {
  6342. return true;
  6343. }
  6344. // Adjust scalar if desired.
  6345. if (scalar) {
  6346. if (scalarCast != CK_Invalid)
  6347. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6348. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6349. }
  6350. return false;
  6351. }
  6352. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6353. SourceLocation Loc, bool IsCompAssign,
  6354. bool AllowBothBool,
  6355. bool AllowBoolConversions) {
  6356. if (!IsCompAssign) {
  6357. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6358. if (LHS.isInvalid())
  6359. return QualType();
  6360. }
  6361. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6362. if (RHS.isInvalid())
  6363. return QualType();
  6364. // For conversion purposes, we ignore any qualifiers.
  6365. // For example, "const float" and "float" are equivalent.
  6366. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6367. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6368. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6369. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6370. assert(LHSVecType || RHSVecType);
  6371. // AltiVec-style "vector bool op vector bool" combinations are allowed
  6372. // for some operators but not others.
  6373. if (!AllowBothBool &&
  6374. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6375. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  6376. return InvalidOperands(Loc, LHS, RHS);
  6377. // If the vector types are identical, return.
  6378. if (Context.hasSameType(LHSType, RHSType))
  6379. return LHSType;
  6380. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6381. if (LHSVecType && RHSVecType &&
  6382. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6383. if (isa<ExtVectorType>(LHSVecType)) {
  6384. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6385. return LHSType;
  6386. }
  6387. if (!IsCompAssign)
  6388. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6389. return RHSType;
  6390. }
  6391. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  6392. // can be mixed, with the result being the non-bool type. The non-bool
  6393. // operand must have integer element type.
  6394. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  6395. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  6396. (Context.getTypeSize(LHSVecType->getElementType()) ==
  6397. Context.getTypeSize(RHSVecType->getElementType()))) {
  6398. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6399. LHSVecType->getElementType()->isIntegerType() &&
  6400. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  6401. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6402. return LHSType;
  6403. }
  6404. if (!IsCompAssign &&
  6405. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6406. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6407. RHSVecType->getElementType()->isIntegerType()) {
  6408. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6409. return RHSType;
  6410. }
  6411. }
  6412. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6413. // the vector element type and splat.
  6414. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6415. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6416. LHSVecType->getElementType(), LHSType))
  6417. return LHSType;
  6418. }
  6419. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6420. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6421. LHSType, RHSVecType->getElementType(),
  6422. RHSType))
  6423. return RHSType;
  6424. }
  6425. // If we're allowing lax vector conversions, only the total (data) size
  6426. // needs to be the same.
  6427. // FIXME: Should we really be allowing this?
  6428. // FIXME: We really just pick the LHS type arbitrarily?
  6429. if (isLaxVectorConversion(RHSType, LHSType)) {
  6430. QualType resultType = LHSType;
  6431. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6432. return resultType;
  6433. }
  6434. // Okay, the expression is invalid.
  6435. // If there's a non-vector, non-real operand, diagnose that.
  6436. if ((!RHSVecType && !RHSType->isRealType()) ||
  6437. (!LHSVecType && !LHSType->isRealType())) {
  6438. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6439. << LHSType << RHSType
  6440. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6441. return QualType();
  6442. }
  6443. // Otherwise, use the generic diagnostic.
  6444. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6445. << LHSType << RHSType
  6446. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6447. return QualType();
  6448. }
  6449. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6450. // expression. These are mainly cases where the null pointer is used as an
  6451. // integer instead of a pointer.
  6452. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6453. SourceLocation Loc, bool IsCompare) {
  6454. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6455. // but we use a bit of a hack here for speed; this is a relatively
  6456. // hot path, and isNullPointerConstant is slow.
  6457. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6458. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6459. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6460. // Avoid analyzing cases where the result will either be invalid (and
  6461. // diagnosed as such) or entirely valid and not something to warn about.
  6462. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6463. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6464. return;
  6465. // Comparison operations would not make sense with a null pointer no matter
  6466. // what the other expression is.
  6467. if (!IsCompare) {
  6468. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6469. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6470. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6471. return;
  6472. }
  6473. // The rest of the operations only make sense with a null pointer
  6474. // if the other expression is a pointer.
  6475. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6476. NonNullType->canDecayToPointerType())
  6477. return;
  6478. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6479. << LHSNull /* LHS is NULL */ << NonNullType
  6480. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6481. }
  6482. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  6483. ExprResult &RHS,
  6484. SourceLocation Loc, bool IsDiv) {
  6485. // Check for division/remainder by zero.
  6486. unsigned Diag = (IsDiv) ? diag::warn_division_by_zero :
  6487. diag::warn_remainder_by_zero;
  6488. llvm::APSInt RHSValue;
  6489. if (!RHS.get()->isValueDependent() &&
  6490. RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
  6491. S.DiagRuntimeBehavior(Loc, RHS.get(),
  6492. S.PDiag(Diag) << RHS.get()->getSourceRange());
  6493. }
  6494. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6495. SourceLocation Loc,
  6496. bool IsCompAssign, bool IsDiv) {
  6497. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6498. if (LHS.get()->getType()->isVectorType() ||
  6499. RHS.get()->getType()->isVectorType())
  6500. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6501. /*AllowBothBool*/getLangOpts().AltiVec,
  6502. /*AllowBoolConversions*/false);
  6503. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6504. if (LHS.isInvalid() || RHS.isInvalid())
  6505. return QualType();
  6506. if (compType.isNull() || !compType->isArithmeticType())
  6507. return InvalidOperands(Loc, LHS, RHS);
  6508. if (IsDiv)
  6509. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  6510. return compType;
  6511. }
  6512. QualType Sema::CheckRemainderOperands(
  6513. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6514. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6515. if (LHS.get()->getType()->isVectorType() ||
  6516. RHS.get()->getType()->isVectorType()) {
  6517. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6518. RHS.get()->getType()->hasIntegerRepresentation())
  6519. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6520. /*AllowBothBool*/getLangOpts().AltiVec,
  6521. /*AllowBoolConversions*/false);
  6522. return InvalidOperands(Loc, LHS, RHS);
  6523. }
  6524. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6525. if (LHS.isInvalid() || RHS.isInvalid())
  6526. return QualType();
  6527. if (compType.isNull() || !compType->isIntegerType())
  6528. return InvalidOperands(Loc, LHS, RHS);
  6529. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  6530. return compType;
  6531. }
  6532. /// \brief Diagnose invalid arithmetic on two void pointers.
  6533. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6534. Expr *LHSExpr, Expr *RHSExpr) {
  6535. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6536. ? diag::err_typecheck_pointer_arith_void_type
  6537. : diag::ext_gnu_void_ptr)
  6538. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6539. << RHSExpr->getSourceRange();
  6540. }
  6541. /// \brief Diagnose invalid arithmetic on a void pointer.
  6542. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6543. Expr *Pointer) {
  6544. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6545. ? diag::err_typecheck_pointer_arith_void_type
  6546. : diag::ext_gnu_void_ptr)
  6547. << 0 /* one pointer */ << Pointer->getSourceRange();
  6548. }
  6549. /// \brief Diagnose invalid arithmetic on two function pointers.
  6550. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6551. Expr *LHS, Expr *RHS) {
  6552. assert(LHS->getType()->isAnyPointerType());
  6553. assert(RHS->getType()->isAnyPointerType());
  6554. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6555. ? diag::err_typecheck_pointer_arith_function_type
  6556. : diag::ext_gnu_ptr_func_arith)
  6557. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6558. // We only show the second type if it differs from the first.
  6559. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6560. RHS->getType())
  6561. << RHS->getType()->getPointeeType()
  6562. << LHS->getSourceRange() << RHS->getSourceRange();
  6563. }
  6564. /// \brief Diagnose invalid arithmetic on a function pointer.
  6565. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6566. Expr *Pointer) {
  6567. assert(Pointer->getType()->isAnyPointerType());
  6568. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6569. ? diag::err_typecheck_pointer_arith_function_type
  6570. : diag::ext_gnu_ptr_func_arith)
  6571. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6572. << 0 /* one pointer, so only one type */
  6573. << Pointer->getSourceRange();
  6574. }
  6575. /// \brief Emit error if Operand is incomplete pointer type
  6576. ///
  6577. /// \returns True if pointer has incomplete type
  6578. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6579. Expr *Operand) {
  6580. QualType ResType = Operand->getType();
  6581. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6582. ResType = ResAtomicType->getValueType();
  6583. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6584. QualType PointeeTy = ResType->getPointeeType();
  6585. return S.RequireCompleteType(Loc, PointeeTy,
  6586. diag::err_typecheck_arithmetic_incomplete_type,
  6587. PointeeTy, Operand->getSourceRange());
  6588. }
  6589. /// \brief Check the validity of an arithmetic pointer operand.
  6590. ///
  6591. /// If the operand has pointer type, this code will check for pointer types
  6592. /// which are invalid in arithmetic operations. These will be diagnosed
  6593. /// appropriately, including whether or not the use is supported as an
  6594. /// extension.
  6595. ///
  6596. /// \returns True when the operand is valid to use (even if as an extension).
  6597. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6598. Expr *Operand) {
  6599. QualType ResType = Operand->getType();
  6600. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6601. ResType = ResAtomicType->getValueType();
  6602. if (!ResType->isAnyPointerType()) return true;
  6603. QualType PointeeTy = ResType->getPointeeType();
  6604. if (PointeeTy->isVoidType()) {
  6605. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6606. return !S.getLangOpts().CPlusPlus;
  6607. }
  6608. if (PointeeTy->isFunctionType()) {
  6609. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6610. return !S.getLangOpts().CPlusPlus;
  6611. }
  6612. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6613. return true;
  6614. }
  6615. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6616. /// operands.
  6617. ///
  6618. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6619. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6620. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6621. /// are (potentially problematic) pointers.
  6622. ///
  6623. /// \returns True when the operand is valid to use (even if as an extension).
  6624. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6625. Expr *LHSExpr, Expr *RHSExpr) {
  6626. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6627. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6628. if (!isLHSPointer && !isRHSPointer) return true;
  6629. QualType LHSPointeeTy, RHSPointeeTy;
  6630. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6631. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6632. // if both are pointers check if operation is valid wrt address spaces
  6633. if (isLHSPointer && isRHSPointer) {
  6634. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6635. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6636. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6637. S.Diag(Loc,
  6638. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6639. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6640. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6641. return false;
  6642. }
  6643. }
  6644. // Check for arithmetic on pointers to incomplete types.
  6645. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6646. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6647. if (isLHSVoidPtr || isRHSVoidPtr) {
  6648. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6649. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6650. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6651. return !S.getLangOpts().CPlusPlus;
  6652. }
  6653. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6654. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6655. if (isLHSFuncPtr || isRHSFuncPtr) {
  6656. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6657. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6658. RHSExpr);
  6659. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6660. return !S.getLangOpts().CPlusPlus;
  6661. }
  6662. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6663. return false;
  6664. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6665. return false;
  6666. return true;
  6667. }
  6668. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6669. /// literal.
  6670. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6671. Expr *LHSExpr, Expr *RHSExpr) {
  6672. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6673. Expr* IndexExpr = RHSExpr;
  6674. if (!StrExpr) {
  6675. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6676. IndexExpr = LHSExpr;
  6677. }
  6678. bool IsStringPlusInt = StrExpr &&
  6679. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6680. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6681. return;
  6682. llvm::APSInt index;
  6683. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6684. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6685. if (index.isNonNegative() &&
  6686. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6687. index.isUnsigned()))
  6688. return;
  6689. }
  6690. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6691. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6692. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6693. // Only print a fixit for "str" + int, not for int + "str".
  6694. if (IndexExpr == RHSExpr) {
  6695. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6696. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6697. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6698. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6699. << FixItHint::CreateInsertion(EndLoc, "]");
  6700. } else
  6701. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6702. }
  6703. /// \brief Emit a warning when adding a char literal to a string.
  6704. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6705. Expr *LHSExpr, Expr *RHSExpr) {
  6706. const Expr *StringRefExpr = LHSExpr;
  6707. const CharacterLiteral *CharExpr =
  6708. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6709. if (!CharExpr) {
  6710. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6711. StringRefExpr = RHSExpr;
  6712. }
  6713. if (!CharExpr || !StringRefExpr)
  6714. return;
  6715. const QualType StringType = StringRefExpr->getType();
  6716. // Return if not a PointerType.
  6717. if (!StringType->isAnyPointerType())
  6718. return;
  6719. // Return if not a CharacterType.
  6720. if (!StringType->getPointeeType()->isAnyCharacterType())
  6721. return;
  6722. ASTContext &Ctx = Self.getASTContext();
  6723. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6724. const QualType CharType = CharExpr->getType();
  6725. if (!CharType->isAnyCharacterType() &&
  6726. CharType->isIntegerType() &&
  6727. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6728. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6729. << DiagRange << Ctx.CharTy;
  6730. } else {
  6731. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6732. << DiagRange << CharExpr->getType();
  6733. }
  6734. // Only print a fixit for str + char, not for char + str.
  6735. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6736. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6737. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6738. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6739. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6740. << FixItHint::CreateInsertion(EndLoc, "]");
  6741. } else {
  6742. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6743. }
  6744. }
  6745. /// \brief Emit error when two pointers are incompatible.
  6746. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6747. Expr *LHSExpr, Expr *RHSExpr) {
  6748. assert(LHSExpr->getType()->isAnyPointerType());
  6749. assert(RHSExpr->getType()->isAnyPointerType());
  6750. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6751. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6752. << RHSExpr->getSourceRange();
  6753. }
  6754. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  6755. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  6756. QualType* CompLHSTy) {
  6757. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6758. if (LHS.get()->getType()->isVectorType() ||
  6759. RHS.get()->getType()->isVectorType()) {
  6760. QualType compType = CheckVectorOperands(
  6761. LHS, RHS, Loc, CompLHSTy,
  6762. /*AllowBothBool*/getLangOpts().AltiVec,
  6763. /*AllowBoolConversions*/getLangOpts().ZVector);
  6764. if (CompLHSTy) *CompLHSTy = compType;
  6765. return compType;
  6766. }
  6767. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6768. if (LHS.isInvalid() || RHS.isInvalid())
  6769. return QualType();
  6770. // Diagnose "string literal" '+' int and string '+' "char literal".
  6771. if (Opc == BO_Add) {
  6772. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6773. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6774. }
  6775. // handle the common case first (both operands are arithmetic).
  6776. if (!compType.isNull() && compType->isArithmeticType()) {
  6777. if (CompLHSTy) *CompLHSTy = compType;
  6778. return compType;
  6779. }
  6780. // Type-checking. Ultimately the pointer's going to be in PExp;
  6781. // note that we bias towards the LHS being the pointer.
  6782. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6783. bool isObjCPointer;
  6784. if (PExp->getType()->isPointerType()) {
  6785. isObjCPointer = false;
  6786. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6787. isObjCPointer = true;
  6788. } else {
  6789. std::swap(PExp, IExp);
  6790. if (PExp->getType()->isPointerType()) {
  6791. isObjCPointer = false;
  6792. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6793. isObjCPointer = true;
  6794. } else {
  6795. return InvalidOperands(Loc, LHS, RHS);
  6796. }
  6797. }
  6798. assert(PExp->getType()->isAnyPointerType());
  6799. if (!IExp->getType()->isIntegerType())
  6800. return InvalidOperands(Loc, LHS, RHS);
  6801. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6802. return QualType();
  6803. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6804. return QualType();
  6805. // Check array bounds for pointer arithemtic
  6806. CheckArrayAccess(PExp, IExp);
  6807. if (CompLHSTy) {
  6808. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  6809. if (LHSTy.isNull()) {
  6810. LHSTy = LHS.get()->getType();
  6811. if (LHSTy->isPromotableIntegerType())
  6812. LHSTy = Context.getPromotedIntegerType(LHSTy);
  6813. }
  6814. *CompLHSTy = LHSTy;
  6815. }
  6816. return PExp->getType();
  6817. }
  6818. // C99 6.5.6
  6819. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  6820. SourceLocation Loc,
  6821. QualType* CompLHSTy) {
  6822. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6823. if (LHS.get()->getType()->isVectorType() ||
  6824. RHS.get()->getType()->isVectorType()) {
  6825. QualType compType = CheckVectorOperands(
  6826. LHS, RHS, Loc, CompLHSTy,
  6827. /*AllowBothBool*/getLangOpts().AltiVec,
  6828. /*AllowBoolConversions*/getLangOpts().ZVector);
  6829. if (CompLHSTy) *CompLHSTy = compType;
  6830. return compType;
  6831. }
  6832. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6833. if (LHS.isInvalid() || RHS.isInvalid())
  6834. return QualType();
  6835. // Enforce type constraints: C99 6.5.6p3.
  6836. // Handle the common case first (both operands are arithmetic).
  6837. if (!compType.isNull() && compType->isArithmeticType()) {
  6838. if (CompLHSTy) *CompLHSTy = compType;
  6839. return compType;
  6840. }
  6841. // Either ptr - int or ptr - ptr.
  6842. if (LHS.get()->getType()->isAnyPointerType()) {
  6843. QualType lpointee = LHS.get()->getType()->getPointeeType();
  6844. // Diagnose bad cases where we step over interface counts.
  6845. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  6846. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  6847. return QualType();
  6848. // The result type of a pointer-int computation is the pointer type.
  6849. if (RHS.get()->getType()->isIntegerType()) {
  6850. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  6851. return QualType();
  6852. // Check array bounds for pointer arithemtic
  6853. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  6854. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  6855. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  6856. return LHS.get()->getType();
  6857. }
  6858. // Handle pointer-pointer subtractions.
  6859. if (const PointerType *RHSPTy
  6860. = RHS.get()->getType()->getAs<PointerType>()) {
  6861. QualType rpointee = RHSPTy->getPointeeType();
  6862. if (getLangOpts().CPlusPlus) {
  6863. // Pointee types must be the same: C++ [expr.add]
  6864. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  6865. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6866. }
  6867. } else {
  6868. // Pointee types must be compatible C99 6.5.6p3
  6869. if (!Context.typesAreCompatible(
  6870. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  6871. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  6872. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6873. return QualType();
  6874. }
  6875. }
  6876. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  6877. LHS.get(), RHS.get()))
  6878. return QualType();
  6879. // The pointee type may have zero size. As an extension, a structure or
  6880. // union may have zero size or an array may have zero length. In this
  6881. // case subtraction does not make sense.
  6882. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  6883. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  6884. if (ElementSize.isZero()) {
  6885. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  6886. << rpointee.getUnqualifiedType()
  6887. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6888. }
  6889. }
  6890. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  6891. return Context.getPointerDiffType();
  6892. }
  6893. }
  6894. return InvalidOperands(Loc, LHS, RHS);
  6895. }
  6896. static bool isScopedEnumerationType(QualType T) {
  6897. if (const EnumType *ET = T->getAs<EnumType>())
  6898. return ET->getDecl()->isScoped();
  6899. return false;
  6900. }
  6901. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  6902. SourceLocation Loc, unsigned Opc,
  6903. QualType LHSType) {
  6904. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  6905. // so skip remaining warnings as we don't want to modify values within Sema.
  6906. if (S.getLangOpts().OpenCL)
  6907. return;
  6908. llvm::APSInt Right;
  6909. // Check right/shifter operand
  6910. if (RHS.get()->isValueDependent() ||
  6911. !RHS.get()->EvaluateAsInt(Right, S.Context))
  6912. return;
  6913. if (Right.isNegative()) {
  6914. S.DiagRuntimeBehavior(Loc, RHS.get(),
  6915. S.PDiag(diag::warn_shift_negative)
  6916. << RHS.get()->getSourceRange());
  6917. return;
  6918. }
  6919. llvm::APInt LeftBits(Right.getBitWidth(),
  6920. S.Context.getTypeSize(LHS.get()->getType()));
  6921. if (Right.uge(LeftBits)) {
  6922. S.DiagRuntimeBehavior(Loc, RHS.get(),
  6923. S.PDiag(diag::warn_shift_gt_typewidth)
  6924. << RHS.get()->getSourceRange());
  6925. return;
  6926. }
  6927. if (Opc != BO_Shl)
  6928. return;
  6929. // When left shifting an ICE which is signed, we can check for overflow which
  6930. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  6931. // integers have defined behavior modulo one more than the maximum value
  6932. // representable in the result type, so never warn for those.
  6933. llvm::APSInt Left;
  6934. if (LHS.get()->isValueDependent() ||
  6935. LHSType->hasUnsignedIntegerRepresentation() ||
  6936. !LHS.get()->EvaluateAsInt(Left, S.Context))
  6937. return;
  6938. // If LHS does not have a signed type and non-negative value
  6939. // then, the behavior is undefined. Warn about it.
  6940. if (Left.isNegative()) {
  6941. S.DiagRuntimeBehavior(Loc, LHS.get(),
  6942. S.PDiag(diag::warn_shift_lhs_negative)
  6943. << LHS.get()->getSourceRange());
  6944. return;
  6945. }
  6946. llvm::APInt ResultBits =
  6947. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  6948. if (LeftBits.uge(ResultBits))
  6949. return;
  6950. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  6951. Result = Result.shl(Right);
  6952. // Print the bit representation of the signed integer as an unsigned
  6953. // hexadecimal number.
  6954. SmallString<40> HexResult;
  6955. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  6956. // If we are only missing a sign bit, this is less likely to result in actual
  6957. // bugs -- if the result is cast back to an unsigned type, it will have the
  6958. // expected value. Thus we place this behind a different warning that can be
  6959. // turned off separately if needed.
  6960. if (LeftBits == ResultBits - 1) {
  6961. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  6962. << HexResult << LHSType
  6963. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6964. return;
  6965. }
  6966. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  6967. << HexResult.str() << Result.getMinSignedBits() << LHSType
  6968. << Left.getBitWidth() << LHS.get()->getSourceRange()
  6969. << RHS.get()->getSourceRange();
  6970. }
  6971. /// \brief Return the resulting type when an OpenCL vector is shifted
  6972. /// by a scalar or vector shift amount.
  6973. static QualType checkOpenCLVectorShift(Sema &S,
  6974. ExprResult &LHS, ExprResult &RHS,
  6975. SourceLocation Loc, bool IsCompAssign) {
  6976. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  6977. if (!LHS.get()->getType()->isVectorType()) {
  6978. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  6979. << RHS.get()->getType() << LHS.get()->getType()
  6980. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6981. return QualType();
  6982. }
  6983. if (!IsCompAssign) {
  6984. LHS = S.UsualUnaryConversions(LHS.get());
  6985. if (LHS.isInvalid()) return QualType();
  6986. }
  6987. RHS = S.UsualUnaryConversions(RHS.get());
  6988. if (RHS.isInvalid()) return QualType();
  6989. QualType LHSType = LHS.get()->getType();
  6990. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  6991. QualType LHSEleType = LHSVecTy->getElementType();
  6992. // Note that RHS might not be a vector.
  6993. QualType RHSType = RHS.get()->getType();
  6994. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  6995. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  6996. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  6997. if (!LHSEleType->isIntegerType()) {
  6998. S.Diag(Loc, diag::err_typecheck_expect_int)
  6999. << LHS.get()->getType() << LHS.get()->getSourceRange();
  7000. return QualType();
  7001. }
  7002. if (!RHSEleType->isIntegerType()) {
  7003. S.Diag(Loc, diag::err_typecheck_expect_int)
  7004. << RHS.get()->getType() << RHS.get()->getSourceRange();
  7005. return QualType();
  7006. }
  7007. if (RHSVecTy) {
  7008. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  7009. // are applied component-wise. So if RHS is a vector, then ensure
  7010. // that the number of elements is the same as LHS...
  7011. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  7012. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  7013. << LHS.get()->getType() << RHS.get()->getType()
  7014. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7015. return QualType();
  7016. }
  7017. } else {
  7018. // ...else expand RHS to match the number of elements in LHS.
  7019. QualType VecTy =
  7020. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  7021. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  7022. }
  7023. return LHSType;
  7024. }
  7025. // C99 6.5.7
  7026. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  7027. SourceLocation Loc, unsigned Opc,
  7028. bool IsCompAssign) {
  7029. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7030. // Vector shifts promote their scalar inputs to vector type.
  7031. if (LHS.get()->getType()->isVectorType() ||
  7032. RHS.get()->getType()->isVectorType()) {
  7033. if (LangOpts.OpenCL)
  7034. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7035. if (LangOpts.ZVector) {
  7036. // The shift operators for the z vector extensions work basically
  7037. // like OpenCL shifts, except that neither the LHS nor the RHS is
  7038. // allowed to be a "vector bool".
  7039. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  7040. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7041. return InvalidOperands(Loc, LHS, RHS);
  7042. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  7043. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7044. return InvalidOperands(Loc, LHS, RHS);
  7045. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7046. }
  7047. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7048. /*AllowBothBool*/true,
  7049. /*AllowBoolConversions*/false);
  7050. }
  7051. // Shifts don't perform usual arithmetic conversions, they just do integer
  7052. // promotions on each operand. C99 6.5.7p3
  7053. // For the LHS, do usual unary conversions, but then reset them away
  7054. // if this is a compound assignment.
  7055. ExprResult OldLHS = LHS;
  7056. LHS = UsualUnaryConversions(LHS.get());
  7057. if (LHS.isInvalid())
  7058. return QualType();
  7059. QualType LHSType = LHS.get()->getType();
  7060. if (IsCompAssign) LHS = OldLHS;
  7061. // The RHS is simpler.
  7062. RHS = UsualUnaryConversions(RHS.get());
  7063. if (RHS.isInvalid())
  7064. return QualType();
  7065. QualType RHSType = RHS.get()->getType();
  7066. // C99 6.5.7p2: Each of the operands shall have integer type.
  7067. if (!LHSType->hasIntegerRepresentation() ||
  7068. !RHSType->hasIntegerRepresentation())
  7069. return InvalidOperands(Loc, LHS, RHS);
  7070. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  7071. // hasIntegerRepresentation() above instead of this.
  7072. if (isScopedEnumerationType(LHSType) ||
  7073. isScopedEnumerationType(RHSType)) {
  7074. return InvalidOperands(Loc, LHS, RHS);
  7075. }
  7076. // Sanity-check shift operands
  7077. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  7078. // "The type of the result is that of the promoted left operand."
  7079. return LHSType;
  7080. }
  7081. static bool IsWithinTemplateSpecialization(Decl *D) {
  7082. if (DeclContext *DC = D->getDeclContext()) {
  7083. if (isa<ClassTemplateSpecializationDecl>(DC))
  7084. return true;
  7085. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  7086. return FD->isFunctionTemplateSpecialization();
  7087. }
  7088. return false;
  7089. }
  7090. /// If two different enums are compared, raise a warning.
  7091. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  7092. Expr *RHS) {
  7093. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  7094. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  7095. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  7096. if (!LHSEnumType)
  7097. return;
  7098. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  7099. if (!RHSEnumType)
  7100. return;
  7101. // Ignore anonymous enums.
  7102. if (!LHSEnumType->getDecl()->getIdentifier())
  7103. return;
  7104. if (!RHSEnumType->getDecl()->getIdentifier())
  7105. return;
  7106. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  7107. return;
  7108. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  7109. << LHSStrippedType << RHSStrippedType
  7110. << LHS->getSourceRange() << RHS->getSourceRange();
  7111. }
  7112. /// \brief Diagnose bad pointer comparisons.
  7113. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  7114. ExprResult &LHS, ExprResult &RHS,
  7115. bool IsError) {
  7116. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  7117. : diag::ext_typecheck_comparison_of_distinct_pointers)
  7118. << LHS.get()->getType() << RHS.get()->getType()
  7119. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7120. }
  7121. /// \brief Returns false if the pointers are converted to a composite type,
  7122. /// true otherwise.
  7123. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  7124. ExprResult &LHS, ExprResult &RHS) {
  7125. // C++ [expr.rel]p2:
  7126. // [...] Pointer conversions (4.10) and qualification
  7127. // conversions (4.4) are performed on pointer operands (or on
  7128. // a pointer operand and a null pointer constant) to bring
  7129. // them to their composite pointer type. [...]
  7130. //
  7131. // C++ [expr.eq]p1 uses the same notion for (in)equality
  7132. // comparisons of pointers.
  7133. // C++ [expr.eq]p2:
  7134. // In addition, pointers to members can be compared, or a pointer to
  7135. // member and a null pointer constant. Pointer to member conversions
  7136. // (4.11) and qualification conversions (4.4) are performed to bring
  7137. // them to a common type. If one operand is a null pointer constant,
  7138. // the common type is the type of the other operand. Otherwise, the
  7139. // common type is a pointer to member type similar (4.4) to the type
  7140. // of one of the operands, with a cv-qualification signature (4.4)
  7141. // that is the union of the cv-qualification signatures of the operand
  7142. // types.
  7143. QualType LHSType = LHS.get()->getType();
  7144. QualType RHSType = RHS.get()->getType();
  7145. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  7146. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  7147. bool NonStandardCompositeType = false;
  7148. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  7149. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  7150. if (T.isNull()) {
  7151. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  7152. return true;
  7153. }
  7154. if (NonStandardCompositeType)
  7155. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  7156. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  7157. << RHS.get()->getSourceRange();
  7158. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  7159. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  7160. return false;
  7161. }
  7162. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  7163. ExprResult &LHS,
  7164. ExprResult &RHS,
  7165. bool IsError) {
  7166. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  7167. : diag::ext_typecheck_comparison_of_fptr_to_void)
  7168. << LHS.get()->getType() << RHS.get()->getType()
  7169. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7170. }
  7171. static bool isObjCObjectLiteral(ExprResult &E) {
  7172. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  7173. case Stmt::ObjCArrayLiteralClass:
  7174. case Stmt::ObjCDictionaryLiteralClass:
  7175. case Stmt::ObjCStringLiteralClass:
  7176. case Stmt::ObjCBoxedExprClass:
  7177. return true;
  7178. default:
  7179. // Note that ObjCBoolLiteral is NOT an object literal!
  7180. return false;
  7181. }
  7182. }
  7183. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  7184. const ObjCObjectPointerType *Type =
  7185. LHS->getType()->getAs<ObjCObjectPointerType>();
  7186. // If this is not actually an Objective-C object, bail out.
  7187. if (!Type)
  7188. return false;
  7189. // Get the LHS object's interface type.
  7190. QualType InterfaceType = Type->getPointeeType();
  7191. // If the RHS isn't an Objective-C object, bail out.
  7192. if (!RHS->getType()->isObjCObjectPointerType())
  7193. return false;
  7194. // Try to find the -isEqual: method.
  7195. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  7196. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  7197. InterfaceType,
  7198. /*instance=*/true);
  7199. if (!Method) {
  7200. if (Type->isObjCIdType()) {
  7201. // For 'id', just check the global pool.
  7202. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7203. /*receiverId=*/true);
  7204. } else {
  7205. // Check protocols.
  7206. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7207. /*instance=*/true);
  7208. }
  7209. }
  7210. if (!Method)
  7211. return false;
  7212. QualType T = Method->parameters()[0]->getType();
  7213. if (!T->isObjCObjectPointerType())
  7214. return false;
  7215. QualType R = Method->getReturnType();
  7216. if (!R->isScalarType())
  7217. return false;
  7218. return true;
  7219. }
  7220. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7221. FromE = FromE->IgnoreParenImpCasts();
  7222. switch (FromE->getStmtClass()) {
  7223. default:
  7224. break;
  7225. case Stmt::ObjCStringLiteralClass:
  7226. // "string literal"
  7227. return LK_String;
  7228. case Stmt::ObjCArrayLiteralClass:
  7229. // "array literal"
  7230. return LK_Array;
  7231. case Stmt::ObjCDictionaryLiteralClass:
  7232. // "dictionary literal"
  7233. return LK_Dictionary;
  7234. case Stmt::BlockExprClass:
  7235. return LK_Block;
  7236. case Stmt::ObjCBoxedExprClass: {
  7237. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7238. switch (Inner->getStmtClass()) {
  7239. case Stmt::IntegerLiteralClass:
  7240. case Stmt::FloatingLiteralClass:
  7241. case Stmt::CharacterLiteralClass:
  7242. case Stmt::ObjCBoolLiteralExprClass:
  7243. case Stmt::CXXBoolLiteralExprClass:
  7244. // "numeric literal"
  7245. return LK_Numeric;
  7246. case Stmt::ImplicitCastExprClass: {
  7247. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7248. // Boolean literals can be represented by implicit casts.
  7249. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7250. return LK_Numeric;
  7251. break;
  7252. }
  7253. default:
  7254. break;
  7255. }
  7256. return LK_Boxed;
  7257. }
  7258. }
  7259. return LK_None;
  7260. }
  7261. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7262. ExprResult &LHS, ExprResult &RHS,
  7263. BinaryOperator::Opcode Opc){
  7264. Expr *Literal;
  7265. Expr *Other;
  7266. if (isObjCObjectLiteral(LHS)) {
  7267. Literal = LHS.get();
  7268. Other = RHS.get();
  7269. } else {
  7270. Literal = RHS.get();
  7271. Other = LHS.get();
  7272. }
  7273. // Don't warn on comparisons against nil.
  7274. Other = Other->IgnoreParenCasts();
  7275. if (Other->isNullPointerConstant(S.getASTContext(),
  7276. Expr::NPC_ValueDependentIsNotNull))
  7277. return;
  7278. // This should be kept in sync with warn_objc_literal_comparison.
  7279. // LK_String should always be after the other literals, since it has its own
  7280. // warning flag.
  7281. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7282. assert(LiteralKind != Sema::LK_Block);
  7283. if (LiteralKind == Sema::LK_None) {
  7284. llvm_unreachable("Unknown Objective-C object literal kind");
  7285. }
  7286. if (LiteralKind == Sema::LK_String)
  7287. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7288. << Literal->getSourceRange();
  7289. else
  7290. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7291. << LiteralKind << Literal->getSourceRange();
  7292. if (BinaryOperator::isEqualityOp(Opc) &&
  7293. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7294. SourceLocation Start = LHS.get()->getLocStart();
  7295. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  7296. CharSourceRange OpRange =
  7297. CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
  7298. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7299. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7300. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7301. << FixItHint::CreateInsertion(End, "]");
  7302. }
  7303. }
  7304. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7305. ExprResult &RHS,
  7306. SourceLocation Loc,
  7307. unsigned OpaqueOpc) {
  7308. // Check that left hand side is !something.
  7309. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7310. if (!UO || UO->getOpcode() != UO_LNot) return;
  7311. // Only check if the right hand side is non-bool arithmetic type.
  7312. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  7313. // Make sure that the something in !something is not bool.
  7314. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7315. if (SubExpr->isKnownToHaveBooleanValue()) return;
  7316. // Emit warning.
  7317. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7318. << Loc;
  7319. // First note suggest !(x < y)
  7320. SourceLocation FirstOpen = SubExpr->getLocStart();
  7321. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7322. FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
  7323. if (FirstClose.isInvalid())
  7324. FirstOpen = SourceLocation();
  7325. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7326. << FixItHint::CreateInsertion(FirstOpen, "(")
  7327. << FixItHint::CreateInsertion(FirstClose, ")");
  7328. // Second note suggests (!x) < y
  7329. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7330. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7331. SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
  7332. if (SecondClose.isInvalid())
  7333. SecondOpen = SourceLocation();
  7334. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7335. << FixItHint::CreateInsertion(SecondOpen, "(")
  7336. << FixItHint::CreateInsertion(SecondClose, ")");
  7337. }
  7338. // Get the decl for a simple expression: a reference to a variable,
  7339. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7340. static ValueDecl *getCompareDecl(Expr *E) {
  7341. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7342. return DR->getDecl();
  7343. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7344. if (Ivar->isFreeIvar())
  7345. return Ivar->getDecl();
  7346. }
  7347. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7348. if (Mem->isImplicitAccess())
  7349. return Mem->getMemberDecl();
  7350. }
  7351. return nullptr;
  7352. }
  7353. // C99 6.5.8, C++ [expr.rel]
  7354. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7355. SourceLocation Loc, unsigned OpaqueOpc,
  7356. bool IsRelational) {
  7357. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7358. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  7359. // Handle vector comparisons separately.
  7360. if (LHS.get()->getType()->isVectorType() ||
  7361. RHS.get()->getType()->isVectorType())
  7362. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7363. QualType LHSType = LHS.get()->getType();
  7364. QualType RHSType = RHS.get()->getType();
  7365. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7366. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7367. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7368. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
  7369. if (!LHSType->hasFloatingRepresentation() &&
  7370. !(LHSType->isBlockPointerType() && IsRelational) &&
  7371. !LHS.get()->getLocStart().isMacroID() &&
  7372. !RHS.get()->getLocStart().isMacroID() &&
  7373. ActiveTemplateInstantiations.empty()) {
  7374. // For non-floating point types, check for self-comparisons of the form
  7375. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7376. // often indicate logic errors in the program.
  7377. //
  7378. // NOTE: Don't warn about comparison expressions resulting from macro
  7379. // expansion. Also don't warn about comparisons which are only self
  7380. // comparisons within a template specialization. The warnings should catch
  7381. // obvious cases in the definition of the template anyways. The idea is to
  7382. // warn when the typed comparison operator will always evaluate to the same
  7383. // result.
  7384. ValueDecl *DL = getCompareDecl(LHSStripped);
  7385. ValueDecl *DR = getCompareDecl(RHSStripped);
  7386. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7387. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7388. << 0 // self-
  7389. << (Opc == BO_EQ
  7390. || Opc == BO_LE
  7391. || Opc == BO_GE));
  7392. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7393. !DL->getType()->isReferenceType() &&
  7394. !DR->getType()->isReferenceType()) {
  7395. // what is it always going to eval to?
  7396. char always_evals_to;
  7397. switch(Opc) {
  7398. case BO_EQ: // e.g. array1 == array2
  7399. always_evals_to = 0; // false
  7400. break;
  7401. case BO_NE: // e.g. array1 != array2
  7402. always_evals_to = 1; // true
  7403. break;
  7404. default:
  7405. // best we can say is 'a constant'
  7406. always_evals_to = 2; // e.g. array1 <= array2
  7407. break;
  7408. }
  7409. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7410. << 1 // array
  7411. << always_evals_to);
  7412. }
  7413. if (isa<CastExpr>(LHSStripped))
  7414. LHSStripped = LHSStripped->IgnoreParenCasts();
  7415. if (isa<CastExpr>(RHSStripped))
  7416. RHSStripped = RHSStripped->IgnoreParenCasts();
  7417. // Warn about comparisons against a string constant (unless the other
  7418. // operand is null), the user probably wants strcmp.
  7419. Expr *literalString = nullptr;
  7420. Expr *literalStringStripped = nullptr;
  7421. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7422. !RHSStripped->isNullPointerConstant(Context,
  7423. Expr::NPC_ValueDependentIsNull)) {
  7424. literalString = LHS.get();
  7425. literalStringStripped = LHSStripped;
  7426. } else if ((isa<StringLiteral>(RHSStripped) ||
  7427. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7428. !LHSStripped->isNullPointerConstant(Context,
  7429. Expr::NPC_ValueDependentIsNull)) {
  7430. literalString = RHS.get();
  7431. literalStringStripped = RHSStripped;
  7432. }
  7433. if (literalString) {
  7434. DiagRuntimeBehavior(Loc, nullptr,
  7435. PDiag(diag::warn_stringcompare)
  7436. << isa<ObjCEncodeExpr>(literalStringStripped)
  7437. << literalString->getSourceRange());
  7438. }
  7439. }
  7440. // C99 6.5.8p3 / C99 6.5.9p4
  7441. UsualArithmeticConversions(LHS, RHS);
  7442. if (LHS.isInvalid() || RHS.isInvalid())
  7443. return QualType();
  7444. LHSType = LHS.get()->getType();
  7445. RHSType = RHS.get()->getType();
  7446. // The result of comparisons is 'bool' in C++, 'int' in C.
  7447. QualType ResultTy = Context.getLogicalOperationType();
  7448. if (IsRelational) {
  7449. if (LHSType->isRealType() && RHSType->isRealType())
  7450. return ResultTy;
  7451. } else {
  7452. // Check for comparisons of floating point operands using != and ==.
  7453. if (LHSType->hasFloatingRepresentation())
  7454. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7455. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7456. return ResultTy;
  7457. }
  7458. const Expr::NullPointerConstantKind LHSNullKind =
  7459. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7460. const Expr::NullPointerConstantKind RHSNullKind =
  7461. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7462. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7463. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7464. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7465. bool IsEquality = Opc == BO_EQ;
  7466. if (RHSIsNull)
  7467. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7468. RHS.get()->getSourceRange());
  7469. else
  7470. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7471. LHS.get()->getSourceRange());
  7472. }
  7473. // All of the following pointer-related warnings are GCC extensions, except
  7474. // when handling null pointer constants.
  7475. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7476. QualType LCanPointeeTy =
  7477. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7478. QualType RCanPointeeTy =
  7479. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7480. if (getLangOpts().CPlusPlus) {
  7481. if (LCanPointeeTy == RCanPointeeTy)
  7482. return ResultTy;
  7483. if (!IsRelational &&
  7484. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7485. // Valid unless comparison between non-null pointer and function pointer
  7486. // This is a gcc extension compatibility comparison.
  7487. // In a SFINAE context, we treat this as a hard error to maintain
  7488. // conformance with the C++ standard.
  7489. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7490. && !LHSIsNull && !RHSIsNull) {
  7491. diagnoseFunctionPointerToVoidComparison(
  7492. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7493. if (isSFINAEContext())
  7494. return QualType();
  7495. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7496. return ResultTy;
  7497. }
  7498. }
  7499. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7500. return QualType();
  7501. else
  7502. return ResultTy;
  7503. }
  7504. // C99 6.5.9p2 and C99 6.5.8p2
  7505. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7506. RCanPointeeTy.getUnqualifiedType())) {
  7507. // Valid unless a relational comparison of function pointers
  7508. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7509. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7510. << LHSType << RHSType << LHS.get()->getSourceRange()
  7511. << RHS.get()->getSourceRange();
  7512. }
  7513. } else if (!IsRelational &&
  7514. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7515. // Valid unless comparison between non-null pointer and function pointer
  7516. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7517. && !LHSIsNull && !RHSIsNull)
  7518. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7519. /*isError*/false);
  7520. } else {
  7521. // Invalid
  7522. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7523. }
  7524. if (LCanPointeeTy != RCanPointeeTy) {
  7525. const PointerType *lhsPtr = LHSType->getAs<PointerType>();
  7526. if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7527. Diag(Loc,
  7528. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7529. << LHSType << RHSType << 0 /* comparison */
  7530. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7531. }
  7532. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7533. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7534. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7535. : CK_BitCast;
  7536. if (LHSIsNull && !RHSIsNull)
  7537. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7538. else
  7539. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7540. }
  7541. return ResultTy;
  7542. }
  7543. if (getLangOpts().CPlusPlus) {
  7544. // Comparison of nullptr_t with itself.
  7545. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7546. return ResultTy;
  7547. // Comparison of pointers with null pointer constants and equality
  7548. // comparisons of member pointers to null pointer constants.
  7549. if (RHSIsNull &&
  7550. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7551. (!IsRelational &&
  7552. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7553. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7554. LHSType->isMemberPointerType()
  7555. ? CK_NullToMemberPointer
  7556. : CK_NullToPointer);
  7557. return ResultTy;
  7558. }
  7559. if (LHSIsNull &&
  7560. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7561. (!IsRelational &&
  7562. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7563. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7564. RHSType->isMemberPointerType()
  7565. ? CK_NullToMemberPointer
  7566. : CK_NullToPointer);
  7567. return ResultTy;
  7568. }
  7569. // Comparison of member pointers.
  7570. if (!IsRelational &&
  7571. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7572. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7573. return QualType();
  7574. else
  7575. return ResultTy;
  7576. }
  7577. // Handle scoped enumeration types specifically, since they don't promote
  7578. // to integers.
  7579. if (LHS.get()->getType()->isEnumeralType() &&
  7580. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7581. RHS.get()->getType()))
  7582. return ResultTy;
  7583. }
  7584. // Handle block pointer types.
  7585. if (!IsRelational && LHSType->isBlockPointerType() &&
  7586. RHSType->isBlockPointerType()) {
  7587. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7588. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7589. if (!LHSIsNull && !RHSIsNull &&
  7590. !Context.typesAreCompatible(lpointee, rpointee)) {
  7591. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7592. << LHSType << RHSType << LHS.get()->getSourceRange()
  7593. << RHS.get()->getSourceRange();
  7594. }
  7595. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7596. return ResultTy;
  7597. }
  7598. // Allow block pointers to be compared with null pointer constants.
  7599. if (!IsRelational
  7600. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7601. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7602. if (!LHSIsNull && !RHSIsNull) {
  7603. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7604. ->getPointeeType()->isVoidType())
  7605. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7606. ->getPointeeType()->isVoidType())))
  7607. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7608. << LHSType << RHSType << LHS.get()->getSourceRange()
  7609. << RHS.get()->getSourceRange();
  7610. }
  7611. if (LHSIsNull && !RHSIsNull)
  7612. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7613. RHSType->isPointerType() ? CK_BitCast
  7614. : CK_AnyPointerToBlockPointerCast);
  7615. else
  7616. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7617. LHSType->isPointerType() ? CK_BitCast
  7618. : CK_AnyPointerToBlockPointerCast);
  7619. return ResultTy;
  7620. }
  7621. if (LHSType->isObjCObjectPointerType() ||
  7622. RHSType->isObjCObjectPointerType()) {
  7623. const PointerType *LPT = LHSType->getAs<PointerType>();
  7624. const PointerType *RPT = RHSType->getAs<PointerType>();
  7625. if (LPT || RPT) {
  7626. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7627. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7628. if (!LPtrToVoid && !RPtrToVoid &&
  7629. !Context.typesAreCompatible(LHSType, RHSType)) {
  7630. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7631. /*isError*/false);
  7632. }
  7633. if (LHSIsNull && !RHSIsNull) {
  7634. Expr *E = LHS.get();
  7635. if (getLangOpts().ObjCAutoRefCount)
  7636. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7637. LHS = ImpCastExprToType(E, RHSType,
  7638. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7639. }
  7640. else {
  7641. Expr *E = RHS.get();
  7642. if (getLangOpts().ObjCAutoRefCount)
  7643. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7644. Opc);
  7645. RHS = ImpCastExprToType(E, LHSType,
  7646. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7647. }
  7648. return ResultTy;
  7649. }
  7650. if (LHSType->isObjCObjectPointerType() &&
  7651. RHSType->isObjCObjectPointerType()) {
  7652. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7653. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7654. /*isError*/false);
  7655. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7656. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7657. if (LHSIsNull && !RHSIsNull)
  7658. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7659. else
  7660. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7661. return ResultTy;
  7662. }
  7663. }
  7664. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7665. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7666. unsigned DiagID = 0;
  7667. bool isError = false;
  7668. if (LangOpts.DebuggerSupport) {
  7669. // Under a debugger, allow the comparison of pointers to integers,
  7670. // since users tend to want to compare addresses.
  7671. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7672. (RHSIsNull && RHSType->isIntegerType())) {
  7673. if (IsRelational && !getLangOpts().CPlusPlus)
  7674. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7675. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7676. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7677. else if (getLangOpts().CPlusPlus) {
  7678. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7679. isError = true;
  7680. } else
  7681. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7682. if (DiagID) {
  7683. Diag(Loc, DiagID)
  7684. << LHSType << RHSType << LHS.get()->getSourceRange()
  7685. << RHS.get()->getSourceRange();
  7686. if (isError)
  7687. return QualType();
  7688. }
  7689. if (LHSType->isIntegerType())
  7690. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7691. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7692. else
  7693. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7694. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7695. return ResultTy;
  7696. }
  7697. // Handle block pointers.
  7698. if (!IsRelational && RHSIsNull
  7699. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7700. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7701. return ResultTy;
  7702. }
  7703. if (!IsRelational && LHSIsNull
  7704. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7705. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7706. return ResultTy;
  7707. }
  7708. return InvalidOperands(Loc, LHS, RHS);
  7709. }
  7710. // Return a signed type that is of identical size and number of elements.
  7711. // For floating point vectors, return an integer type of identical size
  7712. // and number of elements.
  7713. QualType Sema::GetSignedVectorType(QualType V) {
  7714. const VectorType *VTy = V->getAs<VectorType>();
  7715. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7716. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7717. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7718. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7719. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7720. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7721. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7722. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7723. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7724. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7725. "Unhandled vector element size in vector compare");
  7726. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7727. }
  7728. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7729. /// operates on extended vector types. Instead of producing an IntTy result,
  7730. /// like a scalar comparison, a vector comparison produces a vector of integer
  7731. /// types.
  7732. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7733. SourceLocation Loc,
  7734. bool IsRelational) {
  7735. // Check to make sure we're operating on vectors of the same type and width,
  7736. // Allowing one side to be a scalar of element type.
  7737. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  7738. /*AllowBothBool*/true,
  7739. /*AllowBoolConversions*/getLangOpts().ZVector);
  7740. if (vType.isNull())
  7741. return vType;
  7742. QualType LHSType = LHS.get()->getType();
  7743. // If AltiVec, the comparison results in a numeric type, i.e.
  7744. // bool for C++, int for C
  7745. if (getLangOpts().AltiVec &&
  7746. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7747. return Context.getLogicalOperationType();
  7748. // For non-floating point types, check for self-comparisons of the form
  7749. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7750. // often indicate logic errors in the program.
  7751. if (!LHSType->hasFloatingRepresentation() &&
  7752. ActiveTemplateInstantiations.empty()) {
  7753. if (DeclRefExpr* DRL
  7754. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7755. if (DeclRefExpr* DRR
  7756. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7757. if (DRL->getDecl() == DRR->getDecl())
  7758. DiagRuntimeBehavior(Loc, nullptr,
  7759. PDiag(diag::warn_comparison_always)
  7760. << 0 // self-
  7761. << 2 // "a constant"
  7762. );
  7763. }
  7764. // Check for comparisons of floating point operands using != and ==.
  7765. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7766. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7767. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7768. }
  7769. // Return a signed type for the vector.
  7770. return GetSignedVectorType(LHSType);
  7771. }
  7772. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7773. SourceLocation Loc) {
  7774. // Ensure that either both operands are of the same vector type, or
  7775. // one operand is of a vector type and the other is of its element type.
  7776. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  7777. /*AllowBothBool*/true,
  7778. /*AllowBoolConversions*/false);
  7779. if (vType.isNull())
  7780. return InvalidOperands(Loc, LHS, RHS);
  7781. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7782. vType->hasFloatingRepresentation())
  7783. return InvalidOperands(Loc, LHS, RHS);
  7784. return GetSignedVectorType(LHS.get()->getType());
  7785. }
  7786. inline QualType Sema::CheckBitwiseOperands(
  7787. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7788. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7789. if (LHS.get()->getType()->isVectorType() ||
  7790. RHS.get()->getType()->isVectorType()) {
  7791. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7792. RHS.get()->getType()->hasIntegerRepresentation())
  7793. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7794. /*AllowBothBool*/true,
  7795. /*AllowBoolConversions*/getLangOpts().ZVector);
  7796. return InvalidOperands(Loc, LHS, RHS);
  7797. }
  7798. ExprResult LHSResult = LHS, RHSResult = RHS;
  7799. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  7800. IsCompAssign);
  7801. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  7802. return QualType();
  7803. LHS = LHSResult.get();
  7804. RHS = RHSResult.get();
  7805. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  7806. return compType;
  7807. return InvalidOperands(Loc, LHS, RHS);
  7808. }
  7809. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  7810. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  7811. // Check vector operands differently.
  7812. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  7813. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  7814. // Diagnose cases where the user write a logical and/or but probably meant a
  7815. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  7816. // is a constant.
  7817. if (LHS.get()->getType()->isIntegerType() &&
  7818. !LHS.get()->getType()->isBooleanType() &&
  7819. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  7820. // Don't warn in macros or template instantiations.
  7821. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  7822. // If the RHS can be constant folded, and if it constant folds to something
  7823. // that isn't 0 or 1 (which indicate a potential logical operation that
  7824. // happened to fold to true/false) then warn.
  7825. // Parens on the RHS are ignored.
  7826. llvm::APSInt Result;
  7827. if (RHS.get()->EvaluateAsInt(Result, Context))
  7828. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  7829. !RHS.get()->getExprLoc().isMacroID()) ||
  7830. (Result != 0 && Result != 1)) {
  7831. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  7832. << RHS.get()->getSourceRange()
  7833. << (Opc == BO_LAnd ? "&&" : "||");
  7834. // Suggest replacing the logical operator with the bitwise version
  7835. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  7836. << (Opc == BO_LAnd ? "&" : "|")
  7837. << FixItHint::CreateReplacement(SourceRange(
  7838. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  7839. getLangOpts())),
  7840. Opc == BO_LAnd ? "&" : "|");
  7841. if (Opc == BO_LAnd)
  7842. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  7843. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  7844. << FixItHint::CreateRemoval(
  7845. SourceRange(
  7846. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  7847. 0, getSourceManager(),
  7848. getLangOpts()),
  7849. RHS.get()->getLocEnd()));
  7850. }
  7851. }
  7852. if (!Context.getLangOpts().CPlusPlus) {
  7853. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  7854. // not operate on the built-in scalar and vector float types.
  7855. if (Context.getLangOpts().OpenCL &&
  7856. Context.getLangOpts().OpenCLVersion < 120) {
  7857. if (LHS.get()->getType()->isFloatingType() ||
  7858. RHS.get()->getType()->isFloatingType())
  7859. return InvalidOperands(Loc, LHS, RHS);
  7860. }
  7861. LHS = UsualUnaryConversions(LHS.get());
  7862. if (LHS.isInvalid())
  7863. return QualType();
  7864. RHS = UsualUnaryConversions(RHS.get());
  7865. if (RHS.isInvalid())
  7866. return QualType();
  7867. if (!LHS.get()->getType()->isScalarType() ||
  7868. !RHS.get()->getType()->isScalarType())
  7869. return InvalidOperands(Loc, LHS, RHS);
  7870. return Context.IntTy;
  7871. }
  7872. // The following is safe because we only use this method for
  7873. // non-overloadable operands.
  7874. // C++ [expr.log.and]p1
  7875. // C++ [expr.log.or]p1
  7876. // The operands are both contextually converted to type bool.
  7877. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  7878. if (LHSRes.isInvalid())
  7879. return InvalidOperands(Loc, LHS, RHS);
  7880. LHS = LHSRes;
  7881. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  7882. if (RHSRes.isInvalid())
  7883. return InvalidOperands(Loc, LHS, RHS);
  7884. RHS = RHSRes;
  7885. // C++ [expr.log.and]p2
  7886. // C++ [expr.log.or]p2
  7887. // The result is a bool.
  7888. return Context.BoolTy;
  7889. }
  7890. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  7891. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  7892. if (!ME) return false;
  7893. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  7894. ObjCMessageExpr *Base =
  7895. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  7896. if (!Base) return false;
  7897. return Base->getMethodDecl() != nullptr;
  7898. }
  7899. /// Is the given expression (which must be 'const') a reference to a
  7900. /// variable which was originally non-const, but which has become
  7901. /// 'const' due to being captured within a block?
  7902. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  7903. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  7904. assert(E->isLValue() && E->getType().isConstQualified());
  7905. E = E->IgnoreParens();
  7906. // Must be a reference to a declaration from an enclosing scope.
  7907. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  7908. if (!DRE) return NCCK_None;
  7909. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  7910. // The declaration must be a variable which is not declared 'const'.
  7911. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  7912. if (!var) return NCCK_None;
  7913. if (var->getType().isConstQualified()) return NCCK_None;
  7914. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  7915. // Decide whether the first capture was for a block or a lambda.
  7916. DeclContext *DC = S.CurContext, *Prev = nullptr;
  7917. while (DC != var->getDeclContext()) {
  7918. Prev = DC;
  7919. DC = DC->getParent();
  7920. }
  7921. // Unless we have an init-capture, we've gone one step too far.
  7922. if (!var->isInitCapture())
  7923. DC = Prev;
  7924. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  7925. }
  7926. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  7927. Ty = Ty.getNonReferenceType();
  7928. if (IsDereference && Ty->isPointerType())
  7929. Ty = Ty->getPointeeType();
  7930. return !Ty.isConstQualified();
  7931. }
  7932. /// Emit the "read-only variable not assignable" error and print notes to give
  7933. /// more information about why the variable is not assignable, such as pointing
  7934. /// to the declaration of a const variable, showing that a method is const, or
  7935. /// that the function is returning a const reference.
  7936. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  7937. SourceLocation Loc) {
  7938. // Update err_typecheck_assign_const and note_typecheck_assign_const
  7939. // when this enum is changed.
  7940. enum {
  7941. ConstFunction,
  7942. ConstVariable,
  7943. ConstMember,
  7944. ConstMethod,
  7945. ConstUnknown, // Keep as last element
  7946. };
  7947. SourceRange ExprRange = E->getSourceRange();
  7948. // Only emit one error on the first const found. All other consts will emit
  7949. // a note to the error.
  7950. bool DiagnosticEmitted = false;
  7951. // Track if the current expression is the result of a derefence, and if the
  7952. // next checked expression is the result of a derefence.
  7953. bool IsDereference = false;
  7954. bool NextIsDereference = false;
  7955. // Loop to process MemberExpr chains.
  7956. while (true) {
  7957. IsDereference = NextIsDereference;
  7958. NextIsDereference = false;
  7959. E = E->IgnoreParenImpCasts();
  7960. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  7961. NextIsDereference = ME->isArrow();
  7962. const ValueDecl *VD = ME->getMemberDecl();
  7963. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  7964. // Mutable fields can be modified even if the class is const.
  7965. if (Field->isMutable()) {
  7966. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  7967. break;
  7968. }
  7969. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  7970. if (!DiagnosticEmitted) {
  7971. S.Diag(Loc, diag::err_typecheck_assign_const)
  7972. << ExprRange << ConstMember << false /*static*/ << Field
  7973. << Field->getType();
  7974. DiagnosticEmitted = true;
  7975. }
  7976. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  7977. << ConstMember << false /*static*/ << Field << Field->getType()
  7978. << Field->getSourceRange();
  7979. }
  7980. E = ME->getBase();
  7981. continue;
  7982. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  7983. if (VDecl->getType().isConstQualified()) {
  7984. if (!DiagnosticEmitted) {
  7985. S.Diag(Loc, diag::err_typecheck_assign_const)
  7986. << ExprRange << ConstMember << true /*static*/ << VDecl
  7987. << VDecl->getType();
  7988. DiagnosticEmitted = true;
  7989. }
  7990. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  7991. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  7992. << VDecl->getSourceRange();
  7993. }
  7994. // Static fields do not inherit constness from parents.
  7995. break;
  7996. }
  7997. break;
  7998. } // End MemberExpr
  7999. break;
  8000. }
  8001. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8002. // Function calls
  8003. const FunctionDecl *FD = CE->getDirectCallee();
  8004. if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  8005. if (!DiagnosticEmitted) {
  8006. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8007. << ConstFunction << FD;
  8008. DiagnosticEmitted = true;
  8009. }
  8010. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  8011. diag::note_typecheck_assign_const)
  8012. << ConstFunction << FD << FD->getReturnType()
  8013. << FD->getReturnTypeSourceRange();
  8014. }
  8015. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8016. // Point to variable declaration.
  8017. if (const ValueDecl *VD = DRE->getDecl()) {
  8018. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  8019. if (!DiagnosticEmitted) {
  8020. S.Diag(Loc, diag::err_typecheck_assign_const)
  8021. << ExprRange << ConstVariable << VD << VD->getType();
  8022. DiagnosticEmitted = true;
  8023. }
  8024. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8025. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  8026. }
  8027. }
  8028. } else if (isa<CXXThisExpr>(E)) {
  8029. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  8030. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  8031. if (MD->isConst()) {
  8032. if (!DiagnosticEmitted) {
  8033. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8034. << ConstMethod << MD;
  8035. DiagnosticEmitted = true;
  8036. }
  8037. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  8038. << ConstMethod << MD << MD->getSourceRange();
  8039. }
  8040. }
  8041. }
  8042. }
  8043. if (DiagnosticEmitted)
  8044. return;
  8045. // Can't determine a more specific message, so display the generic error.
  8046. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  8047. }
  8048. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  8049. /// emit an error and return true. If so, return false.
  8050. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  8051. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  8052. SourceLocation OrigLoc = Loc;
  8053. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  8054. &Loc);
  8055. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  8056. IsLV = Expr::MLV_InvalidMessageExpression;
  8057. if (IsLV == Expr::MLV_Valid)
  8058. return false;
  8059. unsigned DiagID = 0;
  8060. bool NeedType = false;
  8061. switch (IsLV) { // C99 6.5.16p2
  8062. case Expr::MLV_ConstQualified:
  8063. // Use a specialized diagnostic when we're assigning to an object
  8064. // from an enclosing function or block.
  8065. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  8066. if (NCCK == NCCK_Block)
  8067. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  8068. else
  8069. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  8070. break;
  8071. }
  8072. // In ARC, use some specialized diagnostics for occasions where we
  8073. // infer 'const'. These are always pseudo-strong variables.
  8074. if (S.getLangOpts().ObjCAutoRefCount) {
  8075. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  8076. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  8077. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  8078. // Use the normal diagnostic if it's pseudo-__strong but the
  8079. // user actually wrote 'const'.
  8080. if (var->isARCPseudoStrong() &&
  8081. (!var->getTypeSourceInfo() ||
  8082. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  8083. // There are two pseudo-strong cases:
  8084. // - self
  8085. ObjCMethodDecl *method = S.getCurMethodDecl();
  8086. if (method && var == method->getSelfDecl())
  8087. DiagID = method->isClassMethod()
  8088. ? diag::err_typecheck_arc_assign_self_class_method
  8089. : diag::err_typecheck_arc_assign_self;
  8090. // - fast enumeration variables
  8091. else
  8092. DiagID = diag::err_typecheck_arr_assign_enumeration;
  8093. SourceRange Assign;
  8094. if (Loc != OrigLoc)
  8095. Assign = SourceRange(OrigLoc, OrigLoc);
  8096. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8097. // We need to preserve the AST regardless, so migration tool
  8098. // can do its job.
  8099. return false;
  8100. }
  8101. }
  8102. }
  8103. // If none of the special cases above are triggered, then this is a
  8104. // simple const assignment.
  8105. if (DiagID == 0) {
  8106. DiagnoseConstAssignment(S, E, Loc);
  8107. return true;
  8108. }
  8109. break;
  8110. case Expr::MLV_ConstAddrSpace:
  8111. DiagnoseConstAssignment(S, E, Loc);
  8112. return true;
  8113. case Expr::MLV_ArrayType:
  8114. case Expr::MLV_ArrayTemporary:
  8115. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  8116. NeedType = true;
  8117. break;
  8118. case Expr::MLV_NotObjectType:
  8119. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  8120. NeedType = true;
  8121. break;
  8122. case Expr::MLV_LValueCast:
  8123. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  8124. break;
  8125. case Expr::MLV_Valid:
  8126. llvm_unreachable("did not take early return for MLV_Valid");
  8127. case Expr::MLV_InvalidExpression:
  8128. case Expr::MLV_MemberFunction:
  8129. case Expr::MLV_ClassTemporary:
  8130. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  8131. break;
  8132. case Expr::MLV_IncompleteType:
  8133. case Expr::MLV_IncompleteVoidType:
  8134. return S.RequireCompleteType(Loc, E->getType(),
  8135. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  8136. case Expr::MLV_DuplicateVectorComponents:
  8137. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  8138. break;
  8139. case Expr::MLV_NoSetterProperty:
  8140. llvm_unreachable("readonly properties should be processed differently");
  8141. case Expr::MLV_InvalidMessageExpression:
  8142. DiagID = diag::error_readonly_message_assignment;
  8143. break;
  8144. case Expr::MLV_SubObjCPropertySetting:
  8145. DiagID = diag::error_no_subobject_property_setting;
  8146. break;
  8147. }
  8148. SourceRange Assign;
  8149. if (Loc != OrigLoc)
  8150. Assign = SourceRange(OrigLoc, OrigLoc);
  8151. if (NeedType)
  8152. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  8153. else
  8154. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8155. return true;
  8156. }
  8157. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  8158. SourceLocation Loc,
  8159. Sema &Sema) {
  8160. // C / C++ fields
  8161. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  8162. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  8163. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  8164. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  8165. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  8166. }
  8167. // Objective-C instance variables
  8168. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  8169. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  8170. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  8171. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  8172. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  8173. if (RL && RR && RL->getDecl() == RR->getDecl())
  8174. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  8175. }
  8176. }
  8177. // C99 6.5.16.1
  8178. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  8179. SourceLocation Loc,
  8180. QualType CompoundType) {
  8181. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  8182. // Verify that LHS is a modifiable lvalue, and emit error if not.
  8183. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  8184. return QualType();
  8185. QualType LHSType = LHSExpr->getType();
  8186. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  8187. CompoundType;
  8188. AssignConvertType ConvTy;
  8189. if (CompoundType.isNull()) {
  8190. Expr *RHSCheck = RHS.get();
  8191. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  8192. QualType LHSTy(LHSType);
  8193. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  8194. if (RHS.isInvalid())
  8195. return QualType();
  8196. // Special case of NSObject attributes on c-style pointer types.
  8197. if (ConvTy == IncompatiblePointer &&
  8198. ((Context.isObjCNSObjectType(LHSType) &&
  8199. RHSType->isObjCObjectPointerType()) ||
  8200. (Context.isObjCNSObjectType(RHSType) &&
  8201. LHSType->isObjCObjectPointerType())))
  8202. ConvTy = Compatible;
  8203. if (ConvTy == Compatible &&
  8204. LHSType->isObjCObjectType())
  8205. Diag(Loc, diag::err_objc_object_assignment)
  8206. << LHSType;
  8207. // If the RHS is a unary plus or minus, check to see if they = and + are
  8208. // right next to each other. If so, the user may have typo'd "x =+ 4"
  8209. // instead of "x += 4".
  8210. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  8211. RHSCheck = ICE->getSubExpr();
  8212. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  8213. if ((UO->getOpcode() == UO_Plus ||
  8214. UO->getOpcode() == UO_Minus) &&
  8215. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  8216. // Only if the two operators are exactly adjacent.
  8217. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  8218. // And there is a space or other character before the subexpr of the
  8219. // unary +/-. We don't want to warn on "x=-1".
  8220. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  8221. UO->getSubExpr()->getLocStart().isFileID()) {
  8222. Diag(Loc, diag::warn_not_compound_assign)
  8223. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  8224. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  8225. }
  8226. }
  8227. if (ConvTy == Compatible) {
  8228. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  8229. // Warn about retain cycles where a block captures the LHS, but
  8230. // not if the LHS is a simple variable into which the block is
  8231. // being stored...unless that variable can be captured by reference!
  8232. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  8233. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  8234. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  8235. checkRetainCycles(LHSExpr, RHS.get());
  8236. // It is safe to assign a weak reference into a strong variable.
  8237. // Although this code can still have problems:
  8238. // id x = self.weakProp;
  8239. // id y = self.weakProp;
  8240. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8241. // paths through the function. This should be revisited if
  8242. // -Wrepeated-use-of-weak is made flow-sensitive.
  8243. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8244. RHS.get()->getLocStart()))
  8245. getCurFunction()->markSafeWeakUse(RHS.get());
  8246. } else if (getLangOpts().ObjCAutoRefCount) {
  8247. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  8248. }
  8249. }
  8250. } else {
  8251. // Compound assignment "x += y"
  8252. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  8253. }
  8254. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  8255. RHS.get(), AA_Assigning))
  8256. return QualType();
  8257. CheckForNullPointerDereference(*this, LHSExpr);
  8258. // C99 6.5.16p3: The type of an assignment expression is the type of the
  8259. // left operand unless the left operand has qualified type, in which case
  8260. // it is the unqualified version of the type of the left operand.
  8261. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  8262. // is converted to the type of the assignment expression (above).
  8263. // C++ 5.17p1: the type of the assignment expression is that of its left
  8264. // operand.
  8265. return (getLangOpts().CPlusPlus
  8266. ? LHSType : LHSType.getUnqualifiedType());
  8267. }
  8268. // C99 6.5.17
  8269. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8270. SourceLocation Loc) {
  8271. LHS = S.CheckPlaceholderExpr(LHS.get());
  8272. RHS = S.CheckPlaceholderExpr(RHS.get());
  8273. if (LHS.isInvalid() || RHS.isInvalid())
  8274. return QualType();
  8275. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  8276. // operands, but not unary promotions.
  8277. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  8278. // So we treat the LHS as a ignored value, and in C++ we allow the
  8279. // containing site to determine what should be done with the RHS.
  8280. LHS = S.IgnoredValueConversions(LHS.get());
  8281. if (LHS.isInvalid())
  8282. return QualType();
  8283. S.DiagnoseUnusedExprResult(LHS.get());
  8284. if (!S.getLangOpts().CPlusPlus) {
  8285. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  8286. if (RHS.isInvalid())
  8287. return QualType();
  8288. if (!RHS.get()->getType()->isVoidType())
  8289. S.RequireCompleteType(Loc, RHS.get()->getType(),
  8290. diag::err_incomplete_type);
  8291. }
  8292. return RHS.get()->getType();
  8293. }
  8294. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  8295. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  8296. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  8297. ExprValueKind &VK,
  8298. ExprObjectKind &OK,
  8299. SourceLocation OpLoc,
  8300. bool IsInc, bool IsPrefix) {
  8301. if (Op->isTypeDependent())
  8302. return S.Context.DependentTy;
  8303. QualType ResType = Op->getType();
  8304. // Atomic types can be used for increment / decrement where the non-atomic
  8305. // versions can, so ignore the _Atomic() specifier for the purpose of
  8306. // checking.
  8307. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8308. ResType = ResAtomicType->getValueType();
  8309. assert(!ResType.isNull() && "no type for increment/decrement expression");
  8310. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  8311. // Decrement of bool is not allowed.
  8312. if (!IsInc) {
  8313. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  8314. return QualType();
  8315. }
  8316. // Increment of bool sets it to true, but is deprecated.
  8317. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  8318. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  8319. // Error on enum increments and decrements in C++ mode
  8320. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  8321. return QualType();
  8322. } else if (ResType->isRealType()) {
  8323. // OK!
  8324. } else if (ResType->isPointerType()) {
  8325. // C99 6.5.2.4p2, 6.5.6p2
  8326. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  8327. return QualType();
  8328. } else if (ResType->isObjCObjectPointerType()) {
  8329. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  8330. // Otherwise, we just need a complete type.
  8331. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  8332. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  8333. return QualType();
  8334. } else if (ResType->isAnyComplexType()) {
  8335. // C99 does not support ++/-- on complex types, we allow as an extension.
  8336. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8337. << ResType << Op->getSourceRange();
  8338. } else if (ResType->isPlaceholderType()) {
  8339. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8340. if (PR.isInvalid()) return QualType();
  8341. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8342. IsInc, IsPrefix);
  8343. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8344. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8345. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  8346. (ResType->getAs<VectorType>()->getVectorKind() !=
  8347. VectorType::AltiVecBool)) {
  8348. // The z vector extensions allow ++ and -- for non-bool vectors.
  8349. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8350. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8351. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8352. } else {
  8353. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8354. << ResType << int(IsInc) << Op->getSourceRange();
  8355. return QualType();
  8356. }
  8357. // At this point, we know we have a real, complex or pointer type.
  8358. // Now make sure the operand is a modifiable lvalue.
  8359. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8360. return QualType();
  8361. // In C++, a prefix increment is the same type as the operand. Otherwise
  8362. // (in C or with postfix), the increment is the unqualified type of the
  8363. // operand.
  8364. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8365. VK = VK_LValue;
  8366. OK = Op->getObjectKind();
  8367. return ResType;
  8368. } else {
  8369. VK = VK_RValue;
  8370. return ResType.getUnqualifiedType();
  8371. }
  8372. }
  8373. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8374. /// This routine allows us to typecheck complex/recursive expressions
  8375. /// where the declaration is needed for type checking. We only need to
  8376. /// handle cases when the expression references a function designator
  8377. /// or is an lvalue. Here are some examples:
  8378. /// - &(x) => x
  8379. /// - &*****f => f for f a function designator.
  8380. /// - &s.xx => s
  8381. /// - &s.zz[1].yy -> s, if zz is an array
  8382. /// - *(x + 1) -> x, if x is an array
  8383. /// - &"123"[2] -> 0
  8384. /// - & __real__ x -> x
  8385. static ValueDecl *getPrimaryDecl(Expr *E) {
  8386. switch (E->getStmtClass()) {
  8387. case Stmt::DeclRefExprClass:
  8388. return cast<DeclRefExpr>(E)->getDecl();
  8389. case Stmt::MemberExprClass:
  8390. // If this is an arrow operator, the address is an offset from
  8391. // the base's value, so the object the base refers to is
  8392. // irrelevant.
  8393. if (cast<MemberExpr>(E)->isArrow())
  8394. return nullptr;
  8395. // Otherwise, the expression refers to a part of the base
  8396. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8397. case Stmt::ArraySubscriptExprClass: {
  8398. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8399. // promotion of register arrays earlier.
  8400. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8401. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8402. if (ICE->getSubExpr()->getType()->isArrayType())
  8403. return getPrimaryDecl(ICE->getSubExpr());
  8404. }
  8405. return nullptr;
  8406. }
  8407. case Stmt::UnaryOperatorClass: {
  8408. UnaryOperator *UO = cast<UnaryOperator>(E);
  8409. switch(UO->getOpcode()) {
  8410. case UO_Real:
  8411. case UO_Imag:
  8412. case UO_Extension:
  8413. return getPrimaryDecl(UO->getSubExpr());
  8414. default:
  8415. return nullptr;
  8416. }
  8417. }
  8418. case Stmt::ParenExprClass:
  8419. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8420. case Stmt::ImplicitCastExprClass:
  8421. // If the result of an implicit cast is an l-value, we care about
  8422. // the sub-expression; otherwise, the result here doesn't matter.
  8423. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8424. default:
  8425. return nullptr;
  8426. }
  8427. }
  8428. namespace {
  8429. enum {
  8430. AO_Bit_Field = 0,
  8431. AO_Vector_Element = 1,
  8432. AO_Property_Expansion = 2,
  8433. AO_Register_Variable = 3,
  8434. AO_No_Error = 4
  8435. };
  8436. }
  8437. /// \brief Diagnose invalid operand for address of operations.
  8438. ///
  8439. /// \param Type The type of operand which cannot have its address taken.
  8440. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8441. Expr *E, unsigned Type) {
  8442. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8443. }
  8444. /// CheckAddressOfOperand - The operand of & must be either a function
  8445. /// designator or an lvalue designating an object. If it is an lvalue, the
  8446. /// object cannot be declared with storage class register or be a bit field.
  8447. /// Note: The usual conversions are *not* applied to the operand of the &
  8448. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8449. /// In C++, the operand might be an overloaded function name, in which case
  8450. /// we allow the '&' but retain the overloaded-function type.
  8451. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8452. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8453. if (PTy->getKind() == BuiltinType::Overload) {
  8454. Expr *E = OrigOp.get()->IgnoreParens();
  8455. if (!isa<OverloadExpr>(E)) {
  8456. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8457. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8458. << OrigOp.get()->getSourceRange();
  8459. return QualType();
  8460. }
  8461. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8462. if (isa<UnresolvedMemberExpr>(Ovl))
  8463. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8464. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8465. << OrigOp.get()->getSourceRange();
  8466. return QualType();
  8467. }
  8468. return Context.OverloadTy;
  8469. }
  8470. if (PTy->getKind() == BuiltinType::UnknownAny)
  8471. return Context.UnknownAnyTy;
  8472. if (PTy->getKind() == BuiltinType::BoundMember) {
  8473. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8474. << OrigOp.get()->getSourceRange();
  8475. return QualType();
  8476. }
  8477. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8478. if (OrigOp.isInvalid()) return QualType();
  8479. }
  8480. if (OrigOp.get()->isTypeDependent())
  8481. return Context.DependentTy;
  8482. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8483. // Make sure to ignore parentheses in subsequent checks
  8484. Expr *op = OrigOp.get()->IgnoreParens();
  8485. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8486. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8487. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8488. return QualType();
  8489. }
  8490. if (getLangOpts().C99) {
  8491. // Implement C99-only parts of addressof rules.
  8492. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8493. if (uOp->getOpcode() == UO_Deref)
  8494. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8495. // (assuming the deref expression is valid).
  8496. return uOp->getSubExpr()->getType();
  8497. }
  8498. // Technically, there should be a check for array subscript
  8499. // expressions here, but the result of one is always an lvalue anyway.
  8500. }
  8501. ValueDecl *dcl = getPrimaryDecl(op);
  8502. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8503. unsigned AddressOfError = AO_No_Error;
  8504. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8505. bool sfinae = (bool)isSFINAEContext();
  8506. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8507. : diag::ext_typecheck_addrof_temporary)
  8508. << op->getType() << op->getSourceRange();
  8509. if (sfinae)
  8510. return QualType();
  8511. // Materialize the temporary as an lvalue so that we can take its address.
  8512. OrigOp = op = new (Context)
  8513. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8514. } else if (isa<ObjCSelectorExpr>(op)) {
  8515. return Context.getPointerType(op->getType());
  8516. } else if (lval == Expr::LV_MemberFunction) {
  8517. // If it's an instance method, make a member pointer.
  8518. // The expression must have exactly the form &A::foo.
  8519. // If the underlying expression isn't a decl ref, give up.
  8520. if (!isa<DeclRefExpr>(op)) {
  8521. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8522. << OrigOp.get()->getSourceRange();
  8523. return QualType();
  8524. }
  8525. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8526. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8527. // The id-expression was parenthesized.
  8528. if (OrigOp.get() != DRE) {
  8529. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8530. << OrigOp.get()->getSourceRange();
  8531. // The method was named without a qualifier.
  8532. } else if (!DRE->getQualifier()) {
  8533. if (MD->getParent()->getName().empty())
  8534. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8535. << op->getSourceRange();
  8536. else {
  8537. SmallString<32> Str;
  8538. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8539. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8540. << op->getSourceRange()
  8541. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8542. }
  8543. }
  8544. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8545. if (isa<CXXDestructorDecl>(MD))
  8546. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8547. QualType MPTy = Context.getMemberPointerType(
  8548. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8549. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8550. RequireCompleteType(OpLoc, MPTy, 0);
  8551. return MPTy;
  8552. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8553. // C99 6.5.3.2p1
  8554. // The operand must be either an l-value or a function designator
  8555. if (!op->getType()->isFunctionType()) {
  8556. // Use a special diagnostic for loads from property references.
  8557. if (isa<PseudoObjectExpr>(op)) {
  8558. AddressOfError = AO_Property_Expansion;
  8559. } else {
  8560. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8561. << op->getType() << op->getSourceRange();
  8562. return QualType();
  8563. }
  8564. }
  8565. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8566. // The operand cannot be a bit-field
  8567. AddressOfError = AO_Bit_Field;
  8568. } else if (op->getObjectKind() == OK_VectorComponent) {
  8569. // The operand cannot be an element of a vector
  8570. AddressOfError = AO_Vector_Element;
  8571. } else if (dcl) { // C99 6.5.3.2p1
  8572. // We have an lvalue with a decl. Make sure the decl is not declared
  8573. // with the register storage-class specifier.
  8574. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8575. // in C++ it is not error to take address of a register
  8576. // variable (c++03 7.1.1P3)
  8577. if (vd->getStorageClass() == SC_Register &&
  8578. !getLangOpts().CPlusPlus) {
  8579. AddressOfError = AO_Register_Variable;
  8580. }
  8581. } else if (isa<MSPropertyDecl>(dcl)) {
  8582. AddressOfError = AO_Property_Expansion;
  8583. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8584. return Context.OverloadTy;
  8585. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8586. // Okay: we can take the address of a field.
  8587. // Could be a pointer to member, though, if there is an explicit
  8588. // scope qualifier for the class.
  8589. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8590. DeclContext *Ctx = dcl->getDeclContext();
  8591. if (Ctx && Ctx->isRecord()) {
  8592. if (dcl->getType()->isReferenceType()) {
  8593. Diag(OpLoc,
  8594. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8595. << dcl->getDeclName() << dcl->getType();
  8596. return QualType();
  8597. }
  8598. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8599. Ctx = Ctx->getParent();
  8600. QualType MPTy = Context.getMemberPointerType(
  8601. op->getType(),
  8602. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8603. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8604. RequireCompleteType(OpLoc, MPTy, 0);
  8605. return MPTy;
  8606. }
  8607. }
  8608. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8609. llvm_unreachable("Unknown/unexpected decl type");
  8610. }
  8611. if (AddressOfError != AO_No_Error) {
  8612. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8613. return QualType();
  8614. }
  8615. if (lval == Expr::LV_IncompleteVoidType) {
  8616. // Taking the address of a void variable is technically illegal, but we
  8617. // allow it in cases which are otherwise valid.
  8618. // Example: "extern void x; void* y = &x;".
  8619. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8620. }
  8621. // If the operand has type "type", the result has type "pointer to type".
  8622. if (op->getType()->isObjCObjectType())
  8623. return Context.getObjCObjectPointerType(op->getType());
  8624. return Context.getPointerType(op->getType());
  8625. }
  8626. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8627. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8628. if (!DRE)
  8629. return;
  8630. const Decl *D = DRE->getDecl();
  8631. if (!D)
  8632. return;
  8633. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8634. if (!Param)
  8635. return;
  8636. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8637. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8638. return;
  8639. if (FunctionScopeInfo *FD = S.getCurFunction())
  8640. if (!FD->ModifiedNonNullParams.count(Param))
  8641. FD->ModifiedNonNullParams.insert(Param);
  8642. }
  8643. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8644. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8645. SourceLocation OpLoc) {
  8646. if (Op->isTypeDependent())
  8647. return S.Context.DependentTy;
  8648. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8649. if (ConvResult.isInvalid())
  8650. return QualType();
  8651. Op = ConvResult.get();
  8652. QualType OpTy = Op->getType();
  8653. QualType Result;
  8654. if (isa<CXXReinterpretCastExpr>(Op)) {
  8655. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8656. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8657. Op->getSourceRange());
  8658. }
  8659. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8660. Result = PT->getPointeeType();
  8661. else if (const ObjCObjectPointerType *OPT =
  8662. OpTy->getAs<ObjCObjectPointerType>())
  8663. Result = OPT->getPointeeType();
  8664. else {
  8665. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8666. if (PR.isInvalid()) return QualType();
  8667. if (PR.get() != Op)
  8668. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8669. }
  8670. if (Result.isNull()) {
  8671. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8672. << OpTy << Op->getSourceRange();
  8673. return QualType();
  8674. }
  8675. // Note that per both C89 and C99, indirection is always legal, even if Result
  8676. // is an incomplete type or void. It would be possible to warn about
  8677. // dereferencing a void pointer, but it's completely well-defined, and such a
  8678. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8679. // for pointers to 'void' but is fine for any other pointer type:
  8680. //
  8681. // C++ [expr.unary.op]p1:
  8682. // [...] the expression to which [the unary * operator] is applied shall
  8683. // be a pointer to an object type, or a pointer to a function type
  8684. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8685. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8686. << OpTy << Op->getSourceRange();
  8687. // Dereferences are usually l-values...
  8688. VK = VK_LValue;
  8689. // ...except that certain expressions are never l-values in C.
  8690. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8691. VK = VK_RValue;
  8692. return Result;
  8693. }
  8694. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8695. BinaryOperatorKind Opc;
  8696. switch (Kind) {
  8697. default: llvm_unreachable("Unknown binop!");
  8698. case tok::periodstar: Opc = BO_PtrMemD; break;
  8699. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8700. case tok::star: Opc = BO_Mul; break;
  8701. case tok::slash: Opc = BO_Div; break;
  8702. case tok::percent: Opc = BO_Rem; break;
  8703. case tok::plus: Opc = BO_Add; break;
  8704. case tok::minus: Opc = BO_Sub; break;
  8705. case tok::lessless: Opc = BO_Shl; break;
  8706. case tok::greatergreater: Opc = BO_Shr; break;
  8707. case tok::lessequal: Opc = BO_LE; break;
  8708. case tok::less: Opc = BO_LT; break;
  8709. case tok::greaterequal: Opc = BO_GE; break;
  8710. case tok::greater: Opc = BO_GT; break;
  8711. case tok::exclaimequal: Opc = BO_NE; break;
  8712. case tok::equalequal: Opc = BO_EQ; break;
  8713. case tok::amp: Opc = BO_And; break;
  8714. case tok::caret: Opc = BO_Xor; break;
  8715. case tok::pipe: Opc = BO_Or; break;
  8716. case tok::ampamp: Opc = BO_LAnd; break;
  8717. case tok::pipepipe: Opc = BO_LOr; break;
  8718. case tok::equal: Opc = BO_Assign; break;
  8719. case tok::starequal: Opc = BO_MulAssign; break;
  8720. case tok::slashequal: Opc = BO_DivAssign; break;
  8721. case tok::percentequal: Opc = BO_RemAssign; break;
  8722. case tok::plusequal: Opc = BO_AddAssign; break;
  8723. case tok::minusequal: Opc = BO_SubAssign; break;
  8724. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8725. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8726. case tok::ampequal: Opc = BO_AndAssign; break;
  8727. case tok::caretequal: Opc = BO_XorAssign; break;
  8728. case tok::pipeequal: Opc = BO_OrAssign; break;
  8729. case tok::comma: Opc = BO_Comma; break;
  8730. }
  8731. return Opc;
  8732. }
  8733. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8734. tok::TokenKind Kind) {
  8735. UnaryOperatorKind Opc;
  8736. switch (Kind) {
  8737. default: llvm_unreachable("Unknown unary op!");
  8738. case tok::plusplus: Opc = UO_PreInc; break;
  8739. case tok::minusminus: Opc = UO_PreDec; break;
  8740. case tok::amp: Opc = UO_AddrOf; break;
  8741. case tok::star: Opc = UO_Deref; break;
  8742. case tok::plus: Opc = UO_Plus; break;
  8743. case tok::minus: Opc = UO_Minus; break;
  8744. case tok::tilde: Opc = UO_Not; break;
  8745. case tok::exclaim: Opc = UO_LNot; break;
  8746. case tok::kw___real: Opc = UO_Real; break;
  8747. case tok::kw___imag: Opc = UO_Imag; break;
  8748. case tok::kw___extension__: Opc = UO_Extension; break;
  8749. }
  8750. return Opc;
  8751. }
  8752. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8753. /// This warning is only emitted for builtin assignment operations. It is also
  8754. /// suppressed in the event of macro expansions.
  8755. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8756. SourceLocation OpLoc) {
  8757. if (!S.ActiveTemplateInstantiations.empty())
  8758. return;
  8759. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  8760. return;
  8761. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8762. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8763. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8764. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8765. if (!LHSDeclRef || !RHSDeclRef ||
  8766. LHSDeclRef->getLocation().isMacroID() ||
  8767. RHSDeclRef->getLocation().isMacroID())
  8768. return;
  8769. const ValueDecl *LHSDecl =
  8770. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  8771. const ValueDecl *RHSDecl =
  8772. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  8773. if (LHSDecl != RHSDecl)
  8774. return;
  8775. if (LHSDecl->getType().isVolatileQualified())
  8776. return;
  8777. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  8778. if (RefTy->getPointeeType().isVolatileQualified())
  8779. return;
  8780. S.Diag(OpLoc, diag::warn_self_assignment)
  8781. << LHSDeclRef->getType()
  8782. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8783. }
  8784. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  8785. /// is usually indicative of introspection within the Objective-C pointer.
  8786. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  8787. SourceLocation OpLoc) {
  8788. if (!S.getLangOpts().ObjC1)
  8789. return;
  8790. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  8791. const Expr *LHS = L.get();
  8792. const Expr *RHS = R.get();
  8793. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8794. ObjCPointerExpr = LHS;
  8795. OtherExpr = RHS;
  8796. }
  8797. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8798. ObjCPointerExpr = RHS;
  8799. OtherExpr = LHS;
  8800. }
  8801. // This warning is deliberately made very specific to reduce false
  8802. // positives with logic that uses '&' for hashing. This logic mainly
  8803. // looks for code trying to introspect into tagged pointers, which
  8804. // code should generally never do.
  8805. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  8806. unsigned Diag = diag::warn_objc_pointer_masking;
  8807. // Determine if we are introspecting the result of performSelectorXXX.
  8808. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  8809. // Special case messages to -performSelector and friends, which
  8810. // can return non-pointer values boxed in a pointer value.
  8811. // Some clients may wish to silence warnings in this subcase.
  8812. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  8813. Selector S = ME->getSelector();
  8814. StringRef SelArg0 = S.getNameForSlot(0);
  8815. if (SelArg0.startswith("performSelector"))
  8816. Diag = diag::warn_objc_pointer_masking_performSelector;
  8817. }
  8818. S.Diag(OpLoc, Diag)
  8819. << ObjCPointerExpr->getSourceRange();
  8820. }
  8821. }
  8822. static NamedDecl *getDeclFromExpr(Expr *E) {
  8823. if (!E)
  8824. return nullptr;
  8825. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  8826. return DRE->getDecl();
  8827. if (auto *ME = dyn_cast<MemberExpr>(E))
  8828. return ME->getMemberDecl();
  8829. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  8830. return IRE->getDecl();
  8831. return nullptr;
  8832. }
  8833. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  8834. /// operator @p Opc at location @c TokLoc. This routine only supports
  8835. /// built-in operations; ActOnBinOp handles overloaded operators.
  8836. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  8837. BinaryOperatorKind Opc,
  8838. Expr *LHSExpr, Expr *RHSExpr) {
  8839. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  8840. // The syntax only allows initializer lists on the RHS of assignment,
  8841. // so we don't need to worry about accepting invalid code for
  8842. // non-assignment operators.
  8843. // C++11 5.17p9:
  8844. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  8845. // of x = {} is x = T().
  8846. InitializationKind Kind =
  8847. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  8848. InitializedEntity Entity =
  8849. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  8850. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  8851. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  8852. if (Init.isInvalid())
  8853. return Init;
  8854. RHSExpr = Init.get();
  8855. }
  8856. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  8857. QualType ResultTy; // Result type of the binary operator.
  8858. // The following two variables are used for compound assignment operators
  8859. QualType CompLHSTy; // Type of LHS after promotions for computation
  8860. QualType CompResultTy; // Type of computation result
  8861. ExprValueKind VK = VK_RValue;
  8862. ExprObjectKind OK = OK_Ordinary;
  8863. if (!getLangOpts().CPlusPlus) {
  8864. // C cannot handle TypoExpr nodes on either side of a binop because it
  8865. // doesn't handle dependent types properly, so make sure any TypoExprs have
  8866. // been dealt with before checking the operands.
  8867. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  8868. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  8869. if (Opc != BO_Assign)
  8870. return ExprResult(E);
  8871. // Avoid correcting the RHS to the same Expr as the LHS.
  8872. Decl *D = getDeclFromExpr(E);
  8873. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  8874. });
  8875. if (!LHS.isUsable() || !RHS.isUsable())
  8876. return ExprError();
  8877. }
  8878. switch (Opc) {
  8879. case BO_Assign:
  8880. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  8881. if (getLangOpts().CPlusPlus &&
  8882. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  8883. VK = LHS.get()->getValueKind();
  8884. OK = LHS.get()->getObjectKind();
  8885. }
  8886. if (!ResultTy.isNull()) {
  8887. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  8888. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  8889. }
  8890. RecordModifiableNonNullParam(*this, LHS.get());
  8891. break;
  8892. case BO_PtrMemD:
  8893. case BO_PtrMemI:
  8894. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  8895. Opc == BO_PtrMemI);
  8896. break;
  8897. case BO_Mul:
  8898. case BO_Div:
  8899. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  8900. Opc == BO_Div);
  8901. break;
  8902. case BO_Rem:
  8903. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  8904. break;
  8905. case BO_Add:
  8906. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  8907. break;
  8908. case BO_Sub:
  8909. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  8910. break;
  8911. case BO_Shl:
  8912. case BO_Shr:
  8913. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  8914. break;
  8915. case BO_LE:
  8916. case BO_LT:
  8917. case BO_GE:
  8918. case BO_GT:
  8919. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  8920. break;
  8921. case BO_EQ:
  8922. case BO_NE:
  8923. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  8924. break;
  8925. case BO_And:
  8926. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  8927. case BO_Xor:
  8928. case BO_Or:
  8929. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  8930. break;
  8931. case BO_LAnd:
  8932. case BO_LOr:
  8933. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  8934. break;
  8935. case BO_MulAssign:
  8936. case BO_DivAssign:
  8937. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  8938. Opc == BO_DivAssign);
  8939. CompLHSTy = CompResultTy;
  8940. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8941. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8942. break;
  8943. case BO_RemAssign:
  8944. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  8945. CompLHSTy = CompResultTy;
  8946. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8947. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8948. break;
  8949. case BO_AddAssign:
  8950. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  8951. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8952. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8953. break;
  8954. case BO_SubAssign:
  8955. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  8956. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8957. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8958. break;
  8959. case BO_ShlAssign:
  8960. case BO_ShrAssign:
  8961. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  8962. CompLHSTy = CompResultTy;
  8963. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8964. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8965. break;
  8966. case BO_AndAssign:
  8967. case BO_OrAssign: // fallthrough
  8968. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  8969. case BO_XorAssign:
  8970. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  8971. CompLHSTy = CompResultTy;
  8972. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  8973. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  8974. break;
  8975. case BO_Comma:
  8976. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  8977. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  8978. VK = RHS.get()->getValueKind();
  8979. OK = RHS.get()->getObjectKind();
  8980. }
  8981. break;
  8982. }
  8983. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  8984. return ExprError();
  8985. // Check for array bounds violations for both sides of the BinaryOperator
  8986. CheckArrayAccess(LHS.get());
  8987. CheckArrayAccess(RHS.get());
  8988. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  8989. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  8990. &Context.Idents.get("object_setClass"),
  8991. SourceLocation(), LookupOrdinaryName);
  8992. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  8993. SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  8994. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  8995. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  8996. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  8997. FixItHint::CreateInsertion(RHSLocEnd, ")");
  8998. }
  8999. else
  9000. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  9001. }
  9002. else if (const ObjCIvarRefExpr *OIRE =
  9003. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  9004. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  9005. if (CompResultTy.isNull())
  9006. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  9007. OK, OpLoc, FPFeatures.fp_contract);
  9008. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  9009. OK_ObjCProperty) {
  9010. VK = VK_LValue;
  9011. OK = LHS.get()->getObjectKind();
  9012. }
  9013. return new (Context) CompoundAssignOperator(
  9014. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  9015. OpLoc, FPFeatures.fp_contract);
  9016. }
  9017. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  9018. /// operators are mixed in a way that suggests that the programmer forgot that
  9019. /// comparison operators have higher precedence. The most typical example of
  9020. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  9021. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  9022. SourceLocation OpLoc, Expr *LHSExpr,
  9023. Expr *RHSExpr) {
  9024. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  9025. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  9026. // Check that one of the sides is a comparison operator.
  9027. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  9028. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  9029. if (!isLeftComp && !isRightComp)
  9030. return;
  9031. // Bitwise operations are sometimes used as eager logical ops.
  9032. // Don't diagnose this.
  9033. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  9034. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  9035. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  9036. return;
  9037. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  9038. OpLoc)
  9039. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  9040. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  9041. SourceRange ParensRange = isLeftComp ?
  9042. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  9043. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  9044. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  9045. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  9046. SuggestParentheses(Self, OpLoc,
  9047. Self.PDiag(diag::note_precedence_silence) << OpStr,
  9048. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  9049. SuggestParentheses(Self, OpLoc,
  9050. Self.PDiag(diag::note_precedence_bitwise_first)
  9051. << BinaryOperator::getOpcodeStr(Opc),
  9052. ParensRange);
  9053. }
  9054. /// \brief It accepts a '&' expr that is inside a '|' one.
  9055. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  9056. /// in parentheses.
  9057. static void
  9058. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  9059. BinaryOperator *Bop) {
  9060. assert(Bop->getOpcode() == BO_And);
  9061. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  9062. << Bop->getSourceRange() << OpLoc;
  9063. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9064. Self.PDiag(diag::note_precedence_silence)
  9065. << Bop->getOpcodeStr(),
  9066. Bop->getSourceRange());
  9067. }
  9068. /// \brief It accepts a '&&' expr that is inside a '||' one.
  9069. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  9070. /// in parentheses.
  9071. static void
  9072. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  9073. BinaryOperator *Bop) {
  9074. assert(Bop->getOpcode() == BO_LAnd);
  9075. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  9076. << Bop->getSourceRange() << OpLoc;
  9077. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9078. Self.PDiag(diag::note_precedence_silence)
  9079. << Bop->getOpcodeStr(),
  9080. Bop->getSourceRange());
  9081. }
  9082. /// \brief Returns true if the given expression can be evaluated as a constant
  9083. /// 'true'.
  9084. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  9085. bool Res;
  9086. return !E->isValueDependent() &&
  9087. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  9088. }
  9089. /// \brief Returns true if the given expression can be evaluated as a constant
  9090. /// 'false'.
  9091. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  9092. bool Res;
  9093. return !E->isValueDependent() &&
  9094. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  9095. }
  9096. /// \brief Look for '&&' in the left hand of a '||' expr.
  9097. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  9098. Expr *LHSExpr, Expr *RHSExpr) {
  9099. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  9100. if (Bop->getOpcode() == BO_LAnd) {
  9101. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  9102. if (EvaluatesAsFalse(S, RHSExpr))
  9103. return;
  9104. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  9105. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  9106. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9107. } else if (Bop->getOpcode() == BO_LOr) {
  9108. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  9109. // If it's "a || b && 1 || c" we didn't warn earlier for
  9110. // "a || b && 1", but warn now.
  9111. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  9112. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  9113. }
  9114. }
  9115. }
  9116. }
  9117. /// \brief Look for '&&' in the right hand of a '||' expr.
  9118. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  9119. Expr *LHSExpr, Expr *RHSExpr) {
  9120. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  9121. if (Bop->getOpcode() == BO_LAnd) {
  9122. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  9123. if (EvaluatesAsFalse(S, LHSExpr))
  9124. return;
  9125. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  9126. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  9127. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9128. }
  9129. }
  9130. }
  9131. /// \brief Look for '&' in the left or right hand of a '|' expr.
  9132. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  9133. Expr *OrArg) {
  9134. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  9135. if (Bop->getOpcode() == BO_And)
  9136. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  9137. }
  9138. }
  9139. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  9140. Expr *SubExpr, StringRef Shift) {
  9141. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  9142. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  9143. StringRef Op = Bop->getOpcodeStr();
  9144. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  9145. << Bop->getSourceRange() << OpLoc << Shift << Op;
  9146. SuggestParentheses(S, Bop->getOperatorLoc(),
  9147. S.PDiag(diag::note_precedence_silence) << Op,
  9148. Bop->getSourceRange());
  9149. }
  9150. }
  9151. }
  9152. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  9153. Expr *LHSExpr, Expr *RHSExpr) {
  9154. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  9155. if (!OCE)
  9156. return;
  9157. FunctionDecl *FD = OCE->getDirectCallee();
  9158. if (!FD || !FD->isOverloadedOperator())
  9159. return;
  9160. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  9161. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  9162. return;
  9163. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  9164. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  9165. << (Kind == OO_LessLess);
  9166. SuggestParentheses(S, OCE->getOperatorLoc(),
  9167. S.PDiag(diag::note_precedence_silence)
  9168. << (Kind == OO_LessLess ? "<<" : ">>"),
  9169. OCE->getSourceRange());
  9170. SuggestParentheses(S, OpLoc,
  9171. S.PDiag(diag::note_evaluate_comparison_first),
  9172. SourceRange(OCE->getArg(1)->getLocStart(),
  9173. RHSExpr->getLocEnd()));
  9174. }
  9175. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  9176. /// precedence.
  9177. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  9178. SourceLocation OpLoc, Expr *LHSExpr,
  9179. Expr *RHSExpr){
  9180. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  9181. if (BinaryOperator::isBitwiseOp(Opc))
  9182. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  9183. // Diagnose "arg1 & arg2 | arg3"
  9184. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9185. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  9186. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  9187. }
  9188. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  9189. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  9190. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9191. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  9192. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  9193. }
  9194. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  9195. || Opc == BO_Shr) {
  9196. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  9197. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  9198. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  9199. }
  9200. // Warn on overloaded shift operators and comparisons, such as:
  9201. // cout << 5 == 4;
  9202. if (BinaryOperator::isComparisonOp(Opc))
  9203. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  9204. }
  9205. // Binary Operators. 'Tok' is the token for the operator.
  9206. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  9207. tok::TokenKind Kind,
  9208. Expr *LHSExpr, Expr *RHSExpr) {
  9209. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  9210. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  9211. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  9212. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  9213. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  9214. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  9215. }
  9216. /// Build an overloaded binary operator expression in the given scope.
  9217. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  9218. BinaryOperatorKind Opc,
  9219. Expr *LHS, Expr *RHS) {
  9220. // Find all of the overloaded operators visible from this
  9221. // point. We perform both an operator-name lookup from the local
  9222. // scope and an argument-dependent lookup based on the types of
  9223. // the arguments.
  9224. UnresolvedSet<16> Functions;
  9225. OverloadedOperatorKind OverOp
  9226. = BinaryOperator::getOverloadedOperator(Opc);
  9227. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  9228. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  9229. RHS->getType(), Functions);
  9230. // Build the (potentially-overloaded, potentially-dependent)
  9231. // binary operation.
  9232. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  9233. }
  9234. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  9235. BinaryOperatorKind Opc,
  9236. Expr *LHSExpr, Expr *RHSExpr) {
  9237. // We want to end up calling one of checkPseudoObjectAssignment
  9238. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  9239. // both expressions are overloadable or either is type-dependent),
  9240. // or CreateBuiltinBinOp (in any other case). We also want to get
  9241. // any placeholder types out of the way.
  9242. // Handle pseudo-objects in the LHS.
  9243. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  9244. // Assignments with a pseudo-object l-value need special analysis.
  9245. if (pty->getKind() == BuiltinType::PseudoObject &&
  9246. BinaryOperator::isAssignmentOp(Opc))
  9247. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  9248. // Don't resolve overloads if the other type is overloadable.
  9249. if (pty->getKind() == BuiltinType::Overload) {
  9250. // We can't actually test that if we still have a placeholder,
  9251. // though. Fortunately, none of the exceptions we see in that
  9252. // code below are valid when the LHS is an overload set. Note
  9253. // that an overload set can be dependently-typed, but it never
  9254. // instantiates to having an overloadable type.
  9255. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9256. if (resolvedRHS.isInvalid()) return ExprError();
  9257. RHSExpr = resolvedRHS.get();
  9258. if (RHSExpr->isTypeDependent() ||
  9259. RHSExpr->getType()->isOverloadableType())
  9260. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9261. }
  9262. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  9263. if (LHS.isInvalid()) return ExprError();
  9264. LHSExpr = LHS.get();
  9265. }
  9266. // Handle pseudo-objects in the RHS.
  9267. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  9268. // An overload in the RHS can potentially be resolved by the type
  9269. // being assigned to.
  9270. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  9271. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9272. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9273. if (LHSExpr->getType()->isOverloadableType())
  9274. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9275. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9276. }
  9277. // Don't resolve overloads if the other type is overloadable.
  9278. if (pty->getKind() == BuiltinType::Overload &&
  9279. LHSExpr->getType()->isOverloadableType())
  9280. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9281. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9282. if (!resolvedRHS.isUsable()) return ExprError();
  9283. RHSExpr = resolvedRHS.get();
  9284. }
  9285. if (getLangOpts().CPlusPlus) {
  9286. // If either expression is type-dependent, always build an
  9287. // overloaded op.
  9288. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9289. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9290. // Otherwise, build an overloaded op if either expression has an
  9291. // overloadable type.
  9292. if (LHSExpr->getType()->isOverloadableType() ||
  9293. RHSExpr->getType()->isOverloadableType())
  9294. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9295. }
  9296. // Build a built-in binary operation.
  9297. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9298. }
  9299. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  9300. UnaryOperatorKind Opc,
  9301. Expr *InputExpr) {
  9302. ExprResult Input = InputExpr;
  9303. ExprValueKind VK = VK_RValue;
  9304. ExprObjectKind OK = OK_Ordinary;
  9305. QualType resultType;
  9306. switch (Opc) {
  9307. case UO_PreInc:
  9308. case UO_PreDec:
  9309. case UO_PostInc:
  9310. case UO_PostDec:
  9311. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  9312. OpLoc,
  9313. Opc == UO_PreInc ||
  9314. Opc == UO_PostInc,
  9315. Opc == UO_PreInc ||
  9316. Opc == UO_PreDec);
  9317. break;
  9318. case UO_AddrOf:
  9319. resultType = CheckAddressOfOperand(Input, OpLoc);
  9320. RecordModifiableNonNullParam(*this, InputExpr);
  9321. break;
  9322. case UO_Deref: {
  9323. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9324. if (Input.isInvalid()) return ExprError();
  9325. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  9326. break;
  9327. }
  9328. case UO_Plus:
  9329. case UO_Minus:
  9330. Input = UsualUnaryConversions(Input.get());
  9331. if (Input.isInvalid()) return ExprError();
  9332. resultType = Input.get()->getType();
  9333. if (resultType->isDependentType())
  9334. break;
  9335. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  9336. break;
  9337. else if (resultType->isVectorType() &&
  9338. // The z vector extensions don't allow + or - with bool vectors.
  9339. (!Context.getLangOpts().ZVector ||
  9340. resultType->getAs<VectorType>()->getVectorKind() !=
  9341. VectorType::AltiVecBool))
  9342. break;
  9343. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  9344. Opc == UO_Plus &&
  9345. resultType->isPointerType())
  9346. break;
  9347. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9348. << resultType << Input.get()->getSourceRange());
  9349. case UO_Not: // bitwise complement
  9350. Input = UsualUnaryConversions(Input.get());
  9351. if (Input.isInvalid())
  9352. return ExprError();
  9353. resultType = Input.get()->getType();
  9354. if (resultType->isDependentType())
  9355. break;
  9356. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9357. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9358. // C99 does not support '~' for complex conjugation.
  9359. Diag(OpLoc, diag::ext_integer_complement_complex)
  9360. << resultType << Input.get()->getSourceRange();
  9361. else if (resultType->hasIntegerRepresentation())
  9362. break;
  9363. else if (resultType->isExtVectorType()) {
  9364. if (Context.getLangOpts().OpenCL) {
  9365. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9366. // on vector float types.
  9367. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9368. if (!T->isIntegerType())
  9369. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9370. << resultType << Input.get()->getSourceRange());
  9371. }
  9372. break;
  9373. } else {
  9374. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9375. << resultType << Input.get()->getSourceRange());
  9376. }
  9377. break;
  9378. case UO_LNot: // logical negation
  9379. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9380. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9381. if (Input.isInvalid()) return ExprError();
  9382. resultType = Input.get()->getType();
  9383. // Though we still have to promote half FP to float...
  9384. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9385. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9386. resultType = Context.FloatTy;
  9387. }
  9388. if (resultType->isDependentType())
  9389. break;
  9390. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9391. // C99 6.5.3.3p1: ok, fallthrough;
  9392. if (Context.getLangOpts().CPlusPlus) {
  9393. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9394. // operand contextually converted to bool.
  9395. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9396. ScalarTypeToBooleanCastKind(resultType));
  9397. } else if (Context.getLangOpts().OpenCL &&
  9398. Context.getLangOpts().OpenCLVersion < 120) {
  9399. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9400. // operate on scalar float types.
  9401. if (!resultType->isIntegerType())
  9402. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9403. << resultType << Input.get()->getSourceRange());
  9404. }
  9405. } else if (resultType->isExtVectorType()) {
  9406. if (Context.getLangOpts().OpenCL &&
  9407. Context.getLangOpts().OpenCLVersion < 120) {
  9408. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9409. // operate on vector float types.
  9410. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9411. if (!T->isIntegerType())
  9412. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9413. << resultType << Input.get()->getSourceRange());
  9414. }
  9415. // Vector logical not returns the signed variant of the operand type.
  9416. resultType = GetSignedVectorType(resultType);
  9417. break;
  9418. } else {
  9419. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9420. << resultType << Input.get()->getSourceRange());
  9421. }
  9422. // LNot always has type int. C99 6.5.3.3p5.
  9423. // In C++, it's bool. C++ 5.3.1p8
  9424. resultType = Context.getLogicalOperationType();
  9425. break;
  9426. case UO_Real:
  9427. case UO_Imag:
  9428. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9429. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9430. // complex l-values to ordinary l-values and all other values to r-values.
  9431. if (Input.isInvalid()) return ExprError();
  9432. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9433. if (Input.get()->getValueKind() != VK_RValue &&
  9434. Input.get()->getObjectKind() == OK_Ordinary)
  9435. VK = Input.get()->getValueKind();
  9436. } else if (!getLangOpts().CPlusPlus) {
  9437. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9438. Input = DefaultLvalueConversion(Input.get());
  9439. }
  9440. break;
  9441. case UO_Extension:
  9442. resultType = Input.get()->getType();
  9443. VK = Input.get()->getValueKind();
  9444. OK = Input.get()->getObjectKind();
  9445. break;
  9446. }
  9447. if (resultType.isNull() || Input.isInvalid())
  9448. return ExprError();
  9449. // Check for array bounds violations in the operand of the UnaryOperator,
  9450. // except for the '*' and '&' operators that have to be handled specially
  9451. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9452. // that are explicitly defined as valid by the standard).
  9453. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9454. CheckArrayAccess(Input.get());
  9455. return new (Context)
  9456. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9457. }
  9458. /// \brief Determine whether the given expression is a qualified member
  9459. /// access expression, of a form that could be turned into a pointer to member
  9460. /// with the address-of operator.
  9461. static bool isQualifiedMemberAccess(Expr *E) {
  9462. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9463. if (!DRE->getQualifier())
  9464. return false;
  9465. ValueDecl *VD = DRE->getDecl();
  9466. if (!VD->isCXXClassMember())
  9467. return false;
  9468. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9469. return true;
  9470. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9471. return Method->isInstance();
  9472. return false;
  9473. }
  9474. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9475. if (!ULE->getQualifier())
  9476. return false;
  9477. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9478. DEnd = ULE->decls_end();
  9479. D != DEnd; ++D) {
  9480. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9481. if (Method->isInstance())
  9482. return true;
  9483. } else {
  9484. // Overload set does not contain methods.
  9485. break;
  9486. }
  9487. }
  9488. return false;
  9489. }
  9490. return false;
  9491. }
  9492. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9493. UnaryOperatorKind Opc, Expr *Input) {
  9494. // First things first: handle placeholders so that the
  9495. // overloaded-operator check considers the right type.
  9496. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9497. // Increment and decrement of pseudo-object references.
  9498. if (pty->getKind() == BuiltinType::PseudoObject &&
  9499. UnaryOperator::isIncrementDecrementOp(Opc))
  9500. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9501. // extension is always a builtin operator.
  9502. if (Opc == UO_Extension)
  9503. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9504. // & gets special logic for several kinds of placeholder.
  9505. // The builtin code knows what to do.
  9506. if (Opc == UO_AddrOf &&
  9507. (pty->getKind() == BuiltinType::Overload ||
  9508. pty->getKind() == BuiltinType::UnknownAny ||
  9509. pty->getKind() == BuiltinType::BoundMember))
  9510. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9511. // Anything else needs to be handled now.
  9512. ExprResult Result = CheckPlaceholderExpr(Input);
  9513. if (Result.isInvalid()) return ExprError();
  9514. Input = Result.get();
  9515. }
  9516. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9517. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9518. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9519. // Find all of the overloaded operators visible from this
  9520. // point. We perform both an operator-name lookup from the local
  9521. // scope and an argument-dependent lookup based on the types of
  9522. // the arguments.
  9523. UnresolvedSet<16> Functions;
  9524. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9525. if (S && OverOp != OO_None)
  9526. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9527. Functions);
  9528. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9529. }
  9530. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9531. }
  9532. // Unary Operators. 'Tok' is the token for the operator.
  9533. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9534. tok::TokenKind Op, Expr *Input) {
  9535. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9536. }
  9537. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9538. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9539. LabelDecl *TheDecl) {
  9540. TheDecl->markUsed(Context);
  9541. // Create the AST node. The address of a label always has type 'void*'.
  9542. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9543. Context.getPointerType(Context.VoidTy));
  9544. }
  9545. /// Given the last statement in a statement-expression, check whether
  9546. /// the result is a producing expression (like a call to an
  9547. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9548. /// release out of the full-expression. Otherwise, return null.
  9549. /// Cannot fail.
  9550. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9551. // Should always be wrapped with one of these.
  9552. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9553. if (!cleanups) return nullptr;
  9554. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9555. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9556. return nullptr;
  9557. // Splice out the cast. This shouldn't modify any interesting
  9558. // features of the statement.
  9559. Expr *producer = cast->getSubExpr();
  9560. assert(producer->getType() == cast->getType());
  9561. assert(producer->getValueKind() == cast->getValueKind());
  9562. cleanups->setSubExpr(producer);
  9563. return cleanups;
  9564. }
  9565. void Sema::ActOnStartStmtExpr() {
  9566. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9567. }
  9568. void Sema::ActOnStmtExprError() {
  9569. // Note that function is also called by TreeTransform when leaving a
  9570. // StmtExpr scope without rebuilding anything.
  9571. DiscardCleanupsInEvaluationContext();
  9572. PopExpressionEvaluationContext();
  9573. }
  9574. ExprResult
  9575. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9576. SourceLocation RPLoc) { // "({..})"
  9577. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9578. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9579. if (hasAnyUnrecoverableErrorsInThisFunction())
  9580. DiscardCleanupsInEvaluationContext();
  9581. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9582. PopExpressionEvaluationContext();
  9583. // FIXME: there are a variety of strange constraints to enforce here, for
  9584. // example, it is not possible to goto into a stmt expression apparently.
  9585. // More semantic analysis is needed.
  9586. // If there are sub-stmts in the compound stmt, take the type of the last one
  9587. // as the type of the stmtexpr.
  9588. QualType Ty = Context.VoidTy;
  9589. bool StmtExprMayBindToTemp = false;
  9590. if (!Compound->body_empty()) {
  9591. Stmt *LastStmt = Compound->body_back();
  9592. LabelStmt *LastLabelStmt = nullptr;
  9593. // If LastStmt is a label, skip down through into the body.
  9594. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9595. LastLabelStmt = Label;
  9596. LastStmt = Label->getSubStmt();
  9597. }
  9598. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9599. // Do function/array conversion on the last expression, but not
  9600. // lvalue-to-rvalue. However, initialize an unqualified type.
  9601. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9602. if (LastExpr.isInvalid())
  9603. return ExprError();
  9604. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9605. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9606. // In ARC, if the final expression ends in a consume, splice
  9607. // the consume out and bind it later. In the alternate case
  9608. // (when dealing with a retainable type), the result
  9609. // initialization will create a produce. In both cases the
  9610. // result will be +1, and we'll need to balance that out with
  9611. // a bind.
  9612. if (Expr *rebuiltLastStmt
  9613. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9614. LastExpr = rebuiltLastStmt;
  9615. } else {
  9616. LastExpr = PerformCopyInitialization(
  9617. InitializedEntity::InitializeResult(LPLoc,
  9618. Ty,
  9619. false),
  9620. SourceLocation(),
  9621. LastExpr);
  9622. }
  9623. if (LastExpr.isInvalid())
  9624. return ExprError();
  9625. if (LastExpr.get() != nullptr) {
  9626. if (!LastLabelStmt)
  9627. Compound->setLastStmt(LastExpr.get());
  9628. else
  9629. LastLabelStmt->setSubStmt(LastExpr.get());
  9630. StmtExprMayBindToTemp = true;
  9631. }
  9632. }
  9633. }
  9634. }
  9635. // FIXME: Check that expression type is complete/non-abstract; statement
  9636. // expressions are not lvalues.
  9637. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9638. if (StmtExprMayBindToTemp)
  9639. return MaybeBindToTemporary(ResStmtExpr);
  9640. return ResStmtExpr;
  9641. }
  9642. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9643. TypeSourceInfo *TInfo,
  9644. OffsetOfComponent *CompPtr,
  9645. unsigned NumComponents,
  9646. SourceLocation RParenLoc) {
  9647. QualType ArgTy = TInfo->getType();
  9648. bool Dependent = ArgTy->isDependentType();
  9649. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9650. // We must have at least one component that refers to the type, and the first
  9651. // one is known to be a field designator. Verify that the ArgTy represents
  9652. // a struct/union/class.
  9653. if (!Dependent && !ArgTy->isRecordType())
  9654. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9655. << ArgTy << TypeRange);
  9656. // Type must be complete per C99 7.17p3 because a declaring a variable
  9657. // with an incomplete type would be ill-formed.
  9658. if (!Dependent
  9659. && RequireCompleteType(BuiltinLoc, ArgTy,
  9660. diag::err_offsetof_incomplete_type, TypeRange))
  9661. return ExprError();
  9662. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9663. // GCC extension, diagnose them.
  9664. // FIXME: This diagnostic isn't actually visible because the location is in
  9665. // a system header!
  9666. if (NumComponents != 1)
  9667. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9668. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  9669. bool DidWarnAboutNonPOD = false;
  9670. QualType CurrentType = ArgTy;
  9671. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9672. SmallVector<OffsetOfNode, 4> Comps;
  9673. SmallVector<Expr*, 4> Exprs;
  9674. for (unsigned i = 0; i != NumComponents; ++i) {
  9675. const OffsetOfComponent &OC = CompPtr[i];
  9676. if (OC.isBrackets) {
  9677. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9678. if (!CurrentType->isDependentType()) {
  9679. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9680. if(!AT)
  9681. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9682. << CurrentType);
  9683. CurrentType = AT->getElementType();
  9684. } else
  9685. CurrentType = Context.DependentTy;
  9686. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9687. if (IdxRval.isInvalid())
  9688. return ExprError();
  9689. Expr *Idx = IdxRval.get();
  9690. // The expression must be an integral expression.
  9691. // FIXME: An integral constant expression?
  9692. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9693. !Idx->getType()->isIntegerType())
  9694. return ExprError(Diag(Idx->getLocStart(),
  9695. diag::err_typecheck_subscript_not_integer)
  9696. << Idx->getSourceRange());
  9697. // Record this array index.
  9698. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9699. Exprs.push_back(Idx);
  9700. continue;
  9701. }
  9702. // Offset of a field.
  9703. if (CurrentType->isDependentType()) {
  9704. // We have the offset of a field, but we can't look into the dependent
  9705. // type. Just record the identifier of the field.
  9706. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9707. CurrentType = Context.DependentTy;
  9708. continue;
  9709. }
  9710. // We need to have a complete type to look into.
  9711. if (RequireCompleteType(OC.LocStart, CurrentType,
  9712. diag::err_offsetof_incomplete_type))
  9713. return ExprError();
  9714. // Look for the designated field.
  9715. const RecordType *RC = CurrentType->getAs<RecordType>();
  9716. if (!RC)
  9717. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9718. << CurrentType);
  9719. RecordDecl *RD = RC->getDecl();
  9720. // C++ [lib.support.types]p5:
  9721. // The macro offsetof accepts a restricted set of type arguments in this
  9722. // International Standard. type shall be a POD structure or a POD union
  9723. // (clause 9).
  9724. // C++11 [support.types]p4:
  9725. // If type is not a standard-layout class (Clause 9), the results are
  9726. // undefined.
  9727. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9728. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9729. unsigned DiagID =
  9730. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  9731. : diag::ext_offsetof_non_pod_type;
  9732. if (!IsSafe && !DidWarnAboutNonPOD &&
  9733. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  9734. PDiag(DiagID)
  9735. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  9736. << CurrentType))
  9737. DidWarnAboutNonPOD = true;
  9738. }
  9739. // Look for the field.
  9740. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  9741. LookupQualifiedName(R, RD);
  9742. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  9743. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  9744. if (!MemberDecl) {
  9745. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  9746. MemberDecl = IndirectMemberDecl->getAnonField();
  9747. }
  9748. if (!MemberDecl)
  9749. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  9750. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  9751. OC.LocEnd));
  9752. // C99 7.17p3:
  9753. // (If the specified member is a bit-field, the behavior is undefined.)
  9754. //
  9755. // We diagnose this as an error.
  9756. if (MemberDecl->isBitField()) {
  9757. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  9758. << MemberDecl->getDeclName()
  9759. << SourceRange(BuiltinLoc, RParenLoc);
  9760. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  9761. return ExprError();
  9762. }
  9763. RecordDecl *Parent = MemberDecl->getParent();
  9764. if (IndirectMemberDecl)
  9765. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  9766. // If the member was found in a base class, introduce OffsetOfNodes for
  9767. // the base class indirections.
  9768. CXXBasePaths Paths;
  9769. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  9770. if (Paths.getDetectedVirtual()) {
  9771. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  9772. << MemberDecl->getDeclName()
  9773. << SourceRange(BuiltinLoc, RParenLoc);
  9774. return ExprError();
  9775. }
  9776. CXXBasePath &Path = Paths.front();
  9777. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  9778. B != BEnd; ++B)
  9779. Comps.push_back(OffsetOfNode(B->Base));
  9780. }
  9781. if (IndirectMemberDecl) {
  9782. for (auto *FI : IndirectMemberDecl->chain()) {
  9783. assert(isa<FieldDecl>(FI));
  9784. Comps.push_back(OffsetOfNode(OC.LocStart,
  9785. cast<FieldDecl>(FI), OC.LocEnd));
  9786. }
  9787. } else
  9788. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  9789. CurrentType = MemberDecl->getType().getNonReferenceType();
  9790. }
  9791. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  9792. Comps, Exprs, RParenLoc);
  9793. }
  9794. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  9795. SourceLocation BuiltinLoc,
  9796. SourceLocation TypeLoc,
  9797. ParsedType ParsedArgTy,
  9798. OffsetOfComponent *CompPtr,
  9799. unsigned NumComponents,
  9800. SourceLocation RParenLoc) {
  9801. TypeSourceInfo *ArgTInfo;
  9802. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  9803. if (ArgTy.isNull())
  9804. return ExprError();
  9805. if (!ArgTInfo)
  9806. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  9807. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  9808. RParenLoc);
  9809. }
  9810. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  9811. Expr *CondExpr,
  9812. Expr *LHSExpr, Expr *RHSExpr,
  9813. SourceLocation RPLoc) {
  9814. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  9815. ExprValueKind VK = VK_RValue;
  9816. ExprObjectKind OK = OK_Ordinary;
  9817. QualType resType;
  9818. bool ValueDependent = false;
  9819. bool CondIsTrue = false;
  9820. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  9821. resType = Context.DependentTy;
  9822. ValueDependent = true;
  9823. } else {
  9824. // The conditional expression is required to be a constant expression.
  9825. llvm::APSInt condEval(32);
  9826. ExprResult CondICE
  9827. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  9828. diag::err_typecheck_choose_expr_requires_constant, false);
  9829. if (CondICE.isInvalid())
  9830. return ExprError();
  9831. CondExpr = CondICE.get();
  9832. CondIsTrue = condEval.getZExtValue();
  9833. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  9834. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  9835. resType = ActiveExpr->getType();
  9836. ValueDependent = ActiveExpr->isValueDependent();
  9837. VK = ActiveExpr->getValueKind();
  9838. OK = ActiveExpr->getObjectKind();
  9839. }
  9840. return new (Context)
  9841. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  9842. CondIsTrue, resType->isDependentType(), ValueDependent);
  9843. }
  9844. //===----------------------------------------------------------------------===//
  9845. // Clang Extensions.
  9846. //===----------------------------------------------------------------------===//
  9847. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  9848. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  9849. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  9850. if (LangOpts.CPlusPlus) {
  9851. Decl *ManglingContextDecl;
  9852. if (MangleNumberingContext *MCtx =
  9853. getCurrentMangleNumberContext(Block->getDeclContext(),
  9854. ManglingContextDecl)) {
  9855. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  9856. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  9857. }
  9858. }
  9859. PushBlockScope(CurScope, Block);
  9860. CurContext->addDecl(Block);
  9861. if (CurScope)
  9862. PushDeclContext(CurScope, Block);
  9863. else
  9864. CurContext = Block;
  9865. getCurBlock()->HasImplicitReturnType = true;
  9866. // Enter a new evaluation context to insulate the block from any
  9867. // cleanups from the enclosing full-expression.
  9868. PushExpressionEvaluationContext(PotentiallyEvaluated);
  9869. }
  9870. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  9871. Scope *CurScope) {
  9872. assert(ParamInfo.getIdentifier() == nullptr &&
  9873. "block-id should have no identifier!");
  9874. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  9875. BlockScopeInfo *CurBlock = getCurBlock();
  9876. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  9877. QualType T = Sig->getType();
  9878. // FIXME: We should allow unexpanded parameter packs here, but that would,
  9879. // in turn, make the block expression contain unexpanded parameter packs.
  9880. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  9881. // Drop the parameters.
  9882. FunctionProtoType::ExtProtoInfo EPI;
  9883. EPI.HasTrailingReturn = false;
  9884. EPI.TypeQuals |= DeclSpec::TQ_const;
  9885. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  9886. Sig = Context.getTrivialTypeSourceInfo(T);
  9887. }
  9888. // GetTypeForDeclarator always produces a function type for a block
  9889. // literal signature. Furthermore, it is always a FunctionProtoType
  9890. // unless the function was written with a typedef.
  9891. assert(T->isFunctionType() &&
  9892. "GetTypeForDeclarator made a non-function block signature");
  9893. // Look for an explicit signature in that function type.
  9894. FunctionProtoTypeLoc ExplicitSignature;
  9895. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  9896. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  9897. // Check whether that explicit signature was synthesized by
  9898. // GetTypeForDeclarator. If so, don't save that as part of the
  9899. // written signature.
  9900. if (ExplicitSignature.getLocalRangeBegin() ==
  9901. ExplicitSignature.getLocalRangeEnd()) {
  9902. // This would be much cheaper if we stored TypeLocs instead of
  9903. // TypeSourceInfos.
  9904. TypeLoc Result = ExplicitSignature.getReturnLoc();
  9905. unsigned Size = Result.getFullDataSize();
  9906. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  9907. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  9908. ExplicitSignature = FunctionProtoTypeLoc();
  9909. }
  9910. }
  9911. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  9912. CurBlock->FunctionType = T;
  9913. const FunctionType *Fn = T->getAs<FunctionType>();
  9914. QualType RetTy = Fn->getReturnType();
  9915. bool isVariadic =
  9916. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  9917. CurBlock->TheDecl->setIsVariadic(isVariadic);
  9918. // Context.DependentTy is used as a placeholder for a missing block
  9919. // return type. TODO: what should we do with declarators like:
  9920. // ^ * { ... }
  9921. // If the answer is "apply template argument deduction"....
  9922. if (RetTy != Context.DependentTy) {
  9923. CurBlock->ReturnType = RetTy;
  9924. CurBlock->TheDecl->setBlockMissingReturnType(false);
  9925. CurBlock->HasImplicitReturnType = false;
  9926. }
  9927. // Push block parameters from the declarator if we had them.
  9928. SmallVector<ParmVarDecl*, 8> Params;
  9929. if (ExplicitSignature) {
  9930. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  9931. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  9932. if (Param->getIdentifier() == nullptr &&
  9933. !Param->isImplicit() &&
  9934. !Param->isInvalidDecl() &&
  9935. !getLangOpts().CPlusPlus)
  9936. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  9937. Params.push_back(Param);
  9938. }
  9939. // Fake up parameter variables if we have a typedef, like
  9940. // ^ fntype { ... }
  9941. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  9942. for (const auto &I : Fn->param_types()) {
  9943. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  9944. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  9945. Params.push_back(Param);
  9946. }
  9947. }
  9948. // Set the parameters on the block decl.
  9949. if (!Params.empty()) {
  9950. CurBlock->TheDecl->setParams(Params);
  9951. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  9952. CurBlock->TheDecl->param_end(),
  9953. /*CheckParameterNames=*/false);
  9954. }
  9955. // Finally we can process decl attributes.
  9956. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  9957. // Put the parameter variables in scope.
  9958. for (auto AI : CurBlock->TheDecl->params()) {
  9959. AI->setOwningFunction(CurBlock->TheDecl);
  9960. // If this has an identifier, add it to the scope stack.
  9961. if (AI->getIdentifier()) {
  9962. CheckShadow(CurBlock->TheScope, AI);
  9963. PushOnScopeChains(AI, CurBlock->TheScope);
  9964. }
  9965. }
  9966. }
  9967. /// ActOnBlockError - If there is an error parsing a block, this callback
  9968. /// is invoked to pop the information about the block from the action impl.
  9969. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  9970. // Leave the expression-evaluation context.
  9971. DiscardCleanupsInEvaluationContext();
  9972. PopExpressionEvaluationContext();
  9973. // Pop off CurBlock, handle nested blocks.
  9974. PopDeclContext();
  9975. PopFunctionScopeInfo();
  9976. }
  9977. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  9978. /// literal was successfully completed. ^(int x){...}
  9979. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  9980. Stmt *Body, Scope *CurScope) {
  9981. // If blocks are disabled, emit an error.
  9982. if (!LangOpts.Blocks)
  9983. Diag(CaretLoc, diag::err_blocks_disable);
  9984. // Leave the expression-evaluation context.
  9985. if (hasAnyUnrecoverableErrorsInThisFunction())
  9986. DiscardCleanupsInEvaluationContext();
  9987. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  9988. PopExpressionEvaluationContext();
  9989. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  9990. if (BSI->HasImplicitReturnType)
  9991. deduceClosureReturnType(*BSI);
  9992. PopDeclContext();
  9993. QualType RetTy = Context.VoidTy;
  9994. if (!BSI->ReturnType.isNull())
  9995. RetTy = BSI->ReturnType;
  9996. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  9997. QualType BlockTy;
  9998. // Set the captured variables on the block.
  9999. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  10000. SmallVector<BlockDecl::Capture, 4> Captures;
  10001. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  10002. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  10003. if (Cap.isThisCapture())
  10004. continue;
  10005. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  10006. Cap.isNested(), Cap.getInitExpr());
  10007. Captures.push_back(NewCap);
  10008. }
  10009. BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  10010. // If the user wrote a function type in some form, try to use that.
  10011. if (!BSI->FunctionType.isNull()) {
  10012. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  10013. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  10014. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  10015. // Turn protoless block types into nullary block types.
  10016. if (isa<FunctionNoProtoType>(FTy)) {
  10017. FunctionProtoType::ExtProtoInfo EPI;
  10018. EPI.ExtInfo = Ext;
  10019. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10020. // Otherwise, if we don't need to change anything about the function type,
  10021. // preserve its sugar structure.
  10022. } else if (FTy->getReturnType() == RetTy &&
  10023. (!NoReturn || FTy->getNoReturnAttr())) {
  10024. BlockTy = BSI->FunctionType;
  10025. // Otherwise, make the minimal modifications to the function type.
  10026. } else {
  10027. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  10028. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10029. EPI.TypeQuals = 0; // FIXME: silently?
  10030. EPI.ExtInfo = Ext;
  10031. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  10032. }
  10033. // If we don't have a function type, just build one from nothing.
  10034. } else {
  10035. FunctionProtoType::ExtProtoInfo EPI;
  10036. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  10037. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10038. }
  10039. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  10040. BSI->TheDecl->param_end());
  10041. BlockTy = Context.getBlockPointerType(BlockTy);
  10042. // If needed, diagnose invalid gotos and switches in the block.
  10043. if (getCurFunction()->NeedsScopeChecking() &&
  10044. !PP.isCodeCompletionEnabled())
  10045. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  10046. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  10047. // Try to apply the named return value optimization. We have to check again
  10048. // if we can do this, though, because blocks keep return statements around
  10049. // to deduce an implicit return type.
  10050. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  10051. !BSI->TheDecl->isDependentContext())
  10052. computeNRVO(Body, BSI);
  10053. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  10054. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10055. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  10056. // If the block isn't obviously global, i.e. it captures anything at
  10057. // all, then we need to do a few things in the surrounding context:
  10058. if (Result->getBlockDecl()->hasCaptures()) {
  10059. // First, this expression has a new cleanup object.
  10060. ExprCleanupObjects.push_back(Result->getBlockDecl());
  10061. ExprNeedsCleanups = true;
  10062. // It also gets a branch-protected scope if any of the captured
  10063. // variables needs destruction.
  10064. for (const auto &CI : Result->getBlockDecl()->captures()) {
  10065. const VarDecl *var = CI.getVariable();
  10066. if (var->getType().isDestructedType() != QualType::DK_none) {
  10067. getCurFunction()->setHasBranchProtectedScope();
  10068. break;
  10069. }
  10070. }
  10071. }
  10072. return Result;
  10073. }
  10074. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  10075. Expr *E, ParsedType Ty,
  10076. SourceLocation RPLoc) {
  10077. TypeSourceInfo *TInfo;
  10078. GetTypeFromParser(Ty, &TInfo);
  10079. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  10080. }
  10081. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  10082. Expr *E, TypeSourceInfo *TInfo,
  10083. SourceLocation RPLoc) {
  10084. Expr *OrigExpr = E;
  10085. // Get the va_list type
  10086. QualType VaListType = Context.getBuiltinVaListType();
  10087. if (VaListType->isArrayType()) {
  10088. // Deal with implicit array decay; for example, on x86-64,
  10089. // va_list is an array, but it's supposed to decay to
  10090. // a pointer for va_arg.
  10091. VaListType = Context.getArrayDecayedType(VaListType);
  10092. // Make sure the input expression also decays appropriately.
  10093. ExprResult Result = UsualUnaryConversions(E);
  10094. if (Result.isInvalid())
  10095. return ExprError();
  10096. E = Result.get();
  10097. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  10098. // If va_list is a record type and we are compiling in C++ mode,
  10099. // check the argument using reference binding.
  10100. InitializedEntity Entity
  10101. = InitializedEntity::InitializeParameter(Context,
  10102. Context.getLValueReferenceType(VaListType), false);
  10103. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  10104. if (Init.isInvalid())
  10105. return ExprError();
  10106. E = Init.getAs<Expr>();
  10107. } else {
  10108. // Otherwise, the va_list argument must be an l-value because
  10109. // it is modified by va_arg.
  10110. if (!E->isTypeDependent() &&
  10111. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10112. return ExprError();
  10113. }
  10114. if (!E->isTypeDependent() &&
  10115. !Context.hasSameType(VaListType, E->getType())) {
  10116. return ExprError(Diag(E->getLocStart(),
  10117. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  10118. << OrigExpr->getType() << E->getSourceRange());
  10119. }
  10120. if (!TInfo->getType()->isDependentType()) {
  10121. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  10122. diag::err_second_parameter_to_va_arg_incomplete,
  10123. TInfo->getTypeLoc()))
  10124. return ExprError();
  10125. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  10126. TInfo->getType(),
  10127. diag::err_second_parameter_to_va_arg_abstract,
  10128. TInfo->getTypeLoc()))
  10129. return ExprError();
  10130. if (!TInfo->getType().isPODType(Context)) {
  10131. Diag(TInfo->getTypeLoc().getBeginLoc(),
  10132. TInfo->getType()->isObjCLifetimeType()
  10133. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  10134. : diag::warn_second_parameter_to_va_arg_not_pod)
  10135. << TInfo->getType()
  10136. << TInfo->getTypeLoc().getSourceRange();
  10137. }
  10138. // Check for va_arg where arguments of the given type will be promoted
  10139. // (i.e. this va_arg is guaranteed to have undefined behavior).
  10140. QualType PromoteType;
  10141. if (TInfo->getType()->isPromotableIntegerType()) {
  10142. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  10143. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  10144. PromoteType = QualType();
  10145. }
  10146. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  10147. PromoteType = Context.DoubleTy;
  10148. if (!PromoteType.isNull())
  10149. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  10150. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  10151. << TInfo->getType()
  10152. << PromoteType
  10153. << TInfo->getTypeLoc().getSourceRange());
  10154. }
  10155. QualType T = TInfo->getType().getNonLValueExprType(Context);
  10156. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
  10157. }
  10158. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  10159. // The type of __null will be int or long, depending on the size of
  10160. // pointers on the target.
  10161. QualType Ty;
  10162. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  10163. if (pw == Context.getTargetInfo().getIntWidth())
  10164. Ty = Context.IntTy;
  10165. else if (pw == Context.getTargetInfo().getLongWidth())
  10166. Ty = Context.LongTy;
  10167. else if (pw == Context.getTargetInfo().getLongLongWidth())
  10168. Ty = Context.LongLongTy;
  10169. else {
  10170. llvm_unreachable("I don't know size of pointer!");
  10171. }
  10172. return new (Context) GNUNullExpr(Ty, TokenLoc);
  10173. }
  10174. bool
  10175. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  10176. if (!getLangOpts().ObjC1)
  10177. return false;
  10178. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  10179. if (!PT)
  10180. return false;
  10181. if (!PT->isObjCIdType()) {
  10182. // Check if the destination is the 'NSString' interface.
  10183. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  10184. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  10185. return false;
  10186. }
  10187. // Ignore any parens, implicit casts (should only be
  10188. // array-to-pointer decays), and not-so-opaque values. The last is
  10189. // important for making this trigger for property assignments.
  10190. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  10191. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  10192. if (OV->getSourceExpr())
  10193. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  10194. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  10195. if (!SL || !SL->isAscii())
  10196. return false;
  10197. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  10198. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  10199. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  10200. return true;
  10201. }
  10202. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  10203. SourceLocation Loc,
  10204. QualType DstType, QualType SrcType,
  10205. Expr *SrcExpr, AssignmentAction Action,
  10206. bool *Complained) {
  10207. if (Complained)
  10208. *Complained = false;
  10209. // Decode the result (notice that AST's are still created for extensions).
  10210. bool CheckInferredResultType = false;
  10211. bool isInvalid = false;
  10212. unsigned DiagKind = 0;
  10213. FixItHint Hint;
  10214. ConversionFixItGenerator ConvHints;
  10215. bool MayHaveConvFixit = false;
  10216. bool MayHaveFunctionDiff = false;
  10217. const ObjCInterfaceDecl *IFace = nullptr;
  10218. const ObjCProtocolDecl *PDecl = nullptr;
  10219. switch (ConvTy) {
  10220. case Compatible:
  10221. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  10222. return false;
  10223. case PointerToInt:
  10224. DiagKind = diag::ext_typecheck_convert_pointer_int;
  10225. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10226. MayHaveConvFixit = true;
  10227. break;
  10228. case IntToPointer:
  10229. DiagKind = diag::ext_typecheck_convert_int_pointer;
  10230. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10231. MayHaveConvFixit = true;
  10232. break;
  10233. case IncompatiblePointer:
  10234. DiagKind =
  10235. (Action == AA_Passing_CFAudited ?
  10236. diag::err_arc_typecheck_convert_incompatible_pointer :
  10237. diag::ext_typecheck_convert_incompatible_pointer);
  10238. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  10239. SrcType->isObjCObjectPointerType();
  10240. if (Hint.isNull() && !CheckInferredResultType) {
  10241. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10242. }
  10243. else if (CheckInferredResultType) {
  10244. SrcType = SrcType.getUnqualifiedType();
  10245. DstType = DstType.getUnqualifiedType();
  10246. }
  10247. MayHaveConvFixit = true;
  10248. break;
  10249. case IncompatiblePointerSign:
  10250. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  10251. break;
  10252. case FunctionVoidPointer:
  10253. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  10254. break;
  10255. case IncompatiblePointerDiscardsQualifiers: {
  10256. // Perform array-to-pointer decay if necessary.
  10257. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  10258. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  10259. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  10260. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  10261. DiagKind = diag::err_typecheck_incompatible_address_space;
  10262. break;
  10263. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  10264. DiagKind = diag::err_typecheck_incompatible_ownership;
  10265. break;
  10266. }
  10267. llvm_unreachable("unknown error case for discarding qualifiers!");
  10268. // fallthrough
  10269. }
  10270. case CompatiblePointerDiscardsQualifiers:
  10271. // If the qualifiers lost were because we were applying the
  10272. // (deprecated) C++ conversion from a string literal to a char*
  10273. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  10274. // Ideally, this check would be performed in
  10275. // checkPointerTypesForAssignment. However, that would require a
  10276. // bit of refactoring (so that the second argument is an
  10277. // expression, rather than a type), which should be done as part
  10278. // of a larger effort to fix checkPointerTypesForAssignment for
  10279. // C++ semantics.
  10280. if (getLangOpts().CPlusPlus &&
  10281. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  10282. return false;
  10283. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  10284. break;
  10285. case IncompatibleNestedPointerQualifiers:
  10286. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  10287. break;
  10288. case IntToBlockPointer:
  10289. DiagKind = diag::err_int_to_block_pointer;
  10290. break;
  10291. case IncompatibleBlockPointer:
  10292. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  10293. break;
  10294. case IncompatibleObjCQualifiedId: {
  10295. if (SrcType->isObjCQualifiedIdType()) {
  10296. const ObjCObjectPointerType *srcOPT =
  10297. SrcType->getAs<ObjCObjectPointerType>();
  10298. for (auto *srcProto : srcOPT->quals()) {
  10299. PDecl = srcProto;
  10300. break;
  10301. }
  10302. if (const ObjCInterfaceType *IFaceT =
  10303. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10304. IFace = IFaceT->getDecl();
  10305. }
  10306. else if (DstType->isObjCQualifiedIdType()) {
  10307. const ObjCObjectPointerType *dstOPT =
  10308. DstType->getAs<ObjCObjectPointerType>();
  10309. for (auto *dstProto : dstOPT->quals()) {
  10310. PDecl = dstProto;
  10311. break;
  10312. }
  10313. if (const ObjCInterfaceType *IFaceT =
  10314. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10315. IFace = IFaceT->getDecl();
  10316. }
  10317. DiagKind = diag::warn_incompatible_qualified_id;
  10318. break;
  10319. }
  10320. case IncompatibleVectors:
  10321. DiagKind = diag::warn_incompatible_vectors;
  10322. break;
  10323. case IncompatibleObjCWeakRef:
  10324. DiagKind = diag::err_arc_weak_unavailable_assign;
  10325. break;
  10326. case Incompatible:
  10327. DiagKind = diag::err_typecheck_convert_incompatible;
  10328. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10329. MayHaveConvFixit = true;
  10330. isInvalid = true;
  10331. MayHaveFunctionDiff = true;
  10332. break;
  10333. }
  10334. QualType FirstType, SecondType;
  10335. switch (Action) {
  10336. case AA_Assigning:
  10337. case AA_Initializing:
  10338. // The destination type comes first.
  10339. FirstType = DstType;
  10340. SecondType = SrcType;
  10341. break;
  10342. case AA_Returning:
  10343. case AA_Passing:
  10344. case AA_Passing_CFAudited:
  10345. case AA_Converting:
  10346. case AA_Sending:
  10347. case AA_Casting:
  10348. // The source type comes first.
  10349. FirstType = SrcType;
  10350. SecondType = DstType;
  10351. break;
  10352. }
  10353. PartialDiagnostic FDiag = PDiag(DiagKind);
  10354. if (Action == AA_Passing_CFAudited)
  10355. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10356. else
  10357. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10358. // If we can fix the conversion, suggest the FixIts.
  10359. assert(ConvHints.isNull() || Hint.isNull());
  10360. if (!ConvHints.isNull()) {
  10361. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10362. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10363. FDiag << *HI;
  10364. } else {
  10365. FDiag << Hint;
  10366. }
  10367. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10368. if (MayHaveFunctionDiff)
  10369. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10370. Diag(Loc, FDiag);
  10371. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10372. PDecl && IFace && !IFace->hasDefinition())
  10373. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10374. << IFace->getName() << PDecl->getName();
  10375. if (SecondType == Context.OverloadTy)
  10376. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10377. FirstType);
  10378. if (CheckInferredResultType)
  10379. EmitRelatedResultTypeNote(SrcExpr);
  10380. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10381. EmitRelatedResultTypeNoteForReturn(DstType);
  10382. if (Complained)
  10383. *Complained = true;
  10384. return isInvalid;
  10385. }
  10386. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10387. llvm::APSInt *Result) {
  10388. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10389. public:
  10390. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10391. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10392. }
  10393. } Diagnoser;
  10394. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10395. }
  10396. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10397. llvm::APSInt *Result,
  10398. unsigned DiagID,
  10399. bool AllowFold) {
  10400. class IDDiagnoser : public VerifyICEDiagnoser {
  10401. unsigned DiagID;
  10402. public:
  10403. IDDiagnoser(unsigned DiagID)
  10404. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10405. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10406. S.Diag(Loc, DiagID) << SR;
  10407. }
  10408. } Diagnoser(DiagID);
  10409. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10410. }
  10411. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10412. SourceRange SR) {
  10413. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10414. }
  10415. ExprResult
  10416. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10417. VerifyICEDiagnoser &Diagnoser,
  10418. bool AllowFold) {
  10419. SourceLocation DiagLoc = E->getLocStart();
  10420. if (getLangOpts().CPlusPlus11) {
  10421. // C++11 [expr.const]p5:
  10422. // If an expression of literal class type is used in a context where an
  10423. // integral constant expression is required, then that class type shall
  10424. // have a single non-explicit conversion function to an integral or
  10425. // unscoped enumeration type
  10426. ExprResult Converted;
  10427. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10428. public:
  10429. CXX11ConvertDiagnoser(bool Silent)
  10430. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10431. Silent, true) {}
  10432. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10433. QualType T) override {
  10434. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10435. }
  10436. SemaDiagnosticBuilder diagnoseIncomplete(
  10437. Sema &S, SourceLocation Loc, QualType T) override {
  10438. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10439. }
  10440. SemaDiagnosticBuilder diagnoseExplicitConv(
  10441. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10442. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10443. }
  10444. SemaDiagnosticBuilder noteExplicitConv(
  10445. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10446. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10447. << ConvTy->isEnumeralType() << ConvTy;
  10448. }
  10449. SemaDiagnosticBuilder diagnoseAmbiguous(
  10450. Sema &S, SourceLocation Loc, QualType T) override {
  10451. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10452. }
  10453. SemaDiagnosticBuilder noteAmbiguous(
  10454. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10455. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10456. << ConvTy->isEnumeralType() << ConvTy;
  10457. }
  10458. SemaDiagnosticBuilder diagnoseConversion(
  10459. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10460. llvm_unreachable("conversion functions are permitted");
  10461. }
  10462. } ConvertDiagnoser(Diagnoser.Suppress);
  10463. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10464. ConvertDiagnoser);
  10465. if (Converted.isInvalid())
  10466. return Converted;
  10467. E = Converted.get();
  10468. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10469. return ExprError();
  10470. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10471. // An ICE must be of integral or unscoped enumeration type.
  10472. if (!Diagnoser.Suppress)
  10473. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10474. return ExprError();
  10475. }
  10476. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10477. // in the non-ICE case.
  10478. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10479. if (Result)
  10480. *Result = E->EvaluateKnownConstInt(Context);
  10481. return E;
  10482. }
  10483. Expr::EvalResult EvalResult;
  10484. SmallVector<PartialDiagnosticAt, 8> Notes;
  10485. EvalResult.Diag = &Notes;
  10486. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10487. // not a constant expression as a side-effect.
  10488. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10489. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10490. // In C++11, we can rely on diagnostics being produced for any expression
  10491. // which is not a constant expression. If no diagnostics were produced, then
  10492. // this is a constant expression.
  10493. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10494. if (Result)
  10495. *Result = EvalResult.Val.getInt();
  10496. return E;
  10497. }
  10498. // If our only note is the usual "invalid subexpression" note, just point
  10499. // the caret at its location rather than producing an essentially
  10500. // redundant note.
  10501. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10502. diag::note_invalid_subexpr_in_const_expr) {
  10503. DiagLoc = Notes[0].first;
  10504. Notes.clear();
  10505. }
  10506. if (!Folded || !AllowFold) {
  10507. if (!Diagnoser.Suppress) {
  10508. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10509. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10510. Diag(Notes[I].first, Notes[I].second);
  10511. }
  10512. return ExprError();
  10513. }
  10514. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10515. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10516. Diag(Notes[I].first, Notes[I].second);
  10517. if (Result)
  10518. *Result = EvalResult.Val.getInt();
  10519. return E;
  10520. }
  10521. namespace {
  10522. // Handle the case where we conclude a expression which we speculatively
  10523. // considered to be unevaluated is actually evaluated.
  10524. class TransformToPE : public TreeTransform<TransformToPE> {
  10525. typedef TreeTransform<TransformToPE> BaseTransform;
  10526. public:
  10527. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10528. // Make sure we redo semantic analysis
  10529. bool AlwaysRebuild() { return true; }
  10530. // Make sure we handle LabelStmts correctly.
  10531. // FIXME: This does the right thing, but maybe we need a more general
  10532. // fix to TreeTransform?
  10533. StmtResult TransformLabelStmt(LabelStmt *S) {
  10534. S->getDecl()->setStmt(nullptr);
  10535. return BaseTransform::TransformLabelStmt(S);
  10536. }
  10537. // We need to special-case DeclRefExprs referring to FieldDecls which
  10538. // are not part of a member pointer formation; normal TreeTransforming
  10539. // doesn't catch this case because of the way we represent them in the AST.
  10540. // FIXME: This is a bit ugly; is it really the best way to handle this
  10541. // case?
  10542. //
  10543. // Error on DeclRefExprs referring to FieldDecls.
  10544. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10545. if (isa<FieldDecl>(E->getDecl()) &&
  10546. !SemaRef.isUnevaluatedContext())
  10547. return SemaRef.Diag(E->getLocation(),
  10548. diag::err_invalid_non_static_member_use)
  10549. << E->getDecl() << E->getSourceRange();
  10550. return BaseTransform::TransformDeclRefExpr(E);
  10551. }
  10552. // Exception: filter out member pointer formation
  10553. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10554. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10555. return E;
  10556. return BaseTransform::TransformUnaryOperator(E);
  10557. }
  10558. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10559. // Lambdas never need to be transformed.
  10560. return E;
  10561. }
  10562. };
  10563. }
  10564. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10565. assert(isUnevaluatedContext() &&
  10566. "Should only transform unevaluated expressions");
  10567. ExprEvalContexts.back().Context =
  10568. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10569. if (isUnevaluatedContext())
  10570. return E;
  10571. return TransformToPE(*this).TransformExpr(E);
  10572. }
  10573. void
  10574. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10575. Decl *LambdaContextDecl,
  10576. bool IsDecltype) {
  10577. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10578. ExprNeedsCleanups, LambdaContextDecl,
  10579. IsDecltype);
  10580. ExprNeedsCleanups = false;
  10581. if (!MaybeODRUseExprs.empty())
  10582. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10583. }
  10584. void
  10585. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10586. ReuseLambdaContextDecl_t,
  10587. bool IsDecltype) {
  10588. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10589. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10590. }
  10591. void Sema::PopExpressionEvaluationContext() {
  10592. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10593. unsigned NumTypos = Rec.NumTypos;
  10594. if (!Rec.Lambdas.empty()) {
  10595. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10596. unsigned D;
  10597. if (Rec.isUnevaluated()) {
  10598. // C++11 [expr.prim.lambda]p2:
  10599. // A lambda-expression shall not appear in an unevaluated operand
  10600. // (Clause 5).
  10601. D = diag::err_lambda_unevaluated_operand;
  10602. } else {
  10603. // C++1y [expr.const]p2:
  10604. // A conditional-expression e is a core constant expression unless the
  10605. // evaluation of e, following the rules of the abstract machine, would
  10606. // evaluate [...] a lambda-expression.
  10607. D = diag::err_lambda_in_constant_expression;
  10608. }
  10609. for (const auto *L : Rec.Lambdas)
  10610. Diag(L->getLocStart(), D);
  10611. } else {
  10612. // Mark the capture expressions odr-used. This was deferred
  10613. // during lambda expression creation.
  10614. for (auto *Lambda : Rec.Lambdas) {
  10615. for (auto *C : Lambda->capture_inits())
  10616. MarkDeclarationsReferencedInExpr(C);
  10617. }
  10618. }
  10619. }
  10620. // When are coming out of an unevaluated context, clear out any
  10621. // temporaries that we may have created as part of the evaluation of
  10622. // the expression in that context: they aren't relevant because they
  10623. // will never be constructed.
  10624. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10625. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10626. ExprCleanupObjects.end());
  10627. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10628. CleanupVarDeclMarking();
  10629. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10630. // Otherwise, merge the contexts together.
  10631. } else {
  10632. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10633. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10634. Rec.SavedMaybeODRUseExprs.end());
  10635. }
  10636. // Pop the current expression evaluation context off the stack.
  10637. ExprEvalContexts.pop_back();
  10638. if (!ExprEvalContexts.empty())
  10639. ExprEvalContexts.back().NumTypos += NumTypos;
  10640. else
  10641. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10642. "last ExpressionEvaluationContextRecord");
  10643. }
  10644. void Sema::DiscardCleanupsInEvaluationContext() {
  10645. ExprCleanupObjects.erase(
  10646. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10647. ExprCleanupObjects.end());
  10648. ExprNeedsCleanups = false;
  10649. MaybeODRUseExprs.clear();
  10650. }
  10651. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10652. if (!E->getType()->isVariablyModifiedType())
  10653. return E;
  10654. return TransformToPotentiallyEvaluated(E);
  10655. }
  10656. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10657. // Do not mark anything as "used" within a dependent context; wait for
  10658. // an instantiation.
  10659. if (SemaRef.CurContext->isDependentContext())
  10660. return false;
  10661. switch (SemaRef.ExprEvalContexts.back().Context) {
  10662. case Sema::Unevaluated:
  10663. case Sema::UnevaluatedAbstract:
  10664. // We are in an expression that is not potentially evaluated; do nothing.
  10665. // (Depending on how you read the standard, we actually do need to do
  10666. // something here for null pointer constants, but the standard's
  10667. // definition of a null pointer constant is completely crazy.)
  10668. return false;
  10669. case Sema::ConstantEvaluated:
  10670. case Sema::PotentiallyEvaluated:
  10671. // We are in a potentially evaluated expression (or a constant-expression
  10672. // in C++03); we need to do implicit template instantiation, implicitly
  10673. // define class members, and mark most declarations as used.
  10674. return true;
  10675. case Sema::PotentiallyEvaluatedIfUsed:
  10676. // Referenced declarations will only be used if the construct in the
  10677. // containing expression is used.
  10678. return false;
  10679. }
  10680. llvm_unreachable("Invalid context");
  10681. }
  10682. /// \brief Mark a function referenced, and check whether it is odr-used
  10683. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10684. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10685. bool OdrUse) {
  10686. assert(Func && "No function?");
  10687. Func->setReferenced();
  10688. // C++11 [basic.def.odr]p3:
  10689. // A function whose name appears as a potentially-evaluated expression is
  10690. // odr-used if it is the unique lookup result or the selected member of a
  10691. // set of overloaded functions [...].
  10692. //
  10693. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10694. // can just check that here. Skip the rest of this function if we've already
  10695. // marked the function as used.
  10696. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10697. !IsPotentiallyEvaluatedContext(*this)) {
  10698. // C++11 [temp.inst]p3:
  10699. // Unless a function template specialization has been explicitly
  10700. // instantiated or explicitly specialized, the function template
  10701. // specialization is implicitly instantiated when the specialization is
  10702. // referenced in a context that requires a function definition to exist.
  10703. //
  10704. // We consider constexpr function templates to be referenced in a context
  10705. // that requires a definition to exist whenever they are referenced.
  10706. //
  10707. // FIXME: This instantiates constexpr functions too frequently. If this is
  10708. // really an unevaluated context (and we're not just in the definition of a
  10709. // function template or overload resolution or other cases which we
  10710. // incorrectly consider to be unevaluated contexts), and we're not in a
  10711. // subexpression which we actually need to evaluate (for instance, a
  10712. // template argument, array bound or an expression in a braced-init-list),
  10713. // we are not permitted to instantiate this constexpr function definition.
  10714. //
  10715. // FIXME: This also implicitly defines special members too frequently. They
  10716. // are only supposed to be implicitly defined if they are odr-used, but they
  10717. // are not odr-used from constant expressions in unevaluated contexts.
  10718. // However, they cannot be referenced if they are deleted, and they are
  10719. // deleted whenever the implicit definition of the special member would
  10720. // fail.
  10721. if (!Func->isConstexpr() || Func->getBody())
  10722. return;
  10723. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  10724. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  10725. return;
  10726. }
  10727. // Note that this declaration has been used.
  10728. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  10729. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  10730. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  10731. if (Constructor->isDefaultConstructor()) {
  10732. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  10733. return;
  10734. DefineImplicitDefaultConstructor(Loc, Constructor);
  10735. } else if (Constructor->isCopyConstructor()) {
  10736. DefineImplicitCopyConstructor(Loc, Constructor);
  10737. } else if (Constructor->isMoveConstructor()) {
  10738. DefineImplicitMoveConstructor(Loc, Constructor);
  10739. }
  10740. } else if (Constructor->getInheritedConstructor()) {
  10741. DefineInheritingConstructor(Loc, Constructor);
  10742. }
  10743. } else if (CXXDestructorDecl *Destructor =
  10744. dyn_cast<CXXDestructorDecl>(Func)) {
  10745. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  10746. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  10747. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  10748. return;
  10749. DefineImplicitDestructor(Loc, Destructor);
  10750. }
  10751. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  10752. MarkVTableUsed(Loc, Destructor->getParent());
  10753. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  10754. if (MethodDecl->isOverloadedOperator() &&
  10755. MethodDecl->getOverloadedOperator() == OO_Equal) {
  10756. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  10757. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  10758. if (MethodDecl->isCopyAssignmentOperator())
  10759. DefineImplicitCopyAssignment(Loc, MethodDecl);
  10760. else
  10761. DefineImplicitMoveAssignment(Loc, MethodDecl);
  10762. }
  10763. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  10764. MethodDecl->getParent()->isLambda()) {
  10765. CXXConversionDecl *Conversion =
  10766. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  10767. if (Conversion->isLambdaToBlockPointerConversion())
  10768. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  10769. else
  10770. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  10771. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  10772. MarkVTableUsed(Loc, MethodDecl->getParent());
  10773. }
  10774. // Recursive functions should be marked when used from another function.
  10775. // FIXME: Is this really right?
  10776. if (CurContext == Func) return;
  10777. // Resolve the exception specification for any function which is
  10778. // used: CodeGen will need it.
  10779. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  10780. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  10781. ResolveExceptionSpec(Loc, FPT);
  10782. if (!OdrUse) return;
  10783. // Implicit instantiation of function templates and member functions of
  10784. // class templates.
  10785. if (Func->isImplicitlyInstantiable()) {
  10786. bool AlreadyInstantiated = false;
  10787. SourceLocation PointOfInstantiation = Loc;
  10788. if (FunctionTemplateSpecializationInfo *SpecInfo
  10789. = Func->getTemplateSpecializationInfo()) {
  10790. if (SpecInfo->getPointOfInstantiation().isInvalid())
  10791. SpecInfo->setPointOfInstantiation(Loc);
  10792. else if (SpecInfo->getTemplateSpecializationKind()
  10793. == TSK_ImplicitInstantiation) {
  10794. AlreadyInstantiated = true;
  10795. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  10796. }
  10797. } else if (MemberSpecializationInfo *MSInfo
  10798. = Func->getMemberSpecializationInfo()) {
  10799. if (MSInfo->getPointOfInstantiation().isInvalid())
  10800. MSInfo->setPointOfInstantiation(Loc);
  10801. else if (MSInfo->getTemplateSpecializationKind()
  10802. == TSK_ImplicitInstantiation) {
  10803. AlreadyInstantiated = true;
  10804. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  10805. }
  10806. }
  10807. if (!AlreadyInstantiated || Func->isConstexpr()) {
  10808. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  10809. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  10810. ActiveTemplateInstantiations.size())
  10811. PendingLocalImplicitInstantiations.push_back(
  10812. std::make_pair(Func, PointOfInstantiation));
  10813. else if (Func->isConstexpr())
  10814. // Do not defer instantiations of constexpr functions, to avoid the
  10815. // expression evaluator needing to call back into Sema if it sees a
  10816. // call to such a function.
  10817. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  10818. else {
  10819. PendingInstantiations.push_back(std::make_pair(Func,
  10820. PointOfInstantiation));
  10821. // Notify the consumer that a function was implicitly instantiated.
  10822. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  10823. }
  10824. }
  10825. } else {
  10826. // Walk redefinitions, as some of them may be instantiable.
  10827. for (auto i : Func->redecls()) {
  10828. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  10829. MarkFunctionReferenced(Loc, i);
  10830. }
  10831. }
  10832. // Keep track of used but undefined functions.
  10833. if (!Func->isDefined()) {
  10834. if (mightHaveNonExternalLinkage(Func))
  10835. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  10836. else if (Func->getMostRecentDecl()->isInlined() &&
  10837. !LangOpts.GNUInline &&
  10838. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  10839. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  10840. }
  10841. // Normally the most current decl is marked used while processing the use and
  10842. // any subsequent decls are marked used by decl merging. This fails with
  10843. // template instantiation since marking can happen at the end of the file
  10844. // and, because of the two phase lookup, this function is called with at
  10845. // decl in the middle of a decl chain. We loop to maintain the invariant
  10846. // that once a decl is used, all decls after it are also used.
  10847. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  10848. F->markUsed(Context);
  10849. if (F == Func)
  10850. break;
  10851. }
  10852. }
  10853. static void
  10854. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  10855. VarDecl *var, DeclContext *DC) {
  10856. DeclContext *VarDC = var->getDeclContext();
  10857. // If the parameter still belongs to the translation unit, then
  10858. // we're actually just using one parameter in the declaration of
  10859. // the next.
  10860. if (isa<ParmVarDecl>(var) &&
  10861. isa<TranslationUnitDecl>(VarDC))
  10862. return;
  10863. // For C code, don't diagnose about capture if we're not actually in code
  10864. // right now; it's impossible to write a non-constant expression outside of
  10865. // function context, so we'll get other (more useful) diagnostics later.
  10866. //
  10867. // For C++, things get a bit more nasty... it would be nice to suppress this
  10868. // diagnostic for certain cases like using a local variable in an array bound
  10869. // for a member of a local class, but the correct predicate is not obvious.
  10870. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  10871. return;
  10872. if (isa<CXXMethodDecl>(VarDC) &&
  10873. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  10874. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  10875. << var->getIdentifier();
  10876. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  10877. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  10878. << var->getIdentifier() << fn->getDeclName();
  10879. } else if (isa<BlockDecl>(VarDC)) {
  10880. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  10881. << var->getIdentifier();
  10882. } else {
  10883. // FIXME: Is there any other context where a local variable can be
  10884. // declared?
  10885. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  10886. << var->getIdentifier();
  10887. }
  10888. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  10889. << var->getIdentifier();
  10890. // FIXME: Add additional diagnostic info about class etc. which prevents
  10891. // capture.
  10892. }
  10893. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  10894. bool &SubCapturesAreNested,
  10895. QualType &CaptureType,
  10896. QualType &DeclRefType) {
  10897. // Check whether we've already captured it.
  10898. if (CSI->CaptureMap.count(Var)) {
  10899. // If we found a capture, any subcaptures are nested.
  10900. SubCapturesAreNested = true;
  10901. // Retrieve the capture type for this variable.
  10902. CaptureType = CSI->getCapture(Var).getCaptureType();
  10903. // Compute the type of an expression that refers to this variable.
  10904. DeclRefType = CaptureType.getNonReferenceType();
  10905. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  10906. if (Cap.isCopyCapture() &&
  10907. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  10908. DeclRefType.addConst();
  10909. return true;
  10910. }
  10911. return false;
  10912. }
  10913. // Only block literals, captured statements, and lambda expressions can
  10914. // capture; other scopes don't work.
  10915. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  10916. SourceLocation Loc,
  10917. const bool Diagnose, Sema &S) {
  10918. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  10919. return getLambdaAwareParentOfDeclContext(DC);
  10920. else if (Var->hasLocalStorage()) {
  10921. if (Diagnose)
  10922. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  10923. }
  10924. return nullptr;
  10925. }
  10926. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  10927. // certain types of variables (unnamed, variably modified types etc.)
  10928. // so check for eligibility.
  10929. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  10930. SourceLocation Loc,
  10931. const bool Diagnose, Sema &S) {
  10932. bool IsBlock = isa<BlockScopeInfo>(CSI);
  10933. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  10934. // Lambdas are not allowed to capture unnamed variables
  10935. // (e.g. anonymous unions).
  10936. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  10937. // assuming that's the intent.
  10938. if (IsLambda && !Var->getDeclName()) {
  10939. if (Diagnose) {
  10940. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  10941. S.Diag(Var->getLocation(), diag::note_declared_at);
  10942. }
  10943. return false;
  10944. }
  10945. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  10946. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  10947. if (Diagnose) {
  10948. S.Diag(Loc, diag::err_ref_vm_type);
  10949. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10950. << Var->getDeclName();
  10951. }
  10952. return false;
  10953. }
  10954. // Prohibit structs with flexible array members too.
  10955. // We cannot capture what is in the tail end of the struct.
  10956. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  10957. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  10958. if (Diagnose) {
  10959. if (IsBlock)
  10960. S.Diag(Loc, diag::err_ref_flexarray_type);
  10961. else
  10962. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  10963. << Var->getDeclName();
  10964. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10965. << Var->getDeclName();
  10966. }
  10967. return false;
  10968. }
  10969. }
  10970. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  10971. // Lambdas and captured statements are not allowed to capture __block
  10972. // variables; they don't support the expected semantics.
  10973. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  10974. if (Diagnose) {
  10975. S.Diag(Loc, diag::err_capture_block_variable)
  10976. << Var->getDeclName() << !IsLambda;
  10977. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10978. << Var->getDeclName();
  10979. }
  10980. return false;
  10981. }
  10982. return true;
  10983. }
  10984. // Returns true if the capture by block was successful.
  10985. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  10986. SourceLocation Loc,
  10987. const bool BuildAndDiagnose,
  10988. QualType &CaptureType,
  10989. QualType &DeclRefType,
  10990. const bool Nested,
  10991. Sema &S) {
  10992. Expr *CopyExpr = nullptr;
  10993. bool ByRef = false;
  10994. // Blocks are not allowed to capture arrays.
  10995. if (CaptureType->isArrayType()) {
  10996. if (BuildAndDiagnose) {
  10997. S.Diag(Loc, diag::err_ref_array_type);
  10998. S.Diag(Var->getLocation(), diag::note_previous_decl)
  10999. << Var->getDeclName();
  11000. }
  11001. return false;
  11002. }
  11003. // Forbid the block-capture of autoreleasing variables.
  11004. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11005. if (BuildAndDiagnose) {
  11006. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  11007. << /*block*/ 0;
  11008. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11009. << Var->getDeclName();
  11010. }
  11011. return false;
  11012. }
  11013. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11014. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  11015. // Block capture by reference does not change the capture or
  11016. // declaration reference types.
  11017. ByRef = true;
  11018. } else {
  11019. // Block capture by copy introduces 'const'.
  11020. CaptureType = CaptureType.getNonReferenceType().withConst();
  11021. DeclRefType = CaptureType;
  11022. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  11023. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  11024. // The capture logic needs the destructor, so make sure we mark it.
  11025. // Usually this is unnecessary because most local variables have
  11026. // their destructors marked at declaration time, but parameters are
  11027. // an exception because it's technically only the call site that
  11028. // actually requires the destructor.
  11029. if (isa<ParmVarDecl>(Var))
  11030. S.FinalizeVarWithDestructor(Var, Record);
  11031. // Enter a new evaluation context to insulate the copy
  11032. // full-expression.
  11033. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  11034. // According to the blocks spec, the capture of a variable from
  11035. // the stack requires a const copy constructor. This is not true
  11036. // of the copy/move done to move a __block variable to the heap.
  11037. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  11038. DeclRefType.withConst(),
  11039. VK_LValue, Loc);
  11040. ExprResult Result
  11041. = S.PerformCopyInitialization(
  11042. InitializedEntity::InitializeBlock(Var->getLocation(),
  11043. CaptureType, false),
  11044. Loc, DeclRef);
  11045. // Build a full-expression copy expression if initialization
  11046. // succeeded and used a non-trivial constructor. Recover from
  11047. // errors by pretending that the copy isn't necessary.
  11048. if (!Result.isInvalid() &&
  11049. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  11050. ->isTrivial()) {
  11051. Result = S.MaybeCreateExprWithCleanups(Result);
  11052. CopyExpr = Result.get();
  11053. }
  11054. }
  11055. }
  11056. }
  11057. // Actually capture the variable.
  11058. if (BuildAndDiagnose)
  11059. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  11060. SourceLocation(), CaptureType, CopyExpr);
  11061. return true;
  11062. }
  11063. /// \brief Capture the given variable in the captured region.
  11064. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  11065. VarDecl *Var,
  11066. SourceLocation Loc,
  11067. const bool BuildAndDiagnose,
  11068. QualType &CaptureType,
  11069. QualType &DeclRefType,
  11070. const bool RefersToCapturedVariable,
  11071. Sema &S) {
  11072. // By default, capture variables by reference.
  11073. bool ByRef = true;
  11074. // Using an LValue reference type is consistent with Lambdas (see below).
  11075. if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var))
  11076. DeclRefType = DeclRefType.getUnqualifiedType();
  11077. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11078. Expr *CopyExpr = nullptr;
  11079. if (BuildAndDiagnose) {
  11080. // The current implementation assumes that all variables are captured
  11081. // by references. Since there is no capture by copy, no expression
  11082. // evaluation will be needed.
  11083. RecordDecl *RD = RSI->TheRecordDecl;
  11084. FieldDecl *Field
  11085. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  11086. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  11087. nullptr, false, ICIS_NoInit);
  11088. Field->setImplicit(true);
  11089. Field->setAccess(AS_private);
  11090. RD->addDecl(Field);
  11091. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  11092. DeclRefType, VK_LValue, Loc);
  11093. Var->setReferenced(true);
  11094. Var->markUsed(S.Context);
  11095. }
  11096. // Actually capture the variable.
  11097. if (BuildAndDiagnose)
  11098. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  11099. SourceLocation(), CaptureType, CopyExpr);
  11100. return true;
  11101. }
  11102. /// \brief Create a field within the lambda class for the variable
  11103. /// being captured.
  11104. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
  11105. QualType FieldType, QualType DeclRefType,
  11106. SourceLocation Loc,
  11107. bool RefersToCapturedVariable) {
  11108. CXXRecordDecl *Lambda = LSI->Lambda;
  11109. // Build the non-static data member.
  11110. FieldDecl *Field
  11111. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  11112. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  11113. nullptr, false, ICIS_NoInit);
  11114. Field->setImplicit(true);
  11115. Field->setAccess(AS_private);
  11116. Lambda->addDecl(Field);
  11117. }
  11118. /// \brief Capture the given variable in the lambda.
  11119. static bool captureInLambda(LambdaScopeInfo *LSI,
  11120. VarDecl *Var,
  11121. SourceLocation Loc,
  11122. const bool BuildAndDiagnose,
  11123. QualType &CaptureType,
  11124. QualType &DeclRefType,
  11125. const bool RefersToCapturedVariable,
  11126. const Sema::TryCaptureKind Kind,
  11127. SourceLocation EllipsisLoc,
  11128. const bool IsTopScope,
  11129. Sema &S) {
  11130. // Determine whether we are capturing by reference or by value.
  11131. bool ByRef = false;
  11132. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  11133. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  11134. } else {
  11135. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  11136. }
  11137. // Compute the type of the field that will capture this variable.
  11138. if (ByRef) {
  11139. // C++11 [expr.prim.lambda]p15:
  11140. // An entity is captured by reference if it is implicitly or
  11141. // explicitly captured but not captured by copy. It is
  11142. // unspecified whether additional unnamed non-static data
  11143. // members are declared in the closure type for entities
  11144. // captured by reference.
  11145. //
  11146. // FIXME: It is not clear whether we want to build an lvalue reference
  11147. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  11148. // to do the former, while EDG does the latter. Core issue 1249 will
  11149. // clarify, but for now we follow GCC because it's a more permissive and
  11150. // easily defensible position.
  11151. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11152. } else {
  11153. // C++11 [expr.prim.lambda]p14:
  11154. // For each entity captured by copy, an unnamed non-static
  11155. // data member is declared in the closure type. The
  11156. // declaration order of these members is unspecified. The type
  11157. // of such a data member is the type of the corresponding
  11158. // captured entity if the entity is not a reference to an
  11159. // object, or the referenced type otherwise. [Note: If the
  11160. // captured entity is a reference to a function, the
  11161. // corresponding data member is also a reference to a
  11162. // function. - end note ]
  11163. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  11164. if (!RefType->getPointeeType()->isFunctionType())
  11165. CaptureType = RefType->getPointeeType();
  11166. }
  11167. // Forbid the lambda copy-capture of autoreleasing variables.
  11168. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11169. if (BuildAndDiagnose) {
  11170. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  11171. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11172. << Var->getDeclName();
  11173. }
  11174. return false;
  11175. }
  11176. // Make sure that by-copy captures are of a complete and non-abstract type.
  11177. if (BuildAndDiagnose) {
  11178. if (!CaptureType->isDependentType() &&
  11179. S.RequireCompleteType(Loc, CaptureType,
  11180. diag::err_capture_of_incomplete_type,
  11181. Var->getDeclName()))
  11182. return false;
  11183. if (S.RequireNonAbstractType(Loc, CaptureType,
  11184. diag::err_capture_of_abstract_type))
  11185. return false;
  11186. }
  11187. }
  11188. // Capture this variable in the lambda.
  11189. if (BuildAndDiagnose)
  11190. addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
  11191. RefersToCapturedVariable);
  11192. // Compute the type of a reference to this captured variable.
  11193. if (ByRef)
  11194. DeclRefType = CaptureType.getNonReferenceType();
  11195. else {
  11196. // C++ [expr.prim.lambda]p5:
  11197. // The closure type for a lambda-expression has a public inline
  11198. // function call operator [...]. This function call operator is
  11199. // declared const (9.3.1) if and only if the lambda-expression’s
  11200. // parameter-declaration-clause is not followed by mutable.
  11201. DeclRefType = CaptureType.getNonReferenceType();
  11202. if (!LSI->Mutable && !CaptureType->isReferenceType())
  11203. DeclRefType.addConst();
  11204. }
  11205. // Add the capture.
  11206. if (BuildAndDiagnose)
  11207. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  11208. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  11209. return true;
  11210. }
  11211. bool Sema::tryCaptureVariable(
  11212. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  11213. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  11214. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  11215. // An init-capture is notionally from the context surrounding its
  11216. // declaration, but its parent DC is the lambda class.
  11217. DeclContext *VarDC = Var->getDeclContext();
  11218. if (Var->isInitCapture())
  11219. VarDC = VarDC->getParent();
  11220. DeclContext *DC = CurContext;
  11221. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  11222. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  11223. // We need to sync up the Declaration Context with the
  11224. // FunctionScopeIndexToStopAt
  11225. if (FunctionScopeIndexToStopAt) {
  11226. unsigned FSIndex = FunctionScopes.size() - 1;
  11227. while (FSIndex != MaxFunctionScopesIndex) {
  11228. DC = getLambdaAwareParentOfDeclContext(DC);
  11229. --FSIndex;
  11230. }
  11231. }
  11232. // If the variable is declared in the current context, there is no need to
  11233. // capture it.
  11234. if (VarDC == DC) return true;
  11235. // Capture global variables if it is required to use private copy of this
  11236. // variable.
  11237. bool IsGlobal = !Var->hasLocalStorage();
  11238. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  11239. return true;
  11240. // Walk up the stack to determine whether we can capture the variable,
  11241. // performing the "simple" checks that don't depend on type. We stop when
  11242. // we've either hit the declared scope of the variable or find an existing
  11243. // capture of that variable. We start from the innermost capturing-entity
  11244. // (the DC) and ensure that all intervening capturing-entities
  11245. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  11246. // declcontext can either capture the variable or have already captured
  11247. // the variable.
  11248. CaptureType = Var->getType();
  11249. DeclRefType = CaptureType.getNonReferenceType();
  11250. bool Nested = false;
  11251. bool Explicit = (Kind != TryCapture_Implicit);
  11252. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  11253. unsigned OpenMPLevel = 0;
  11254. do {
  11255. // Only block literals, captured statements, and lambda expressions can
  11256. // capture; other scopes don't work.
  11257. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11258. ExprLoc,
  11259. BuildAndDiagnose,
  11260. *this);
  11261. // We need to check for the parent *first* because, if we *have*
  11262. // private-captured a global variable, we need to recursively capture it in
  11263. // intermediate blocks, lambdas, etc.
  11264. if (!ParentDC) {
  11265. if (IsGlobal) {
  11266. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11267. break;
  11268. }
  11269. return true;
  11270. }
  11271. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11272. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11273. // Check whether we've already captured it.
  11274. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11275. DeclRefType))
  11276. break;
  11277. if (getLangOpts().OpenMP) {
  11278. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11279. // OpenMP private variables should not be captured in outer scope, so
  11280. // just break here.
  11281. if (RSI->CapRegionKind == CR_OpenMP) {
  11282. if (isOpenMPPrivateVar(Var, OpenMPLevel)) {
  11283. Nested = true;
  11284. DeclRefType = DeclRefType.getUnqualifiedType();
  11285. CaptureType = Context.getLValueReferenceType(DeclRefType);
  11286. break;
  11287. }
  11288. ++OpenMPLevel;
  11289. }
  11290. }
  11291. }
  11292. // If we are instantiating a generic lambda call operator body,
  11293. // we do not want to capture new variables. What was captured
  11294. // during either a lambdas transformation or initial parsing
  11295. // should be used.
  11296. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11297. if (BuildAndDiagnose) {
  11298. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11299. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11300. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11301. Diag(Var->getLocation(), diag::note_previous_decl)
  11302. << Var->getDeclName();
  11303. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11304. } else
  11305. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11306. }
  11307. return true;
  11308. }
  11309. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11310. // certain types of variables (unnamed, variably modified types etc.)
  11311. // so check for eligibility.
  11312. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11313. return true;
  11314. // Try to capture variable-length arrays types.
  11315. if (Var->getType()->isVariablyModifiedType()) {
  11316. // We're going to walk down into the type and look for VLA
  11317. // expressions.
  11318. QualType QTy = Var->getType();
  11319. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11320. QTy = PVD->getOriginalType();
  11321. do {
  11322. const Type *Ty = QTy.getTypePtr();
  11323. switch (Ty->getTypeClass()) {
  11324. #define TYPE(Class, Base)
  11325. #define ABSTRACT_TYPE(Class, Base)
  11326. #define NON_CANONICAL_TYPE(Class, Base)
  11327. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11328. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11329. #include "clang/AST/TypeNodes.def"
  11330. QTy = QualType();
  11331. break;
  11332. // These types are never variably-modified.
  11333. case Type::Builtin:
  11334. case Type::Complex:
  11335. case Type::Vector:
  11336. case Type::ExtVector:
  11337. case Type::Record:
  11338. case Type::Enum:
  11339. case Type::Elaborated:
  11340. case Type::TemplateSpecialization:
  11341. case Type::ObjCObject:
  11342. case Type::ObjCInterface:
  11343. case Type::ObjCObjectPointer:
  11344. llvm_unreachable("type class is never variably-modified!");
  11345. case Type::Adjusted:
  11346. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11347. break;
  11348. case Type::Decayed:
  11349. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11350. break;
  11351. case Type::Pointer:
  11352. QTy = cast<PointerType>(Ty)->getPointeeType();
  11353. break;
  11354. case Type::BlockPointer:
  11355. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11356. break;
  11357. case Type::LValueReference:
  11358. case Type::RValueReference:
  11359. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11360. break;
  11361. case Type::MemberPointer:
  11362. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11363. break;
  11364. case Type::ConstantArray:
  11365. case Type::IncompleteArray:
  11366. // Losing element qualification here is fine.
  11367. QTy = cast<ArrayType>(Ty)->getElementType();
  11368. break;
  11369. case Type::VariableArray: {
  11370. // Losing element qualification here is fine.
  11371. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11372. // Unknown size indication requires no size computation.
  11373. // Otherwise, evaluate and record it.
  11374. if (auto Size = VAT->getSizeExpr()) {
  11375. if (!CSI->isVLATypeCaptured(VAT)) {
  11376. RecordDecl *CapRecord = nullptr;
  11377. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11378. CapRecord = LSI->Lambda;
  11379. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11380. CapRecord = CRSI->TheRecordDecl;
  11381. }
  11382. if (CapRecord) {
  11383. auto ExprLoc = Size->getExprLoc();
  11384. auto SizeType = Context.getSizeType();
  11385. // Build the non-static data member.
  11386. auto Field = FieldDecl::Create(
  11387. Context, CapRecord, ExprLoc, ExprLoc,
  11388. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11389. /*BW*/ nullptr, /*Mutable*/ false,
  11390. /*InitStyle*/ ICIS_NoInit);
  11391. Field->setImplicit(true);
  11392. Field->setAccess(AS_private);
  11393. Field->setCapturedVLAType(VAT);
  11394. CapRecord->addDecl(Field);
  11395. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11396. }
  11397. }
  11398. }
  11399. QTy = VAT->getElementType();
  11400. break;
  11401. }
  11402. case Type::FunctionProto:
  11403. case Type::FunctionNoProto:
  11404. QTy = cast<FunctionType>(Ty)->getReturnType();
  11405. break;
  11406. case Type::Paren:
  11407. case Type::TypeOf:
  11408. case Type::UnaryTransform:
  11409. case Type::Attributed:
  11410. case Type::SubstTemplateTypeParm:
  11411. case Type::PackExpansion:
  11412. // Keep walking after single level desugaring.
  11413. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11414. break;
  11415. case Type::Typedef:
  11416. QTy = cast<TypedefType>(Ty)->desugar();
  11417. break;
  11418. case Type::Decltype:
  11419. QTy = cast<DecltypeType>(Ty)->desugar();
  11420. break;
  11421. case Type::Auto:
  11422. QTy = cast<AutoType>(Ty)->getDeducedType();
  11423. break;
  11424. case Type::TypeOfExpr:
  11425. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11426. break;
  11427. case Type::Atomic:
  11428. QTy = cast<AtomicType>(Ty)->getValueType();
  11429. break;
  11430. }
  11431. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11432. }
  11433. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11434. // No capture-default, and this is not an explicit capture
  11435. // so cannot capture this variable.
  11436. if (BuildAndDiagnose) {
  11437. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11438. Diag(Var->getLocation(), diag::note_previous_decl)
  11439. << Var->getDeclName();
  11440. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11441. diag::note_lambda_decl);
  11442. // FIXME: If we error out because an outer lambda can not implicitly
  11443. // capture a variable that an inner lambda explicitly captures, we
  11444. // should have the inner lambda do the explicit capture - because
  11445. // it makes for cleaner diagnostics later. This would purely be done
  11446. // so that the diagnostic does not misleadingly claim that a variable
  11447. // can not be captured by a lambda implicitly even though it is captured
  11448. // explicitly. Suggestion:
  11449. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11450. // at the function head
  11451. // - cache the StartingDeclContext - this must be a lambda
  11452. // - captureInLambda in the innermost lambda the variable.
  11453. }
  11454. return true;
  11455. }
  11456. FunctionScopesIndex--;
  11457. DC = ParentDC;
  11458. Explicit = false;
  11459. } while (!VarDC->Equals(DC));
  11460. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11461. // computing the type of the capture at each step, checking type-specific
  11462. // requirements, and adding captures if requested.
  11463. // If the variable had already been captured previously, we start capturing
  11464. // at the lambda nested within that one.
  11465. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11466. ++I) {
  11467. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11468. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11469. if (!captureInBlock(BSI, Var, ExprLoc,
  11470. BuildAndDiagnose, CaptureType,
  11471. DeclRefType, Nested, *this))
  11472. return true;
  11473. Nested = true;
  11474. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11475. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11476. BuildAndDiagnose, CaptureType,
  11477. DeclRefType, Nested, *this))
  11478. return true;
  11479. Nested = true;
  11480. } else {
  11481. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11482. if (!captureInLambda(LSI, Var, ExprLoc,
  11483. BuildAndDiagnose, CaptureType,
  11484. DeclRefType, Nested, Kind, EllipsisLoc,
  11485. /*IsTopScope*/I == N - 1, *this))
  11486. return true;
  11487. Nested = true;
  11488. }
  11489. }
  11490. return false;
  11491. }
  11492. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11493. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11494. QualType CaptureType;
  11495. QualType DeclRefType;
  11496. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11497. /*BuildAndDiagnose=*/true, CaptureType,
  11498. DeclRefType, nullptr);
  11499. }
  11500. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11501. QualType CaptureType;
  11502. QualType DeclRefType;
  11503. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11504. /*BuildAndDiagnose=*/false, CaptureType,
  11505. DeclRefType, nullptr);
  11506. }
  11507. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11508. QualType CaptureType;
  11509. QualType DeclRefType;
  11510. // Determine whether we can capture this variable.
  11511. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11512. /*BuildAndDiagnose=*/false, CaptureType,
  11513. DeclRefType, nullptr))
  11514. return QualType();
  11515. return DeclRefType;
  11516. }
  11517. // If either the type of the variable or the initializer is dependent,
  11518. // return false. Otherwise, determine whether the variable is a constant
  11519. // expression. Use this if you need to know if a variable that might or
  11520. // might not be dependent is truly a constant expression.
  11521. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11522. ASTContext &Context) {
  11523. if (Var->getType()->isDependentType())
  11524. return false;
  11525. const VarDecl *DefVD = nullptr;
  11526. Var->getAnyInitializer(DefVD);
  11527. if (!DefVD)
  11528. return false;
  11529. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11530. Expr *Init = cast<Expr>(Eval->Value);
  11531. if (Init->isValueDependent())
  11532. return false;
  11533. return IsVariableAConstantExpression(Var, Context);
  11534. }
  11535. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11536. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11537. // an object that satisfies the requirements for appearing in a
  11538. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11539. // is immediately applied." This function handles the lvalue-to-rvalue
  11540. // conversion part.
  11541. MaybeODRUseExprs.erase(E->IgnoreParens());
  11542. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11543. // to a variable that is a constant expression, and if so, identify it as
  11544. // a reference to a variable that does not involve an odr-use of that
  11545. // variable.
  11546. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11547. Expr *SansParensExpr = E->IgnoreParens();
  11548. VarDecl *Var = nullptr;
  11549. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11550. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11551. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11552. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11553. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11554. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11555. }
  11556. }
  11557. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11558. Res = CorrectDelayedTyposInExpr(Res);
  11559. if (!Res.isUsable())
  11560. return Res;
  11561. // If a constant-expression is a reference to a variable where we delay
  11562. // deciding whether it is an odr-use, just assume we will apply the
  11563. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11564. // (a non-type template argument), we have special handling anyway.
  11565. UpdateMarkingForLValueToRValue(Res.get());
  11566. return Res;
  11567. }
  11568. void Sema::CleanupVarDeclMarking() {
  11569. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11570. e = MaybeODRUseExprs.end();
  11571. i != e; ++i) {
  11572. VarDecl *Var;
  11573. SourceLocation Loc;
  11574. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11575. Var = cast<VarDecl>(DRE->getDecl());
  11576. Loc = DRE->getLocation();
  11577. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11578. Var = cast<VarDecl>(ME->getMemberDecl());
  11579. Loc = ME->getMemberLoc();
  11580. } else {
  11581. llvm_unreachable("Unexpected expression");
  11582. }
  11583. MarkVarDeclODRUsed(Var, Loc, *this,
  11584. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11585. }
  11586. MaybeODRUseExprs.clear();
  11587. }
  11588. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11589. VarDecl *Var, Expr *E) {
  11590. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11591. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11592. Var->setReferenced();
  11593. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11594. bool MarkODRUsed = true;
  11595. // If the context is not potentially evaluated, this is not an odr-use and
  11596. // does not trigger instantiation.
  11597. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11598. if (SemaRef.isUnevaluatedContext())
  11599. return;
  11600. // If we don't yet know whether this context is going to end up being an
  11601. // evaluated context, and we're referencing a variable from an enclosing
  11602. // scope, add a potential capture.
  11603. //
  11604. // FIXME: Is this necessary? These contexts are only used for default
  11605. // arguments, where local variables can't be used.
  11606. const bool RefersToEnclosingScope =
  11607. (SemaRef.CurContext != Var->getDeclContext() &&
  11608. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11609. if (RefersToEnclosingScope) {
  11610. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11611. // If a variable could potentially be odr-used, defer marking it so
  11612. // until we finish analyzing the full expression for any
  11613. // lvalue-to-rvalue
  11614. // or discarded value conversions that would obviate odr-use.
  11615. // Add it to the list of potential captures that will be analyzed
  11616. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11617. // unless the variable is a reference that was initialized by a constant
  11618. // expression (this will never need to be captured or odr-used).
  11619. assert(E && "Capture variable should be used in an expression.");
  11620. if (!Var->getType()->isReferenceType() ||
  11621. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11622. LSI->addPotentialCapture(E->IgnoreParens());
  11623. }
  11624. }
  11625. if (!isTemplateInstantiation(TSK))
  11626. return;
  11627. // Instantiate, but do not mark as odr-used, variable templates.
  11628. MarkODRUsed = false;
  11629. }
  11630. VarTemplateSpecializationDecl *VarSpec =
  11631. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11632. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11633. "Can't instantiate a partial template specialization.");
  11634. // Perform implicit instantiation of static data members, static data member
  11635. // templates of class templates, and variable template specializations. Delay
  11636. // instantiations of variable templates, except for those that could be used
  11637. // in a constant expression.
  11638. if (isTemplateInstantiation(TSK)) {
  11639. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11640. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11641. if (Var->getPointOfInstantiation().isInvalid()) {
  11642. // This is a modification of an existing AST node. Notify listeners.
  11643. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11644. L->StaticDataMemberInstantiated(Var);
  11645. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11646. // Don't bother trying to instantiate it again, unless we might need
  11647. // its initializer before we get to the end of the TU.
  11648. TryInstantiating = false;
  11649. }
  11650. if (Var->getPointOfInstantiation().isInvalid())
  11651. Var->setTemplateSpecializationKind(TSK, Loc);
  11652. if (TryInstantiating) {
  11653. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11654. bool InstantiationDependent = false;
  11655. bool IsNonDependent =
  11656. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11657. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11658. : true;
  11659. // Do not instantiate specializations that are still type-dependent.
  11660. if (IsNonDependent) {
  11661. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11662. // Do not defer instantiations of variables which could be used in a
  11663. // constant expression.
  11664. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11665. } else {
  11666. SemaRef.PendingInstantiations
  11667. .push_back(std::make_pair(Var, PointOfInstantiation));
  11668. }
  11669. }
  11670. }
  11671. }
  11672. if(!MarkODRUsed) return;
  11673. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11674. // the requirements for appearing in a constant expression (5.19) and, if
  11675. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11676. // is immediately applied." We check the first part here, and
  11677. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11678. // Note that we use the C++11 definition everywhere because nothing in
  11679. // C++03 depends on whether we get the C++03 version correct. The second
  11680. // part does not apply to references, since they are not objects.
  11681. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11682. // A reference initialized by a constant expression can never be
  11683. // odr-used, so simply ignore it.
  11684. if (!Var->getType()->isReferenceType())
  11685. SemaRef.MaybeODRUseExprs.insert(E);
  11686. } else
  11687. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11688. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11689. }
  11690. /// \brief Mark a variable referenced, and check whether it is odr-used
  11691. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11692. /// used directly for normal expressions referring to VarDecl.
  11693. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11694. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11695. }
  11696. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11697. Decl *D, Expr *E, bool OdrUse) {
  11698. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11699. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11700. return;
  11701. }
  11702. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11703. // If this is a call to a method via a cast, also mark the method in the
  11704. // derived class used in case codegen can devirtualize the call.
  11705. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11706. if (!ME)
  11707. return;
  11708. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11709. if (!MD)
  11710. return;
  11711. // Only attempt to devirtualize if this is truly a virtual call.
  11712. bool IsVirtualCall = MD->isVirtual() &&
  11713. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  11714. if (!IsVirtualCall)
  11715. return;
  11716. const Expr *Base = ME->getBase();
  11717. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  11718. if (!MostDerivedClassDecl)
  11719. return;
  11720. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  11721. if (!DM || DM->isPure())
  11722. return;
  11723. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  11724. }
  11725. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  11726. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  11727. // TODO: update this with DR# once a defect report is filed.
  11728. // C++11 defect. The address of a pure member should not be an ODR use, even
  11729. // if it's a qualified reference.
  11730. bool OdrUse = true;
  11731. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  11732. if (Method->isVirtual())
  11733. OdrUse = false;
  11734. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  11735. }
  11736. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  11737. void Sema::MarkMemberReferenced(MemberExpr *E) {
  11738. // C++11 [basic.def.odr]p2:
  11739. // A non-overloaded function whose name appears as a potentially-evaluated
  11740. // expression or a member of a set of candidate functions, if selected by
  11741. // overload resolution when referred to from a potentially-evaluated
  11742. // expression, is odr-used, unless it is a pure virtual function and its
  11743. // name is not explicitly qualified.
  11744. bool OdrUse = true;
  11745. if (E->performsVirtualDispatch(getLangOpts())) {
  11746. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  11747. if (Method->isPure())
  11748. OdrUse = false;
  11749. }
  11750. SourceLocation Loc = E->getMemberLoc().isValid() ?
  11751. E->getMemberLoc() : E->getLocStart();
  11752. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  11753. }
  11754. /// \brief Perform marking for a reference to an arbitrary declaration. It
  11755. /// marks the declaration referenced, and performs odr-use checking for
  11756. /// functions and variables. This method should not be used when building a
  11757. /// normal expression which refers to a variable.
  11758. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  11759. if (OdrUse) {
  11760. if (auto *VD = dyn_cast<VarDecl>(D)) {
  11761. MarkVariableReferenced(Loc, VD);
  11762. return;
  11763. }
  11764. }
  11765. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  11766. MarkFunctionReferenced(Loc, FD, OdrUse);
  11767. return;
  11768. }
  11769. D->setReferenced();
  11770. }
  11771. namespace {
  11772. // Mark all of the declarations referenced
  11773. // FIXME: Not fully implemented yet! We need to have a better understanding
  11774. // of when we're entering
  11775. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  11776. Sema &S;
  11777. SourceLocation Loc;
  11778. public:
  11779. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  11780. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  11781. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  11782. bool TraverseRecordType(RecordType *T);
  11783. };
  11784. }
  11785. bool MarkReferencedDecls::TraverseTemplateArgument(
  11786. const TemplateArgument &Arg) {
  11787. if (Arg.getKind() == TemplateArgument::Declaration) {
  11788. if (Decl *D = Arg.getAsDecl())
  11789. S.MarkAnyDeclReferenced(Loc, D, true);
  11790. }
  11791. return Inherited::TraverseTemplateArgument(Arg);
  11792. }
  11793. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  11794. if (ClassTemplateSpecializationDecl *Spec
  11795. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  11796. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  11797. return TraverseTemplateArguments(Args.data(), Args.size());
  11798. }
  11799. return true;
  11800. }
  11801. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  11802. MarkReferencedDecls Marker(*this, Loc);
  11803. Marker.TraverseType(Context.getCanonicalType(T));
  11804. }
  11805. namespace {
  11806. /// \brief Helper class that marks all of the declarations referenced by
  11807. /// potentially-evaluated subexpressions as "referenced".
  11808. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  11809. Sema &S;
  11810. bool SkipLocalVariables;
  11811. public:
  11812. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  11813. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  11814. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  11815. void VisitDeclRefExpr(DeclRefExpr *E) {
  11816. // If we were asked not to visit local variables, don't.
  11817. if (SkipLocalVariables) {
  11818. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  11819. if (VD->hasLocalStorage())
  11820. return;
  11821. }
  11822. S.MarkDeclRefReferenced(E);
  11823. }
  11824. void VisitMemberExpr(MemberExpr *E) {
  11825. S.MarkMemberReferenced(E);
  11826. Inherited::VisitMemberExpr(E);
  11827. }
  11828. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  11829. S.MarkFunctionReferenced(E->getLocStart(),
  11830. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  11831. Visit(E->getSubExpr());
  11832. }
  11833. void VisitCXXNewExpr(CXXNewExpr *E) {
  11834. if (E->getOperatorNew())
  11835. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  11836. if (E->getOperatorDelete())
  11837. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  11838. Inherited::VisitCXXNewExpr(E);
  11839. }
  11840. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  11841. if (E->getOperatorDelete())
  11842. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  11843. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  11844. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  11845. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  11846. S.MarkFunctionReferenced(E->getLocStart(),
  11847. S.LookupDestructor(Record));
  11848. }
  11849. Inherited::VisitCXXDeleteExpr(E);
  11850. }
  11851. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  11852. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  11853. Inherited::VisitCXXConstructExpr(E);
  11854. }
  11855. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  11856. Visit(E->getExpr());
  11857. }
  11858. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  11859. Inherited::VisitImplicitCastExpr(E);
  11860. if (E->getCastKind() == CK_LValueToRValue)
  11861. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  11862. }
  11863. };
  11864. }
  11865. /// \brief Mark any declarations that appear within this expression or any
  11866. /// potentially-evaluated subexpressions as "referenced".
  11867. ///
  11868. /// \param SkipLocalVariables If true, don't mark local variables as
  11869. /// 'referenced'.
  11870. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  11871. bool SkipLocalVariables) {
  11872. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  11873. }
  11874. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  11875. /// of the program being compiled.
  11876. ///
  11877. /// This routine emits the given diagnostic when the code currently being
  11878. /// type-checked is "potentially evaluated", meaning that there is a
  11879. /// possibility that the code will actually be executable. Code in sizeof()
  11880. /// expressions, code used only during overload resolution, etc., are not
  11881. /// potentially evaluated. This routine will suppress such diagnostics or,
  11882. /// in the absolutely nutty case of potentially potentially evaluated
  11883. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  11884. /// later.
  11885. ///
  11886. /// This routine should be used for all diagnostics that describe the run-time
  11887. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  11888. /// Failure to do so will likely result in spurious diagnostics or failures
  11889. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  11890. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  11891. const PartialDiagnostic &PD) {
  11892. switch (ExprEvalContexts.back().Context) {
  11893. case Unevaluated:
  11894. case UnevaluatedAbstract:
  11895. // The argument will never be evaluated, so don't complain.
  11896. break;
  11897. case ConstantEvaluated:
  11898. // Relevant diagnostics should be produced by constant evaluation.
  11899. break;
  11900. case PotentiallyEvaluated:
  11901. case PotentiallyEvaluatedIfUsed:
  11902. if (Statement && getCurFunctionOrMethodDecl()) {
  11903. FunctionScopes.back()->PossiblyUnreachableDiags.
  11904. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  11905. }
  11906. else
  11907. Diag(Loc, PD);
  11908. return true;
  11909. }
  11910. return false;
  11911. }
  11912. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  11913. CallExpr *CE, FunctionDecl *FD) {
  11914. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  11915. return false;
  11916. // If we're inside a decltype's expression, don't check for a valid return
  11917. // type or construct temporaries until we know whether this is the last call.
  11918. if (ExprEvalContexts.back().IsDecltype) {
  11919. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  11920. return false;
  11921. }
  11922. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  11923. FunctionDecl *FD;
  11924. CallExpr *CE;
  11925. public:
  11926. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  11927. : FD(FD), CE(CE) { }
  11928. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  11929. if (!FD) {
  11930. S.Diag(Loc, diag::err_call_incomplete_return)
  11931. << T << CE->getSourceRange();
  11932. return;
  11933. }
  11934. S.Diag(Loc, diag::err_call_function_incomplete_return)
  11935. << CE->getSourceRange() << FD->getDeclName() << T;
  11936. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  11937. << FD->getDeclName();
  11938. }
  11939. } Diagnoser(FD, CE);
  11940. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  11941. return true;
  11942. return false;
  11943. }
  11944. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  11945. // will prevent this condition from triggering, which is what we want.
  11946. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  11947. SourceLocation Loc;
  11948. unsigned diagnostic = diag::warn_condition_is_assignment;
  11949. bool IsOrAssign = false;
  11950. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  11951. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  11952. return;
  11953. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  11954. // Greylist some idioms by putting them into a warning subcategory.
  11955. if (ObjCMessageExpr *ME
  11956. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  11957. Selector Sel = ME->getSelector();
  11958. // self = [<foo> init...]
  11959. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  11960. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  11961. // <foo> = [<bar> nextObject]
  11962. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  11963. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  11964. }
  11965. Loc = Op->getOperatorLoc();
  11966. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  11967. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  11968. return;
  11969. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  11970. Loc = Op->getOperatorLoc();
  11971. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  11972. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  11973. else {
  11974. // Not an assignment.
  11975. return;
  11976. }
  11977. Diag(Loc, diagnostic) << E->getSourceRange();
  11978. SourceLocation Open = E->getLocStart();
  11979. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  11980. Diag(Loc, diag::note_condition_assign_silence)
  11981. << FixItHint::CreateInsertion(Open, "(")
  11982. << FixItHint::CreateInsertion(Close, ")");
  11983. if (IsOrAssign)
  11984. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  11985. << FixItHint::CreateReplacement(Loc, "!=");
  11986. else
  11987. Diag(Loc, diag::note_condition_assign_to_comparison)
  11988. << FixItHint::CreateReplacement(Loc, "==");
  11989. }
  11990. /// \brief Redundant parentheses over an equality comparison can indicate
  11991. /// that the user intended an assignment used as condition.
  11992. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  11993. // Don't warn if the parens came from a macro.
  11994. SourceLocation parenLoc = ParenE->getLocStart();
  11995. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  11996. return;
  11997. // Don't warn for dependent expressions.
  11998. if (ParenE->isTypeDependent())
  11999. return;
  12000. Expr *E = ParenE->IgnoreParens();
  12001. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  12002. if (opE->getOpcode() == BO_EQ &&
  12003. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  12004. == Expr::MLV_Valid) {
  12005. SourceLocation Loc = opE->getOperatorLoc();
  12006. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  12007. SourceRange ParenERange = ParenE->getSourceRange();
  12008. Diag(Loc, diag::note_equality_comparison_silence)
  12009. << FixItHint::CreateRemoval(ParenERange.getBegin())
  12010. << FixItHint::CreateRemoval(ParenERange.getEnd());
  12011. Diag(Loc, diag::note_equality_comparison_to_assign)
  12012. << FixItHint::CreateReplacement(Loc, "=");
  12013. }
  12014. }
  12015. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  12016. DiagnoseAssignmentAsCondition(E);
  12017. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  12018. DiagnoseEqualityWithExtraParens(parenE);
  12019. ExprResult result = CheckPlaceholderExpr(E);
  12020. if (result.isInvalid()) return ExprError();
  12021. E = result.get();
  12022. if (!E->isTypeDependent()) {
  12023. if (getLangOpts().CPlusPlus)
  12024. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  12025. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  12026. if (ERes.isInvalid())
  12027. return ExprError();
  12028. E = ERes.get();
  12029. QualType T = E->getType();
  12030. if (!T->isScalarType()) { // C99 6.8.4.1p1
  12031. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  12032. << T << E->getSourceRange();
  12033. return ExprError();
  12034. }
  12035. CheckBoolLikeConversion(E, Loc);
  12036. }
  12037. return E;
  12038. }
  12039. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  12040. Expr *SubExpr) {
  12041. if (!SubExpr)
  12042. return ExprError();
  12043. return CheckBooleanCondition(SubExpr, Loc);
  12044. }
  12045. namespace {
  12046. /// A visitor for rebuilding a call to an __unknown_any expression
  12047. /// to have an appropriate type.
  12048. struct RebuildUnknownAnyFunction
  12049. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  12050. Sema &S;
  12051. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  12052. ExprResult VisitStmt(Stmt *S) {
  12053. llvm_unreachable("unexpected statement!");
  12054. }
  12055. ExprResult VisitExpr(Expr *E) {
  12056. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  12057. << E->getSourceRange();
  12058. return ExprError();
  12059. }
  12060. /// Rebuild an expression which simply semantically wraps another
  12061. /// expression which it shares the type and value kind of.
  12062. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12063. ExprResult SubResult = Visit(E->getSubExpr());
  12064. if (SubResult.isInvalid()) return ExprError();
  12065. Expr *SubExpr = SubResult.get();
  12066. E->setSubExpr(SubExpr);
  12067. E->setType(SubExpr->getType());
  12068. E->setValueKind(SubExpr->getValueKind());
  12069. assert(E->getObjectKind() == OK_Ordinary);
  12070. return E;
  12071. }
  12072. ExprResult VisitParenExpr(ParenExpr *E) {
  12073. return rebuildSugarExpr(E);
  12074. }
  12075. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12076. return rebuildSugarExpr(E);
  12077. }
  12078. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12079. ExprResult SubResult = Visit(E->getSubExpr());
  12080. if (SubResult.isInvalid()) return ExprError();
  12081. Expr *SubExpr = SubResult.get();
  12082. E->setSubExpr(SubExpr);
  12083. E->setType(S.Context.getPointerType(SubExpr->getType()));
  12084. assert(E->getValueKind() == VK_RValue);
  12085. assert(E->getObjectKind() == OK_Ordinary);
  12086. return E;
  12087. }
  12088. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  12089. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  12090. E->setType(VD->getType());
  12091. assert(E->getValueKind() == VK_RValue);
  12092. if (S.getLangOpts().CPlusPlus &&
  12093. !(isa<CXXMethodDecl>(VD) &&
  12094. cast<CXXMethodDecl>(VD)->isInstance()))
  12095. E->setValueKind(VK_LValue);
  12096. return E;
  12097. }
  12098. ExprResult VisitMemberExpr(MemberExpr *E) {
  12099. return resolveDecl(E, E->getMemberDecl());
  12100. }
  12101. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12102. return resolveDecl(E, E->getDecl());
  12103. }
  12104. };
  12105. }
  12106. /// Given a function expression of unknown-any type, try to rebuild it
  12107. /// to have a function type.
  12108. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  12109. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  12110. if (Result.isInvalid()) return ExprError();
  12111. return S.DefaultFunctionArrayConversion(Result.get());
  12112. }
  12113. namespace {
  12114. /// A visitor for rebuilding an expression of type __unknown_anytype
  12115. /// into one which resolves the type directly on the referring
  12116. /// expression. Strict preservation of the original source
  12117. /// structure is not a goal.
  12118. struct RebuildUnknownAnyExpr
  12119. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  12120. Sema &S;
  12121. /// The current destination type.
  12122. QualType DestType;
  12123. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  12124. : S(S), DestType(CastType) {}
  12125. ExprResult VisitStmt(Stmt *S) {
  12126. llvm_unreachable("unexpected statement!");
  12127. }
  12128. ExprResult VisitExpr(Expr *E) {
  12129. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12130. << E->getSourceRange();
  12131. return ExprError();
  12132. }
  12133. ExprResult VisitCallExpr(CallExpr *E);
  12134. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  12135. /// Rebuild an expression which simply semantically wraps another
  12136. /// expression which it shares the type and value kind of.
  12137. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12138. ExprResult SubResult = Visit(E->getSubExpr());
  12139. if (SubResult.isInvalid()) return ExprError();
  12140. Expr *SubExpr = SubResult.get();
  12141. E->setSubExpr(SubExpr);
  12142. E->setType(SubExpr->getType());
  12143. E->setValueKind(SubExpr->getValueKind());
  12144. assert(E->getObjectKind() == OK_Ordinary);
  12145. return E;
  12146. }
  12147. ExprResult VisitParenExpr(ParenExpr *E) {
  12148. return rebuildSugarExpr(E);
  12149. }
  12150. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12151. return rebuildSugarExpr(E);
  12152. }
  12153. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12154. const PointerType *Ptr = DestType->getAs<PointerType>();
  12155. if (!Ptr) {
  12156. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  12157. << E->getSourceRange();
  12158. return ExprError();
  12159. }
  12160. assert(E->getValueKind() == VK_RValue);
  12161. assert(E->getObjectKind() == OK_Ordinary);
  12162. E->setType(DestType);
  12163. // Build the sub-expression as if it were an object of the pointee type.
  12164. DestType = Ptr->getPointeeType();
  12165. ExprResult SubResult = Visit(E->getSubExpr());
  12166. if (SubResult.isInvalid()) return ExprError();
  12167. E->setSubExpr(SubResult.get());
  12168. return E;
  12169. }
  12170. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  12171. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  12172. ExprResult VisitMemberExpr(MemberExpr *E) {
  12173. return resolveDecl(E, E->getMemberDecl());
  12174. }
  12175. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12176. return resolveDecl(E, E->getDecl());
  12177. }
  12178. };
  12179. }
  12180. /// Rebuilds a call expression which yielded __unknown_anytype.
  12181. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  12182. Expr *CalleeExpr = E->getCallee();
  12183. enum FnKind {
  12184. FK_MemberFunction,
  12185. FK_FunctionPointer,
  12186. FK_BlockPointer
  12187. };
  12188. FnKind Kind;
  12189. QualType CalleeType = CalleeExpr->getType();
  12190. if (CalleeType == S.Context.BoundMemberTy) {
  12191. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  12192. Kind = FK_MemberFunction;
  12193. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  12194. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  12195. CalleeType = Ptr->getPointeeType();
  12196. Kind = FK_FunctionPointer;
  12197. } else {
  12198. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  12199. Kind = FK_BlockPointer;
  12200. }
  12201. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  12202. // Verify that this is a legal result type of a function.
  12203. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12204. unsigned diagID = diag::err_func_returning_array_function;
  12205. if (Kind == FK_BlockPointer)
  12206. diagID = diag::err_block_returning_array_function;
  12207. S.Diag(E->getExprLoc(), diagID)
  12208. << DestType->isFunctionType() << DestType;
  12209. return ExprError();
  12210. }
  12211. // Otherwise, go ahead and set DestType as the call's result.
  12212. E->setType(DestType.getNonLValueExprType(S.Context));
  12213. E->setValueKind(Expr::getValueKindForType(DestType));
  12214. assert(E->getObjectKind() == OK_Ordinary);
  12215. // Rebuild the function type, replacing the result type with DestType.
  12216. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  12217. if (Proto) {
  12218. // __unknown_anytype(...) is a special case used by the debugger when
  12219. // it has no idea what a function's signature is.
  12220. //
  12221. // We want to build this call essentially under the K&R
  12222. // unprototyped rules, but making a FunctionNoProtoType in C++
  12223. // would foul up all sorts of assumptions. However, we cannot
  12224. // simply pass all arguments as variadic arguments, nor can we
  12225. // portably just call the function under a non-variadic type; see
  12226. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  12227. // However, it turns out that in practice it is generally safe to
  12228. // call a function declared as "A foo(B,C,D);" under the prototype
  12229. // "A foo(B,C,D,...);". The only known exception is with the
  12230. // Windows ABI, where any variadic function is implicitly cdecl
  12231. // regardless of its normal CC. Therefore we change the parameter
  12232. // types to match the types of the arguments.
  12233. //
  12234. // This is a hack, but it is far superior to moving the
  12235. // corresponding target-specific code from IR-gen to Sema/AST.
  12236. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  12237. SmallVector<QualType, 8> ArgTypes;
  12238. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  12239. ArgTypes.reserve(E->getNumArgs());
  12240. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  12241. Expr *Arg = E->getArg(i);
  12242. QualType ArgType = Arg->getType();
  12243. if (E->isLValue()) {
  12244. ArgType = S.Context.getLValueReferenceType(ArgType);
  12245. } else if (E->isXValue()) {
  12246. ArgType = S.Context.getRValueReferenceType(ArgType);
  12247. }
  12248. ArgTypes.push_back(ArgType);
  12249. }
  12250. ParamTypes = ArgTypes;
  12251. }
  12252. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  12253. Proto->getExtProtoInfo());
  12254. } else {
  12255. DestType = S.Context.getFunctionNoProtoType(DestType,
  12256. FnType->getExtInfo());
  12257. }
  12258. // Rebuild the appropriate pointer-to-function type.
  12259. switch (Kind) {
  12260. case FK_MemberFunction:
  12261. // Nothing to do.
  12262. break;
  12263. case FK_FunctionPointer:
  12264. DestType = S.Context.getPointerType(DestType);
  12265. break;
  12266. case FK_BlockPointer:
  12267. DestType = S.Context.getBlockPointerType(DestType);
  12268. break;
  12269. }
  12270. // Finally, we can recurse.
  12271. ExprResult CalleeResult = Visit(CalleeExpr);
  12272. if (!CalleeResult.isUsable()) return ExprError();
  12273. E->setCallee(CalleeResult.get());
  12274. // Bind a temporary if necessary.
  12275. return S.MaybeBindToTemporary(E);
  12276. }
  12277. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12278. // Verify that this is a legal result type of a call.
  12279. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12280. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12281. << DestType->isFunctionType() << DestType;
  12282. return ExprError();
  12283. }
  12284. // Rewrite the method result type if available.
  12285. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12286. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12287. Method->setReturnType(DestType);
  12288. }
  12289. // Change the type of the message.
  12290. E->setType(DestType.getNonReferenceType());
  12291. E->setValueKind(Expr::getValueKindForType(DestType));
  12292. return S.MaybeBindToTemporary(E);
  12293. }
  12294. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12295. // The only case we should ever see here is a function-to-pointer decay.
  12296. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12297. assert(E->getValueKind() == VK_RValue);
  12298. assert(E->getObjectKind() == OK_Ordinary);
  12299. E->setType(DestType);
  12300. // Rebuild the sub-expression as the pointee (function) type.
  12301. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12302. ExprResult Result = Visit(E->getSubExpr());
  12303. if (!Result.isUsable()) return ExprError();
  12304. E->setSubExpr(Result.get());
  12305. return E;
  12306. } else if (E->getCastKind() == CK_LValueToRValue) {
  12307. assert(E->getValueKind() == VK_RValue);
  12308. assert(E->getObjectKind() == OK_Ordinary);
  12309. assert(isa<BlockPointerType>(E->getType()));
  12310. E->setType(DestType);
  12311. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12312. DestType = S.Context.getLValueReferenceType(DestType);
  12313. ExprResult Result = Visit(E->getSubExpr());
  12314. if (!Result.isUsable()) return ExprError();
  12315. E->setSubExpr(Result.get());
  12316. return E;
  12317. } else {
  12318. llvm_unreachable("Unhandled cast type!");
  12319. }
  12320. }
  12321. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12322. ExprValueKind ValueKind = VK_LValue;
  12323. QualType Type = DestType;
  12324. // We know how to make this work for certain kinds of decls:
  12325. // - functions
  12326. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12327. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12328. DestType = Ptr->getPointeeType();
  12329. ExprResult Result = resolveDecl(E, VD);
  12330. if (Result.isInvalid()) return ExprError();
  12331. return S.ImpCastExprToType(Result.get(), Type,
  12332. CK_FunctionToPointerDecay, VK_RValue);
  12333. }
  12334. if (!Type->isFunctionType()) {
  12335. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12336. << VD << E->getSourceRange();
  12337. return ExprError();
  12338. }
  12339. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12340. // We must match the FunctionDecl's type to the hack introduced in
  12341. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12342. // type. See the lengthy commentary in that routine.
  12343. QualType FDT = FD->getType();
  12344. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12345. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12346. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12347. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12348. SourceLocation Loc = FD->getLocation();
  12349. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12350. FD->getDeclContext(),
  12351. Loc, Loc, FD->getNameInfo().getName(),
  12352. DestType, FD->getTypeSourceInfo(),
  12353. SC_None, false/*isInlineSpecified*/,
  12354. FD->hasPrototype(),
  12355. false/*isConstexprSpecified*/);
  12356. if (FD->getQualifier())
  12357. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12358. SmallVector<ParmVarDecl*, 16> Params;
  12359. for (const auto &AI : FT->param_types()) {
  12360. ParmVarDecl *Param =
  12361. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12362. Param->setScopeInfo(0, Params.size());
  12363. Params.push_back(Param);
  12364. }
  12365. NewFD->setParams(Params);
  12366. DRE->setDecl(NewFD);
  12367. VD = DRE->getDecl();
  12368. }
  12369. }
  12370. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12371. if (MD->isInstance()) {
  12372. ValueKind = VK_RValue;
  12373. Type = S.Context.BoundMemberTy;
  12374. }
  12375. // Function references aren't l-values in C.
  12376. if (!S.getLangOpts().CPlusPlus)
  12377. ValueKind = VK_RValue;
  12378. // - variables
  12379. } else if (isa<VarDecl>(VD)) {
  12380. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12381. Type = RefTy->getPointeeType();
  12382. } else if (Type->isFunctionType()) {
  12383. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12384. << VD << E->getSourceRange();
  12385. return ExprError();
  12386. }
  12387. // - nothing else
  12388. } else {
  12389. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12390. << VD << E->getSourceRange();
  12391. return ExprError();
  12392. }
  12393. // Modifying the declaration like this is friendly to IR-gen but
  12394. // also really dangerous.
  12395. VD->setType(DestType);
  12396. E->setType(Type);
  12397. E->setValueKind(ValueKind);
  12398. return E;
  12399. }
  12400. /// Check a cast of an unknown-any type. We intentionally only
  12401. /// trigger this for C-style casts.
  12402. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12403. Expr *CastExpr, CastKind &CastKind,
  12404. ExprValueKind &VK, CXXCastPath &Path) {
  12405. // Rewrite the casted expression from scratch.
  12406. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12407. if (!result.isUsable()) return ExprError();
  12408. CastExpr = result.get();
  12409. VK = CastExpr->getValueKind();
  12410. CastKind = CK_NoOp;
  12411. return CastExpr;
  12412. }
  12413. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12414. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12415. }
  12416. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12417. Expr *arg, QualType &paramType) {
  12418. // If the syntactic form of the argument is not an explicit cast of
  12419. // any sort, just do default argument promotion.
  12420. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12421. if (!castArg) {
  12422. ExprResult result = DefaultArgumentPromotion(arg);
  12423. if (result.isInvalid()) return ExprError();
  12424. paramType = result.get()->getType();
  12425. return result;
  12426. }
  12427. // Otherwise, use the type that was written in the explicit cast.
  12428. assert(!arg->hasPlaceholderType());
  12429. paramType = castArg->getTypeAsWritten();
  12430. // Copy-initialize a parameter of that type.
  12431. InitializedEntity entity =
  12432. InitializedEntity::InitializeParameter(Context, paramType,
  12433. /*consumed*/ false);
  12434. return PerformCopyInitialization(entity, callLoc, arg);
  12435. }
  12436. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12437. Expr *orig = E;
  12438. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12439. while (true) {
  12440. E = E->IgnoreParenImpCasts();
  12441. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12442. E = call->getCallee();
  12443. diagID = diag::err_uncasted_call_of_unknown_any;
  12444. } else {
  12445. break;
  12446. }
  12447. }
  12448. SourceLocation loc;
  12449. NamedDecl *d;
  12450. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12451. loc = ref->getLocation();
  12452. d = ref->getDecl();
  12453. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12454. loc = mem->getMemberLoc();
  12455. d = mem->getMemberDecl();
  12456. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12457. diagID = diag::err_uncasted_call_of_unknown_any;
  12458. loc = msg->getSelectorStartLoc();
  12459. d = msg->getMethodDecl();
  12460. if (!d) {
  12461. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12462. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12463. << orig->getSourceRange();
  12464. return ExprError();
  12465. }
  12466. } else {
  12467. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12468. << E->getSourceRange();
  12469. return ExprError();
  12470. }
  12471. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12472. // Never recoverable.
  12473. return ExprError();
  12474. }
  12475. /// Check for operands with placeholder types and complain if found.
  12476. /// Returns true if there was an error and no recovery was possible.
  12477. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12478. if (!getLangOpts().CPlusPlus) {
  12479. // C cannot handle TypoExpr nodes on either side of a binop because it
  12480. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12481. // been dealt with before checking the operands.
  12482. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12483. if (!Result.isUsable()) return ExprError();
  12484. E = Result.get();
  12485. }
  12486. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12487. if (!placeholderType) return E;
  12488. switch (placeholderType->getKind()) {
  12489. // Overloaded expressions.
  12490. case BuiltinType::Overload: {
  12491. // Try to resolve a single function template specialization.
  12492. // This is obligatory.
  12493. ExprResult result = E;
  12494. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12495. return result;
  12496. // If that failed, try to recover with a call.
  12497. } else {
  12498. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12499. /*complain*/ true);
  12500. return result;
  12501. }
  12502. }
  12503. // Bound member functions.
  12504. case BuiltinType::BoundMember: {
  12505. ExprResult result = E;
  12506. const Expr *BME = E->IgnoreParens();
  12507. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  12508. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  12509. if (isa<CXXPseudoDestructorExpr>(BME)) {
  12510. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  12511. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  12512. if (ME->getMemberNameInfo().getName().getNameKind() ==
  12513. DeclarationName::CXXDestructorName)
  12514. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  12515. }
  12516. tryToRecoverWithCall(result, PD,
  12517. /*complain*/ true);
  12518. return result;
  12519. }
  12520. // ARC unbridged casts.
  12521. case BuiltinType::ARCUnbridgedCast: {
  12522. Expr *realCast = stripARCUnbridgedCast(E);
  12523. diagnoseARCUnbridgedCast(realCast);
  12524. return realCast;
  12525. }
  12526. // Expressions of unknown type.
  12527. case BuiltinType::UnknownAny:
  12528. return diagnoseUnknownAnyExpr(*this, E);
  12529. // Pseudo-objects.
  12530. case BuiltinType::PseudoObject:
  12531. return checkPseudoObjectRValue(E);
  12532. case BuiltinType::BuiltinFn: {
  12533. // Accept __noop without parens by implicitly converting it to a call expr.
  12534. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12535. if (DRE) {
  12536. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12537. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12538. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12539. CK_BuiltinFnToFnPtr).get();
  12540. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12541. VK_RValue, SourceLocation());
  12542. }
  12543. }
  12544. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12545. return ExprError();
  12546. }
  12547. // Everything else should be impossible.
  12548. #define BUILTIN_TYPE(Id, SingletonId) \
  12549. case BuiltinType::Id:
  12550. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12551. #include "clang/AST/BuiltinTypes.def"
  12552. break;
  12553. }
  12554. llvm_unreachable("invalid placeholder type!");
  12555. }
  12556. bool Sema::CheckCaseExpression(Expr *E) {
  12557. if (E->isTypeDependent())
  12558. return true;
  12559. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12560. return E->getType()->isIntegralOrEnumerationType();
  12561. return false;
  12562. }
  12563. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12564. ExprResult
  12565. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12566. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12567. "Unknown Objective-C Boolean value!");
  12568. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12569. if (!Context.getBOOLDecl()) {
  12570. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12571. Sema::LookupOrdinaryName);
  12572. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12573. NamedDecl *ND = Result.getFoundDecl();
  12574. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12575. Context.setBOOLDecl(TD);
  12576. }
  12577. }
  12578. if (Context.getBOOLDecl())
  12579. BoolT = Context.getBOOLType();
  12580. return new (Context)
  12581. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12582. }