SemaExpr.cpp 561 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578
  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. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  46. using namespace clang;
  47. using namespace sema;
  48. /// \brief Determine whether the use of this declaration is valid, without
  49. /// emitting diagnostics.
  50. bool Sema::CanUseDecl(NamedDecl *D) {
  51. // See if this is an auto-typed variable whose initializer we are parsing.
  52. if (ParsingInitForAutoVars.count(D))
  53. return false;
  54. // See if this is a deleted function.
  55. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  56. if (FD->isDeleted())
  57. return false;
  58. // If the function has a deduced return type, and we can't deduce it,
  59. // then we can't use it either.
  60. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  61. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  62. return false;
  63. }
  64. // See if this function is unavailable.
  65. if (D->getAvailability() == AR_Unavailable &&
  66. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  67. return false;
  68. return true;
  69. }
  70. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  71. // Warn if this is used but marked unused.
  72. if (D->hasAttr<UnusedAttr>()) {
  73. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  74. if (DC && !DC->hasAttr<UnusedAttr>())
  75. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  76. }
  77. }
  78. static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
  79. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  80. if (!OMD)
  81. return false;
  82. const ObjCInterfaceDecl *OID = OMD->getClassInterface();
  83. if (!OID)
  84. return false;
  85. for (const ObjCCategoryDecl *Cat : OID->visible_categories())
  86. if (ObjCMethodDecl *CatMeth =
  87. Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
  88. if (!CatMeth->hasAttr<AvailabilityAttr>())
  89. return true;
  90. return false;
  91. }
  92. static AvailabilityResult
  93. DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
  94. const ObjCInterfaceDecl *UnknownObjCClass,
  95. bool ObjCPropertyAccess) {
  96. // See if this declaration is unavailable or deprecated.
  97. std::string Message;
  98. AvailabilityResult Result = D->getAvailability(&Message);
  99. // For typedefs, if the typedef declaration appears available look
  100. // to the underlying type to see if it is more restrictive.
  101. while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  102. if (Result == AR_Available) {
  103. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  104. D = TT->getDecl();
  105. Result = D->getAvailability(&Message);
  106. continue;
  107. }
  108. }
  109. break;
  110. }
  111. // Forward class declarations get their attributes from their definition.
  112. if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
  113. if (IDecl->getDefinition()) {
  114. D = IDecl->getDefinition();
  115. Result = D->getAvailability(&Message);
  116. }
  117. }
  118. if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
  119. if (Result == AR_Available) {
  120. const DeclContext *DC = ECD->getDeclContext();
  121. if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
  122. Result = TheEnumDecl->getAvailability(&Message);
  123. }
  124. const ObjCPropertyDecl *ObjCPDecl = nullptr;
  125. if (Result == AR_Deprecated || Result == AR_Unavailable ||
  126. AR_NotYetIntroduced) {
  127. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  128. if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
  129. AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
  130. if (PDeclResult == Result)
  131. ObjCPDecl = PD;
  132. }
  133. }
  134. }
  135. switch (Result) {
  136. case AR_Available:
  137. break;
  138. case AR_Deprecated:
  139. if (S.getCurContextAvailability() != AR_Deprecated)
  140. S.EmitAvailabilityWarning(Sema::AD_Deprecation,
  141. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  142. ObjCPropertyAccess);
  143. break;
  144. case AR_NotYetIntroduced: {
  145. // Don't do this for enums, they can't be redeclared.
  146. if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
  147. break;
  148. bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
  149. // Objective-C method declarations in categories are not modelled as
  150. // redeclarations, so manually look for a redeclaration in a category
  151. // if necessary.
  152. if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
  153. Warn = false;
  154. // In general, D will point to the most recent redeclaration. However,
  155. // for `@class A;` decls, this isn't true -- manually go through the
  156. // redecl chain in that case.
  157. if (Warn && isa<ObjCInterfaceDecl>(D))
  158. for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
  159. Redecl = Redecl->getPreviousDecl())
  160. if (!Redecl->hasAttr<AvailabilityAttr>() ||
  161. Redecl->getAttr<AvailabilityAttr>()->isInherited())
  162. Warn = false;
  163. if (Warn)
  164. S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
  165. UnknownObjCClass, ObjCPDecl,
  166. ObjCPropertyAccess);
  167. break;
  168. }
  169. case AR_Unavailable:
  170. if (S.getCurContextAvailability() != AR_Unavailable)
  171. S.EmitAvailabilityWarning(Sema::AD_Unavailable,
  172. D, Message, Loc, UnknownObjCClass, ObjCPDecl,
  173. ObjCPropertyAccess);
  174. break;
  175. }
  176. return Result;
  177. }
  178. /// \brief Emit a note explaining that this function is deleted.
  179. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  180. assert(Decl->isDeleted());
  181. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  182. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  183. // If the method was explicitly defaulted, point at that declaration.
  184. if (!Method->isImplicit())
  185. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  186. // Try to diagnose why this special member function was implicitly
  187. // deleted. This might fail, if that reason no longer applies.
  188. CXXSpecialMember CSM = getSpecialMember(Method);
  189. if (CSM != CXXInvalid)
  190. ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
  191. return;
  192. }
  193. if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
  194. if (CXXConstructorDecl *BaseCD =
  195. const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
  196. Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
  197. if (BaseCD->isDeleted()) {
  198. NoteDeletedFunction(BaseCD);
  199. } else {
  200. // FIXME: An explanation of why exactly it can't be inherited
  201. // would be nice.
  202. Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
  203. }
  204. return;
  205. }
  206. }
  207. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  208. << Decl << true;
  209. }
  210. /// \brief Determine whether a FunctionDecl was ever declared with an
  211. /// explicit storage class.
  212. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  213. for (auto I : D->redecls()) {
  214. if (I->getStorageClass() != SC_None)
  215. return true;
  216. }
  217. return false;
  218. }
  219. /// \brief Check whether we're in an extern inline function and referring to a
  220. /// variable or function with internal linkage (C11 6.7.4p3).
  221. ///
  222. /// This is only a warning because we used to silently accept this code, but
  223. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  224. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  225. /// and so while there may still be user mistakes, most of the time we can't
  226. /// prove that there are errors.
  227. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  228. const NamedDecl *D,
  229. SourceLocation Loc) {
  230. // This is disabled under C++; there are too many ways for this to fire in
  231. // contexts where the warning is a false positive, or where it is technically
  232. // correct but benign.
  233. if (S.getLangOpts().CPlusPlus)
  234. return;
  235. // Check if this is an inlined function or method.
  236. FunctionDecl *Current = S.getCurFunctionDecl();
  237. if (!Current)
  238. return;
  239. if (!Current->isInlined())
  240. return;
  241. if (!Current->isExternallyVisible())
  242. return;
  243. // Check if the decl has internal linkage.
  244. if (D->getFormalLinkage() != InternalLinkage)
  245. return;
  246. // Downgrade from ExtWarn to Extension if
  247. // (1) the supposedly external inline function is in the main file,
  248. // and probably won't be included anywhere else.
  249. // (2) the thing we're referencing is a pure function.
  250. // (3) the thing we're referencing is another inline function.
  251. // This last can give us false negatives, but it's better than warning on
  252. // wrappers for simple C library functions.
  253. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  254. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  255. if (!DowngradeWarning && UsedFn)
  256. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  257. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  258. : diag::ext_internal_in_extern_inline)
  259. << /*IsVar=*/!UsedFn << D;
  260. S.MaybeSuggestAddingStaticToDecl(Current);
  261. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  262. << D;
  263. }
  264. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  265. const FunctionDecl *First = Cur->getFirstDecl();
  266. // Suggest "static" on the function, if possible.
  267. if (!hasAnyExplicitStorageClass(First)) {
  268. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  269. Diag(DeclBegin, diag::note_convert_inline_to_static)
  270. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  271. }
  272. }
  273. /// \brief Determine whether the use of this declaration is valid, and
  274. /// emit any corresponding diagnostics.
  275. ///
  276. /// This routine diagnoses various problems with referencing
  277. /// declarations that can occur when using a declaration. For example,
  278. /// it might warn if a deprecated or unavailable declaration is being
  279. /// used, or produce an error (and return true) if a C++0x deleted
  280. /// function is being used.
  281. ///
  282. /// \returns true if there was an error (this declaration cannot be
  283. /// referenced), false otherwise.
  284. ///
  285. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  286. const ObjCInterfaceDecl *UnknownObjCClass,
  287. bool ObjCPropertyAccess) {
  288. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  289. // If there were any diagnostics suppressed by template argument deduction,
  290. // emit them now.
  291. SuppressedDiagnosticsMap::iterator
  292. Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  293. if (Pos != SuppressedDiagnostics.end()) {
  294. SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
  295. for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
  296. Diag(Suppressed[I].first, Suppressed[I].second);
  297. // Clear out the list of suppressed diagnostics, so that we don't emit
  298. // them again for this specialization. However, we don't obsolete this
  299. // entry from the table, because we want to avoid ever emitting these
  300. // diagnostics again.
  301. Suppressed.clear();
  302. }
  303. // C++ [basic.start.main]p3:
  304. // The function 'main' shall not be used within a program.
  305. if (cast<FunctionDecl>(D)->isMain())
  306. Diag(Loc, diag::ext_main_used);
  307. }
  308. // See if this is an auto-typed variable whose initializer we are parsing.
  309. if (ParsingInitForAutoVars.count(D)) {
  310. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  311. << D->getDeclName();
  312. return true;
  313. }
  314. // See if this is a deleted function.
  315. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  316. if (FD->isDeleted()) {
  317. Diag(Loc, diag::err_deleted_function_use);
  318. NoteDeletedFunction(FD);
  319. return true;
  320. }
  321. // If the function has a deduced return type, and we can't deduce it,
  322. // then we can't use it either.
  323. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  324. DeduceReturnType(FD, Loc))
  325. return true;
  326. }
  327. DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
  328. ObjCPropertyAccess);
  329. DiagnoseUnusedOfDecl(*this, D, Loc);
  330. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  331. return false;
  332. }
  333. /// \brief Retrieve the message suffix that should be added to a
  334. /// diagnostic complaining about the given function being deleted or
  335. /// unavailable.
  336. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  337. std::string Message;
  338. if (FD->getAvailability(&Message))
  339. return ": " + Message;
  340. return std::string();
  341. }
  342. /// DiagnoseSentinelCalls - This routine checks whether a call or
  343. /// message-send is to a declaration with the sentinel attribute, and
  344. /// if so, it checks that the requirements of the sentinel are
  345. /// satisfied.
  346. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  347. ArrayRef<Expr *> Args) {
  348. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  349. if (!attr)
  350. return;
  351. // The number of formal parameters of the declaration.
  352. unsigned numFormalParams;
  353. // The kind of declaration. This is also an index into a %select in
  354. // the diagnostic.
  355. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  356. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  357. numFormalParams = MD->param_size();
  358. calleeType = CT_Method;
  359. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  360. numFormalParams = FD->param_size();
  361. calleeType = CT_Function;
  362. } else if (isa<VarDecl>(D)) {
  363. QualType type = cast<ValueDecl>(D)->getType();
  364. const FunctionType *fn = nullptr;
  365. if (const PointerType *ptr = type->getAs<PointerType>()) {
  366. fn = ptr->getPointeeType()->getAs<FunctionType>();
  367. if (!fn) return;
  368. calleeType = CT_Function;
  369. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  370. fn = ptr->getPointeeType()->castAs<FunctionType>();
  371. calleeType = CT_Block;
  372. } else {
  373. return;
  374. }
  375. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  376. numFormalParams = proto->getNumParams();
  377. } else {
  378. numFormalParams = 0;
  379. }
  380. } else {
  381. return;
  382. }
  383. // "nullPos" is the number of formal parameters at the end which
  384. // effectively count as part of the variadic arguments. This is
  385. // useful if you would prefer to not have *any* formal parameters,
  386. // but the language forces you to have at least one.
  387. unsigned nullPos = attr->getNullPos();
  388. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  389. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  390. // The number of arguments which should follow the sentinel.
  391. unsigned numArgsAfterSentinel = attr->getSentinel();
  392. // If there aren't enough arguments for all the formal parameters,
  393. // the sentinel, and the args after the sentinel, complain.
  394. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  395. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  396. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  397. return;
  398. }
  399. // Otherwise, find the sentinel expression.
  400. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  401. if (!sentinelExpr) return;
  402. if (sentinelExpr->isValueDependent()) return;
  403. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  404. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  405. // or 'NULL' if those are actually defined in the context. Only use
  406. // 'nil' for ObjC methods, where it's much more likely that the
  407. // variadic arguments form a list of object pointers.
  408. SourceLocation MissingNilLoc
  409. = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
  410. std::string NullValue;
  411. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  412. NullValue = "nil";
  413. else if (getLangOpts().CPlusPlus11)
  414. NullValue = "nullptr";
  415. else if (PP.isMacroDefined("NULL"))
  416. NullValue = "NULL";
  417. else
  418. NullValue = "(void*) 0";
  419. if (MissingNilLoc.isInvalid())
  420. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  421. else
  422. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  423. << int(calleeType)
  424. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  425. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  426. }
  427. SourceRange Sema::getExprRange(Expr *E) const {
  428. return E ? E->getSourceRange() : SourceRange();
  429. }
  430. //===----------------------------------------------------------------------===//
  431. // Standard Promotions and Conversions
  432. //===----------------------------------------------------------------------===//
  433. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  434. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
  435. // Handle any placeholder expressions which made it here.
  436. if (E->getType()->isPlaceholderType()) {
  437. ExprResult result = CheckPlaceholderExpr(E);
  438. if (result.isInvalid()) return ExprError();
  439. E = result.get();
  440. }
  441. QualType Ty = E->getType();
  442. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  443. if (Ty->isFunctionType()) {
  444. // If we are here, we are not calling a function but taking
  445. // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
  446. if (getLangOpts().OpenCL) {
  447. Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
  448. return ExprError();
  449. }
  450. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  451. CK_FunctionToPointerDecay).get();
  452. } else if (Ty->isArrayType() && !getLangOpts().HLSL) { // HLSL Change - HLSL does not have pointers; do not decay arrays
  453. // In C90 mode, arrays only promote to pointers if the array expression is
  454. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  455. // type 'array of type' is converted to an expression that has type 'pointer
  456. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  457. // that has type 'array of type' ...". The relevant change is "an lvalue"
  458. // (C90) to "an expression" (C99).
  459. //
  460. // C++ 4.2p1:
  461. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  462. // T" can be converted to an rvalue of type "pointer to T".
  463. //
  464. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  465. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  466. CK_ArrayToPointerDecay).get();
  467. }
  468. return E;
  469. }
  470. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  471. // Check to see if we are dereferencing a null pointer. If so,
  472. // and if not volatile-qualified, this is undefined behavior that the
  473. // optimizer will delete, so warn about it. People sometimes try to use this
  474. // to get a deterministic trap and are surprised by clang's behavior. This
  475. // only handles the pattern "*null", which is a very syntactic check.
  476. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  477. if (UO->getOpcode() == UO_Deref &&
  478. UO->getSubExpr()->IgnoreParenCasts()->
  479. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  480. !UO->getType().isVolatileQualified()) {
  481. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  482. S.PDiag(diag::warn_indirection_through_null)
  483. << UO->getSubExpr()->getSourceRange());
  484. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  485. S.PDiag(diag::note_indirection_through_null));
  486. }
  487. }
  488. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  489. SourceLocation AssignLoc,
  490. const Expr* RHS) {
  491. const ObjCIvarDecl *IV = OIRE->getDecl();
  492. if (!IV)
  493. return;
  494. DeclarationName MemberName = IV->getDeclName();
  495. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  496. if (!Member || !Member->isStr("isa"))
  497. return;
  498. const Expr *Base = OIRE->getBase();
  499. QualType BaseType = Base->getType();
  500. if (OIRE->isArrow())
  501. BaseType = BaseType->getPointeeType();
  502. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  503. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  504. ObjCInterfaceDecl *ClassDeclared = nullptr;
  505. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  506. if (!ClassDeclared->getSuperClass()
  507. && (*ClassDeclared->ivar_begin()) == IV) {
  508. if (RHS) {
  509. NamedDecl *ObjectSetClass =
  510. S.LookupSingleName(S.TUScope,
  511. &S.Context.Idents.get("object_setClass"),
  512. SourceLocation(), S.LookupOrdinaryName);
  513. if (ObjectSetClass) {
  514. SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
  515. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  516. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  517. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  518. AssignLoc), ",") <<
  519. FixItHint::CreateInsertion(RHSLocEnd, ")");
  520. }
  521. else
  522. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  523. } else {
  524. NamedDecl *ObjectGetClass =
  525. S.LookupSingleName(S.TUScope,
  526. &S.Context.Idents.get("object_getClass"),
  527. SourceLocation(), S.LookupOrdinaryName);
  528. if (ObjectGetClass)
  529. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  530. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  531. FixItHint::CreateReplacement(
  532. SourceRange(OIRE->getOpLoc(),
  533. OIRE->getLocEnd()), ")");
  534. else
  535. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  536. }
  537. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  538. }
  539. }
  540. }
  541. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  542. // Handle any placeholder expressions which made it here.
  543. if (E->getType()->isPlaceholderType()) {
  544. ExprResult result = CheckPlaceholderExpr(E);
  545. if (result.isInvalid()) return ExprError();
  546. E = result.get();
  547. }
  548. // C++ [conv.lval]p1:
  549. // A glvalue of a non-function, non-array type T can be
  550. // converted to a prvalue.
  551. if (!E->isGLValue()) return E;
  552. QualType T = E->getType();
  553. assert(!T.isNull() && "r-value conversion on typeless expression?");
  554. // We don't want to throw lvalue-to-rvalue casts on top of
  555. // expressions of certain types in C++.
  556. if (getLangOpts().CPlusPlus &&
  557. !getLangOpts().HLSL && // HLSL Change - matrices and object types should turn into lvalues
  558. (E->getType() == Context.OverloadTy ||
  559. T->isDependentType() ||
  560. T->isRecordType()))
  561. return E;
  562. // The C standard is actually really unclear on this point, and
  563. // DR106 tells us what the result should be but not why. It's
  564. // generally best to say that void types just doesn't undergo
  565. // lvalue-to-rvalue at all. Note that expressions of unqualified
  566. // 'void' type are never l-values, but qualified void can be.
  567. if (T->isVoidType())
  568. return E;
  569. // OpenCL usually rejects direct accesses to values of 'half' type.
  570. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
  571. T->isHalfType()) {
  572. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  573. << 0 << T;
  574. return ExprError();
  575. }
  576. CheckForNullPointerDereference(*this, E);
  577. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  578. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  579. &Context.Idents.get("object_getClass"),
  580. SourceLocation(), LookupOrdinaryName);
  581. if (ObjectGetClass)
  582. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  583. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  584. FixItHint::CreateReplacement(
  585. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  586. else
  587. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  588. }
  589. else if (const ObjCIvarRefExpr *OIRE =
  590. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  591. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  592. // C++ [conv.lval]p1:
  593. // [...] If T is a non-class type, the type of the prvalue is the
  594. // cv-unqualified version of T. Otherwise, the type of the
  595. // rvalue is T.
  596. //
  597. // C99 6.3.2.1p2:
  598. // If the lvalue has qualified type, the value has the unqualified
  599. // version of the type of the lvalue; otherwise, the value has the
  600. // type of the lvalue.
  601. if (T.hasQualifiers())
  602. T = T.getUnqualifiedType();
  603. UpdateMarkingForLValueToRValue(E);
  604. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  605. // balance that.
  606. if (getLangOpts().ObjCAutoRefCount &&
  607. E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  608. ExprNeedsCleanups = true;
  609. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  610. nullptr, VK_RValue);
  611. // C11 6.3.2.1p2:
  612. // ... if the lvalue has atomic type, the value has the non-atomic version
  613. // of the type of the lvalue ...
  614. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  615. T = Atomic->getValueType().getUnqualifiedType();
  616. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  617. nullptr, VK_RValue);
  618. }
  619. return Res;
  620. }
  621. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
  622. ExprResult Res = DefaultFunctionArrayConversion(E);
  623. if (Res.isInvalid())
  624. return ExprError();
  625. Res = DefaultLvalueConversion(Res.get());
  626. if (Res.isInvalid())
  627. return ExprError();
  628. return Res;
  629. }
  630. /// CallExprUnaryConversions - a special case of an unary conversion
  631. /// performed on a function designator of a call expression.
  632. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  633. QualType Ty = E->getType();
  634. ExprResult Res = E;
  635. // Only do implicit cast for a function type, but not for a pointer
  636. // to function type.
  637. if (Ty->isFunctionType()) {
  638. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  639. CK_FunctionToPointerDecay).get();
  640. if (Res.isInvalid())
  641. return ExprError();
  642. }
  643. Res = DefaultLvalueConversion(Res.get());
  644. if (Res.isInvalid())
  645. return ExprError();
  646. return Res.get();
  647. }
  648. /// UsualUnaryConversions - Performs various conversions that are common to most
  649. /// operators (C99 6.3). The conversions of array and function types are
  650. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  651. /// apply if the array is an argument to the sizeof or address (&) operators.
  652. /// In these instances, this routine should *not* be called.
  653. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  654. // First, convert to an r-value.
  655. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  656. if (Res.isInvalid())
  657. return ExprError();
  658. E = Res.get();
  659. QualType Ty = E->getType();
  660. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  661. // Half FP have to be promoted to float unless it is natively supported
  662. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  663. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  664. // Try to perform integral promotions if the object has a theoretically
  665. // promotable type.
  666. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  667. // C99 6.3.1.1p2:
  668. //
  669. // The following may be used in an expression wherever an int or
  670. // unsigned int may be used:
  671. // - an object or expression with an integer type whose integer
  672. // conversion rank is less than or equal to the rank of int
  673. // and unsigned int.
  674. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  675. //
  676. // If an int can represent all values of the original type, the
  677. // value is converted to an int; otherwise, it is converted to an
  678. // unsigned int. These are called the integer promotions. All
  679. // other types are unchanged by the integer promotions.
  680. QualType PTy = Context.isPromotableBitField(E);
  681. if (!PTy.isNull()) {
  682. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  683. return E;
  684. }
  685. if (Ty->isPromotableIntegerType() && !getLangOpts().HLSL) { // HLSL Change: leave low-precision integrals as such for intermediate operations
  686. QualType PT = Context.getPromotedIntegerType(Ty);
  687. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  688. return E;
  689. }
  690. }
  691. return E;
  692. }
  693. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  694. /// do not have a prototype. Arguments that have type float or __fp16
  695. /// are promoted to double. All other argument types are converted by
  696. /// UsualUnaryConversions().
  697. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  698. QualType Ty = E->getType();
  699. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  700. ExprResult Res = UsualUnaryConversions(E);
  701. if (Res.isInvalid())
  702. return ExprError();
  703. E = Res.get();
  704. // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
  705. // double.
  706. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  707. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  708. BTy->getKind() == BuiltinType::Float))
  709. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  710. // C++ performs lvalue-to-rvalue conversion as a default argument
  711. // promotion, even on class types, but note:
  712. // C++11 [conv.lval]p2:
  713. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  714. // operand or a subexpression thereof the value contained in the
  715. // referenced object is not accessed. Otherwise, if the glvalue
  716. // has a class type, the conversion copy-initializes a temporary
  717. // of type T from the glvalue and the result of the conversion
  718. // is a prvalue for the temporary.
  719. // FIXME: add some way to gate this entire thing for correctness in
  720. // potentially potentially evaluated contexts.
  721. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  722. ExprResult Temp = PerformCopyInitialization(
  723. InitializedEntity::InitializeTemporary(E->getType()),
  724. E->getExprLoc(), E);
  725. if (Temp.isInvalid())
  726. return ExprError();
  727. E = Temp.get();
  728. }
  729. return E;
  730. }
  731. /// Determine the degree of POD-ness for an expression.
  732. /// Incomplete types are considered POD, since this check can be performed
  733. /// when we're in an unevaluated context.
  734. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  735. if (Ty->isIncompleteType()) {
  736. // C++11 [expr.call]p7:
  737. // After these conversions, if the argument does not have arithmetic,
  738. // enumeration, pointer, pointer to member, or class type, the program
  739. // is ill-formed.
  740. //
  741. // Since we've already performed array-to-pointer and function-to-pointer
  742. // decay, the only such type in C++ is cv void. This also handles
  743. // initializer lists as variadic arguments.
  744. if (Ty->isVoidType())
  745. return VAK_Invalid;
  746. if (Ty->isObjCObjectType())
  747. return VAK_Invalid;
  748. return VAK_Valid;
  749. }
  750. if (Ty.isCXX98PODType(Context))
  751. return VAK_Valid;
  752. // C++11 [expr.call]p7:
  753. // Passing a potentially-evaluated argument of class type (Clause 9)
  754. // having a non-trivial copy constructor, a non-trivial move constructor,
  755. // or a non-trivial destructor, with no corresponding parameter,
  756. // is conditionally-supported with implementation-defined semantics.
  757. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  758. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  759. if (!Record->hasNonTrivialCopyConstructor() &&
  760. !Record->hasNonTrivialMoveConstructor() &&
  761. !Record->hasNonTrivialDestructor())
  762. return VAK_ValidInCXX11;
  763. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  764. return VAK_Valid;
  765. if (Ty->isObjCObjectType())
  766. return VAK_Invalid;
  767. if (getLangOpts().MSVCCompat)
  768. return VAK_MSVCUndefined;
  769. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  770. // permitted to reject them. We should consider doing so.
  771. return VAK_Undefined;
  772. }
  773. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  774. // Don't allow one to pass an Objective-C interface to a vararg.
  775. const QualType &Ty = E->getType();
  776. VarArgKind VAK = isValidVarArgType(Ty);
  777. // Complain about passing non-POD types through varargs.
  778. switch (VAK) {
  779. case VAK_ValidInCXX11:
  780. DiagRuntimeBehavior(
  781. E->getLocStart(), nullptr,
  782. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  783. << Ty << CT);
  784. // Fall through.
  785. case VAK_Valid:
  786. if (Ty->isRecordType()) {
  787. // This is unlikely to be what the user intended. If the class has a
  788. // 'c_str' member function, the user probably meant to call that.
  789. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  790. PDiag(diag::warn_pass_class_arg_to_vararg)
  791. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  792. }
  793. break;
  794. case VAK_Undefined:
  795. case VAK_MSVCUndefined:
  796. DiagRuntimeBehavior(
  797. E->getLocStart(), nullptr,
  798. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  799. << getLangOpts().CPlusPlus11 << Ty << CT);
  800. break;
  801. case VAK_Invalid:
  802. if (Ty->isObjCObjectType())
  803. DiagRuntimeBehavior(
  804. E->getLocStart(), nullptr,
  805. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  806. << Ty << CT);
  807. else
  808. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  809. << isa<InitListExpr>(E) << Ty << CT;
  810. break;
  811. }
  812. }
  813. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  814. /// will create a trap if the resulting type is not a POD type.
  815. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  816. FunctionDecl *FDecl) {
  817. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  818. // Strip the unbridged-cast placeholder expression off, if applicable.
  819. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  820. (CT == VariadicMethod ||
  821. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  822. E = stripARCUnbridgedCast(E);
  823. // Otherwise, do normal placeholder checking.
  824. } else {
  825. ExprResult ExprRes = CheckPlaceholderExpr(E);
  826. if (ExprRes.isInvalid())
  827. return ExprError();
  828. E = ExprRes.get();
  829. }
  830. }
  831. ExprResult ExprRes = DefaultArgumentPromotion(E);
  832. if (ExprRes.isInvalid())
  833. return ExprError();
  834. E = ExprRes.get();
  835. // Diagnostics regarding non-POD argument types are
  836. // emitted along with format string checking in Sema::CheckFunctionCall().
  837. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  838. // Turn this into a trap.
  839. CXXScopeSpec SS;
  840. SourceLocation TemplateKWLoc;
  841. UnqualifiedId Name;
  842. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  843. E->getLocStart());
  844. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  845. Name, true, false);
  846. if (TrapFn.isInvalid())
  847. return ExprError();
  848. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  849. E->getLocStart(), None,
  850. E->getLocEnd());
  851. if (Call.isInvalid())
  852. return ExprError();
  853. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  854. Call.get(), E);
  855. if (Comma.isInvalid())
  856. return ExprError();
  857. return Comma.get();
  858. }
  859. if (!getLangOpts().CPlusPlus &&
  860. RequireCompleteType(E->getExprLoc(), E->getType(),
  861. diag::err_call_incomplete_argument))
  862. return ExprError();
  863. return E;
  864. }
  865. /// \brief Converts an integer to complex float type. Helper function of
  866. /// UsualArithmeticConversions()
  867. ///
  868. /// \return false if the integer expression is an integer type and is
  869. /// successfully converted to the complex type.
  870. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  871. ExprResult &ComplexExpr,
  872. QualType IntTy,
  873. QualType ComplexTy,
  874. bool SkipCast) {
  875. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  876. if (SkipCast) return false;
  877. if (IntTy->isIntegerType()) {
  878. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  879. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  880. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  881. CK_FloatingRealToComplex);
  882. } else {
  883. assert(IntTy->isComplexIntegerType());
  884. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  885. CK_IntegralComplexToFloatingComplex);
  886. }
  887. return false;
  888. }
  889. /// \brief Handle arithmetic conversion with complex types. Helper function of
  890. /// UsualArithmeticConversions()
  891. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  892. ExprResult &RHS, QualType LHSType,
  893. QualType RHSType,
  894. bool IsCompAssign) {
  895. // if we have an integer operand, the result is the complex type.
  896. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  897. /*skipCast*/false))
  898. return LHSType;
  899. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  900. /*skipCast*/IsCompAssign))
  901. return RHSType;
  902. // This handles complex/complex, complex/float, or float/complex.
  903. // When both operands are complex, the shorter operand is converted to the
  904. // type of the longer, and that is the type of the result. This corresponds
  905. // to what is done when combining two real floating-point operands.
  906. // The fun begins when size promotion occur across type domains.
  907. // From H&S 6.3.4: When one operand is complex and the other is a real
  908. // floating-point type, the less precise type is converted, within it's
  909. // real or complex domain, to the precision of the other type. For example,
  910. // when combining a "long double" with a "double _Complex", the
  911. // "double _Complex" is promoted to "long double _Complex".
  912. // Compute the rank of the two types, regardless of whether they are complex.
  913. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  914. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  915. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  916. QualType LHSElementType =
  917. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  918. QualType RHSElementType =
  919. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  920. QualType ResultType = S.Context.getComplexType(LHSElementType);
  921. if (Order < 0) {
  922. // Promote the precision of the LHS if not an assignment.
  923. ResultType = S.Context.getComplexType(RHSElementType);
  924. if (!IsCompAssign) {
  925. if (LHSComplexType)
  926. LHS =
  927. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  928. else
  929. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  930. }
  931. } else if (Order > 0) {
  932. // Promote the precision of the RHS.
  933. if (RHSComplexType)
  934. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  935. else
  936. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  937. }
  938. return ResultType;
  939. }
  940. /// \brief Hande arithmetic conversion from integer to float. Helper function
  941. /// of UsualArithmeticConversions()
  942. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  943. ExprResult &IntExpr,
  944. QualType FloatTy, QualType IntTy,
  945. bool ConvertFloat, bool ConvertInt) {
  946. if (IntTy->isIntegerType()) {
  947. if (ConvertInt)
  948. // Convert intExpr to the lhs floating point type.
  949. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  950. CK_IntegralToFloating);
  951. return FloatTy;
  952. }
  953. // Convert both sides to the appropriate complex float.
  954. assert(IntTy->isComplexIntegerType());
  955. QualType result = S.Context.getComplexType(FloatTy);
  956. // _Complex int -> _Complex float
  957. if (ConvertInt)
  958. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  959. CK_IntegralComplexToFloatingComplex);
  960. // float -> _Complex float
  961. if (ConvertFloat)
  962. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  963. CK_FloatingRealToComplex);
  964. return result;
  965. }
  966. /// \brief Handle arithmethic conversion with floating point types. Helper
  967. /// function of UsualArithmeticConversions()
  968. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  969. ExprResult &RHS, QualType LHSType,
  970. QualType RHSType, bool IsCompAssign) {
  971. bool LHSFloat = LHSType->isRealFloatingType();
  972. bool RHSFloat = RHSType->isRealFloatingType();
  973. // If we have two real floating types, convert the smaller operand
  974. // to the bigger result.
  975. if (LHSFloat && RHSFloat) {
  976. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  977. if (order > 0) {
  978. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  979. return LHSType;
  980. }
  981. assert(order < 0 && "illegal float comparison");
  982. if (!IsCompAssign)
  983. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  984. return RHSType;
  985. }
  986. if (LHSFloat) {
  987. // Half FP has to be promoted to float unless it is natively supported
  988. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  989. LHSType = S.Context.FloatTy;
  990. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  991. /*convertFloat=*/!IsCompAssign,
  992. /*convertInt=*/ true);
  993. }
  994. assert(RHSFloat);
  995. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  996. /*convertInt=*/ true,
  997. /*convertFloat=*/!IsCompAssign);
  998. }
  999. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1000. namespace {
  1001. /// These helper callbacks are placed in an anonymous namespace to
  1002. /// permit their use as function template parameters.
  1003. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1004. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1005. }
  1006. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1007. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1008. CK_IntegralComplexCast);
  1009. }
  1010. }
  1011. /// \brief Handle integer arithmetic conversions. Helper function of
  1012. /// UsualArithmeticConversions()
  1013. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1014. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1015. ExprResult &RHS, QualType LHSType,
  1016. QualType RHSType, bool IsCompAssign) {
  1017. // The rules for this case are in C99 6.3.1.8
  1018. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1019. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1020. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1021. if (LHSSigned == RHSSigned) {
  1022. // Same signedness; use the higher-ranked type
  1023. if (order >= 0) {
  1024. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1025. return LHSType;
  1026. } else if (!IsCompAssign)
  1027. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1028. return RHSType;
  1029. } else if (order != (LHSSigned ? 1 : -1)) {
  1030. // The unsigned type has greater than or equal rank to the
  1031. // signed type, so use the unsigned type
  1032. if (RHSSigned) {
  1033. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1034. return LHSType;
  1035. } else if (!IsCompAssign)
  1036. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1037. return RHSType;
  1038. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1039. // The two types are different widths; if we are here, that
  1040. // means the signed type is larger than the unsigned type, so
  1041. // use the signed type.
  1042. if (LHSSigned) {
  1043. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1044. return LHSType;
  1045. } else if (!IsCompAssign)
  1046. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1047. return RHSType;
  1048. } else {
  1049. // The signed type is higher-ranked than the unsigned type,
  1050. // but isn't actually any bigger (like unsigned int and long
  1051. // on most 32-bit systems). Use the unsigned type corresponding
  1052. // to the signed type.
  1053. QualType result =
  1054. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1055. RHS = (*doRHSCast)(S, RHS.get(), result);
  1056. if (!IsCompAssign)
  1057. LHS = (*doLHSCast)(S, LHS.get(), result);
  1058. return result;
  1059. }
  1060. }
  1061. /// \brief Handle conversions with GCC complex int extension. Helper function
  1062. /// of UsualArithmeticConversions()
  1063. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1064. ExprResult &RHS, QualType LHSType,
  1065. QualType RHSType,
  1066. bool IsCompAssign) {
  1067. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1068. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1069. if (LHSComplexInt && RHSComplexInt) {
  1070. QualType LHSEltType = LHSComplexInt->getElementType();
  1071. QualType RHSEltType = RHSComplexInt->getElementType();
  1072. QualType ScalarType =
  1073. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1074. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1075. return S.Context.getComplexType(ScalarType);
  1076. }
  1077. if (LHSComplexInt) {
  1078. QualType LHSEltType = LHSComplexInt->getElementType();
  1079. QualType ScalarType =
  1080. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1081. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1082. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1083. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1084. CK_IntegralRealToComplex);
  1085. return ComplexType;
  1086. }
  1087. assert(RHSComplexInt);
  1088. QualType RHSEltType = RHSComplexInt->getElementType();
  1089. QualType ScalarType =
  1090. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1091. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1092. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1093. if (!IsCompAssign)
  1094. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1095. CK_IntegralRealToComplex);
  1096. return ComplexType;
  1097. }
  1098. /// UsualArithmeticConversions - Performs various conversions that are common to
  1099. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1100. /// routine returns the first non-arithmetic type found. The client is
  1101. /// responsible for emitting appropriate error diagnostics.
  1102. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1103. bool IsCompAssign) {
  1104. if (!IsCompAssign) {
  1105. LHS = UsualUnaryConversions(LHS.get());
  1106. if (LHS.isInvalid())
  1107. return QualType();
  1108. }
  1109. RHS = UsualUnaryConversions(RHS.get());
  1110. if (RHS.isInvalid())
  1111. return QualType();
  1112. // For conversion purposes, we ignore any qualifiers.
  1113. // For example, "const float" and "float" are equivalent.
  1114. QualType LHSType =
  1115. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1116. QualType RHSType =
  1117. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1118. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1119. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1120. LHSType = AtomicLHS->getValueType();
  1121. // If both types are identical, no conversion is needed.
  1122. if (LHSType == RHSType)
  1123. return LHSType;
  1124. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1125. // The caller can deal with this (e.g. pointer + int).
  1126. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1127. return QualType();
  1128. // Apply unary and bitfield promotions to the LHS's type.
  1129. QualType LHSUnpromotedType = LHSType;
  1130. if (LHSType->isPromotableIntegerType())
  1131. LHSType = Context.getPromotedIntegerType(LHSType);
  1132. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1133. if (!LHSBitfieldPromoteTy.isNull())
  1134. LHSType = LHSBitfieldPromoteTy;
  1135. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1136. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1137. // If both types are identical, no conversion is needed.
  1138. if (LHSType == RHSType)
  1139. return LHSType;
  1140. // At this point, we have two different arithmetic types.
  1141. // Handle complex types first (C99 6.3.1.8p1).
  1142. if (LHSType->isComplexType() || RHSType->isComplexType())
  1143. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1144. IsCompAssign);
  1145. // Now handle "real" floating types (i.e. float, double, long double).
  1146. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1147. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1148. IsCompAssign);
  1149. // Handle GCC complex int extension.
  1150. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1151. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1152. IsCompAssign);
  1153. // Finally, we have two differing integer types.
  1154. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1155. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1156. }
  1157. //===----------------------------------------------------------------------===//
  1158. // Semantic Analysis for various Expression Types
  1159. //===----------------------------------------------------------------------===//
  1160. ExprResult
  1161. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1162. SourceLocation DefaultLoc,
  1163. SourceLocation RParenLoc,
  1164. Expr *ControllingExpr,
  1165. ArrayRef<ParsedType> ArgTypes,
  1166. ArrayRef<Expr *> ArgExprs) {
  1167. unsigned NumAssocs = ArgTypes.size();
  1168. assert(NumAssocs == ArgExprs.size());
  1169. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1170. for (unsigned i = 0; i < NumAssocs; ++i) {
  1171. if (ArgTypes[i])
  1172. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1173. else
  1174. Types[i] = nullptr;
  1175. }
  1176. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1177. ControllingExpr,
  1178. llvm::makeArrayRef(Types, NumAssocs),
  1179. ArgExprs);
  1180. delete [] Types;
  1181. return ER;
  1182. }
  1183. ExprResult
  1184. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1185. SourceLocation DefaultLoc,
  1186. SourceLocation RParenLoc,
  1187. Expr *ControllingExpr,
  1188. ArrayRef<TypeSourceInfo *> Types,
  1189. ArrayRef<Expr *> Exprs) {
  1190. unsigned NumAssocs = Types.size();
  1191. assert(NumAssocs == Exprs.size());
  1192. if (ControllingExpr->getType()->isPlaceholderType()) {
  1193. ExprResult result = CheckPlaceholderExpr(ControllingExpr);
  1194. if (result.isInvalid()) return ExprError();
  1195. ControllingExpr = result.get();
  1196. }
  1197. // The controlling expression is an unevaluated operand, so side effects are
  1198. // likely unintended.
  1199. if (ActiveTemplateInstantiations.empty() &&
  1200. ControllingExpr->HasSideEffects(Context, false))
  1201. Diag(ControllingExpr->getExprLoc(),
  1202. diag::warn_side_effects_unevaluated_context);
  1203. bool TypeErrorFound = false,
  1204. IsResultDependent = ControllingExpr->isTypeDependent(),
  1205. ContainsUnexpandedParameterPack
  1206. = ControllingExpr->containsUnexpandedParameterPack();
  1207. for (unsigned i = 0; i < NumAssocs; ++i) {
  1208. if (Exprs[i]->containsUnexpandedParameterPack())
  1209. ContainsUnexpandedParameterPack = true;
  1210. if (Types[i]) {
  1211. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1212. ContainsUnexpandedParameterPack = true;
  1213. if (Types[i]->getType()->isDependentType()) {
  1214. IsResultDependent = true;
  1215. } else {
  1216. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1217. // complete object type other than a variably modified type."
  1218. unsigned D = 0;
  1219. if (Types[i]->getType()->isIncompleteType())
  1220. D = diag::err_assoc_type_incomplete;
  1221. else if (!Types[i]->getType()->isObjectType())
  1222. D = diag::err_assoc_type_nonobject;
  1223. else if (Types[i]->getType()->isVariablyModifiedType())
  1224. D = diag::err_assoc_type_variably_modified;
  1225. if (D != 0) {
  1226. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1227. << Types[i]->getTypeLoc().getSourceRange()
  1228. << Types[i]->getType();
  1229. TypeErrorFound = true;
  1230. }
  1231. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1232. // selection shall specify compatible types."
  1233. for (unsigned j = i+1; j < NumAssocs; ++j)
  1234. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1235. Context.typesAreCompatible(Types[i]->getType(),
  1236. Types[j]->getType())) {
  1237. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1238. diag::err_assoc_compatible_types)
  1239. << Types[j]->getTypeLoc().getSourceRange()
  1240. << Types[j]->getType()
  1241. << Types[i]->getType();
  1242. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1243. diag::note_compat_assoc)
  1244. << Types[i]->getTypeLoc().getSourceRange()
  1245. << Types[i]->getType();
  1246. TypeErrorFound = true;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. if (TypeErrorFound)
  1252. return ExprError();
  1253. // If we determined that the generic selection is result-dependent, don't
  1254. // try to compute the result expression.
  1255. if (IsResultDependent)
  1256. return new (Context) GenericSelectionExpr(
  1257. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1258. ContainsUnexpandedParameterPack);
  1259. SmallVector<unsigned, 1> CompatIndices;
  1260. unsigned DefaultIndex = -1U;
  1261. for (unsigned i = 0; i < NumAssocs; ++i) {
  1262. if (!Types[i])
  1263. DefaultIndex = i;
  1264. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1265. Types[i]->getType()))
  1266. CompatIndices.push_back(i);
  1267. }
  1268. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1269. // type compatible with at most one of the types named in its generic
  1270. // association list."
  1271. if (CompatIndices.size() > 1) {
  1272. // We strip parens here because the controlling expression is typically
  1273. // parenthesized in macro definitions.
  1274. ControllingExpr = ControllingExpr->IgnoreParens();
  1275. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1276. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1277. << (unsigned) CompatIndices.size();
  1278. for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
  1279. E = CompatIndices.end(); I != E; ++I) {
  1280. Diag(Types[*I]->getTypeLoc().getBeginLoc(),
  1281. diag::note_compat_assoc)
  1282. << Types[*I]->getTypeLoc().getSourceRange()
  1283. << Types[*I]->getType();
  1284. }
  1285. return ExprError();
  1286. }
  1287. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1288. // its controlling expression shall have type compatible with exactly one of
  1289. // the types named in its generic association list."
  1290. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1291. // We strip parens here because the controlling expression is typically
  1292. // parenthesized in macro definitions.
  1293. ControllingExpr = ControllingExpr->IgnoreParens();
  1294. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1295. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1296. return ExprError();
  1297. }
  1298. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1299. // type name that is compatible with the type of the controlling expression,
  1300. // then the result expression of the generic selection is the expression
  1301. // in that generic association. Otherwise, the result expression of the
  1302. // generic selection is the expression in the default generic association."
  1303. unsigned ResultIndex =
  1304. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1305. return new (Context) GenericSelectionExpr(
  1306. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1307. ContainsUnexpandedParameterPack, ResultIndex);
  1308. }
  1309. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1310. /// location of the token and the offset of the ud-suffix within it.
  1311. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1312. unsigned Offset) {
  1313. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1314. S.getLangOpts());
  1315. }
  1316. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1317. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1318. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1319. IdentifierInfo *UDSuffix,
  1320. SourceLocation UDSuffixLoc,
  1321. ArrayRef<Expr*> Args,
  1322. SourceLocation LitEndLoc) {
  1323. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1324. QualType ArgTy[2];
  1325. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1326. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1327. if (ArgTy[ArgIdx]->isArrayType())
  1328. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1329. }
  1330. DeclarationName OpName =
  1331. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1332. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1333. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1334. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1335. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1336. /*AllowRaw*/false, /*AllowTemplate*/false,
  1337. /*AllowStringTemplate*/false) == Sema::LOLR_Error)
  1338. return ExprError();
  1339. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1340. }
  1341. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1342. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1343. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1344. /// multiple tokens. However, the common case is that StringToks points to one
  1345. /// string.
  1346. ///
  1347. ExprResult
  1348. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1349. assert(!StringToks.empty() && "Must have at least one string!");
  1350. StringLiteralParser Literal(StringToks, PP);
  1351. if (Literal.hadError)
  1352. return ExprError();
  1353. SmallVector<SourceLocation, 4> StringTokLocs;
  1354. for (unsigned i = 0; i != StringToks.size(); ++i)
  1355. StringTokLocs.push_back(StringToks[i].getLocation());
  1356. // HLSL Change Starts
  1357. if (getLangOpts().HLSL) {
  1358. assert(!Literal.isWide() && !Literal.isUTF16() && !Literal.isUTF32() && !Literal.isPascal()
  1359. && "HLSL parser always produces simple string literals");
  1360. QualType CharTyConst = Context.CharTy;
  1361. CharTyConst.addConst();
  1362. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1363. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1364. ArrayType::Normal, 0);
  1365. StringLiteral *Result = StringLiteral::Create(Context, Literal.GetString(), StringLiteral::StringKind::Ascii,
  1366. false, StrTy, &StringTokLocs[0], StringTokLocs.size());
  1367. return Result;
  1368. }
  1369. // HLSL Change Ends
  1370. QualType CharTy = Context.CharTy;
  1371. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1372. if (Literal.isWide()) {
  1373. CharTy = Context.getWideCharType();
  1374. Kind = StringLiteral::Wide;
  1375. } else if (Literal.isUTF8()) {
  1376. Kind = StringLiteral::UTF8;
  1377. } else if (Literal.isUTF16()) {
  1378. CharTy = Context.Char16Ty;
  1379. Kind = StringLiteral::UTF16;
  1380. } else if (Literal.isUTF32()) {
  1381. CharTy = Context.Char32Ty;
  1382. Kind = StringLiteral::UTF32;
  1383. } else if (Literal.isPascal()) {
  1384. CharTy = Context.UnsignedCharTy;
  1385. }
  1386. QualType CharTyConst = CharTy;
  1387. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1388. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1389. CharTyConst.addConst();
  1390. // Get an array type for the string, according to C99 6.4.5. This includes
  1391. // the nul terminator character as well as the string length for pascal
  1392. // strings.
  1393. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1394. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1395. ArrayType::Normal, 0);
  1396. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1397. if (getLangOpts().OpenCL) {
  1398. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1399. }
  1400. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1401. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1402. Kind, Literal.Pascal, StrTy,
  1403. &StringTokLocs[0],
  1404. StringTokLocs.size());
  1405. if (Literal.getUDSuffix().empty())
  1406. return Lit;
  1407. // We're building a user-defined literal.
  1408. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1409. SourceLocation UDSuffixLoc =
  1410. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1411. Literal.getUDSuffixOffset());
  1412. // Make sure we're allowed user-defined literals here.
  1413. if (!UDLScope)
  1414. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1415. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1416. // operator "" X (str, len)
  1417. QualType SizeType = Context.getSizeType();
  1418. DeclarationName OpName =
  1419. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1420. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1421. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1422. QualType ArgTy[] = {
  1423. Context.getArrayDecayedType(StrTy), SizeType
  1424. };
  1425. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1426. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1427. /*AllowRaw*/false, /*AllowTemplate*/false,
  1428. /*AllowStringTemplate*/true)) {
  1429. case LOLR_Cooked: {
  1430. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1431. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1432. StringTokLocs[0]);
  1433. Expr *Args[] = { Lit, LenArg };
  1434. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1435. }
  1436. case LOLR_StringTemplate: {
  1437. TemplateArgumentListInfo ExplicitArgs;
  1438. unsigned CharBits = Context.getIntWidth(CharTy);
  1439. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1440. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1441. TemplateArgument TypeArg(CharTy);
  1442. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1443. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1444. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1445. Value = Lit->getCodeUnit(I);
  1446. TemplateArgument Arg(Context, Value, CharTy);
  1447. TemplateArgumentLocInfo ArgInfo;
  1448. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1449. }
  1450. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1451. &ExplicitArgs);
  1452. }
  1453. case LOLR_Raw:
  1454. case LOLR_Template:
  1455. llvm_unreachable("unexpected literal operator lookup result");
  1456. case LOLR_Error:
  1457. return ExprError();
  1458. }
  1459. llvm_unreachable("unexpected literal operator lookup result");
  1460. }
  1461. ExprResult
  1462. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1463. SourceLocation Loc,
  1464. const CXXScopeSpec *SS) {
  1465. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1466. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1467. }
  1468. /// BuildDeclRefExpr - Build an expression that references a
  1469. /// declaration that does not require a closure capture.
  1470. ExprResult
  1471. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1472. const DeclarationNameInfo &NameInfo,
  1473. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1474. const TemplateArgumentListInfo *TemplateArgs) {
  1475. if (getLangOpts().CUDA)
  1476. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  1477. if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
  1478. if (CheckCUDATarget(Caller, Callee)) {
  1479. Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
  1480. << IdentifyCUDATarget(Callee) << D->getIdentifier()
  1481. << IdentifyCUDATarget(Caller);
  1482. Diag(D->getLocation(), diag::note_previous_decl)
  1483. << D->getIdentifier();
  1484. return ExprError();
  1485. }
  1486. }
  1487. bool RefersToCapturedVariable =
  1488. isa<VarDecl>(D) &&
  1489. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1490. DeclRefExpr *E;
  1491. if (isa<VarTemplateSpecializationDecl>(D)) {
  1492. VarTemplateSpecializationDecl *VarSpec =
  1493. cast<VarTemplateSpecializationDecl>(D);
  1494. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1495. : NestedNameSpecifierLoc(),
  1496. VarSpec->getTemplateKeywordLoc(), D,
  1497. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1498. FoundD, TemplateArgs);
  1499. } else {
  1500. assert(!TemplateArgs && "No template arguments for non-variable"
  1501. " template specialization references");
  1502. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1503. : NestedNameSpecifierLoc(),
  1504. SourceLocation(), D, RefersToCapturedVariable,
  1505. NameInfo, Ty, VK, FoundD);
  1506. }
  1507. MarkDeclRefReferenced(E);
  1508. if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
  1509. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1510. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1511. recordUseOfEvaluatedWeak(E);
  1512. // Just in case we're building an illegal pointer-to-member.
  1513. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1514. if (FD && FD->isBitField())
  1515. E->setObjectKind(OK_BitField);
  1516. return E;
  1517. }
  1518. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1519. /// possibly a list of template arguments.
  1520. ///
  1521. /// If this produces template arguments, it is permitted to call
  1522. /// DecomposeTemplateName.
  1523. ///
  1524. /// This actually loses a lot of source location information for
  1525. /// non-standard name kinds; we should consider preserving that in
  1526. /// some way.
  1527. void
  1528. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1529. TemplateArgumentListInfo &Buffer,
  1530. DeclarationNameInfo &NameInfo,
  1531. const TemplateArgumentListInfo *&TemplateArgs) {
  1532. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1533. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1534. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1535. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1536. Id.TemplateId->NumArgs);
  1537. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1538. TemplateName TName = Id.TemplateId->Template.get();
  1539. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1540. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1541. TemplateArgs = &Buffer;
  1542. } else {
  1543. NameInfo = GetNameFromUnqualifiedId(Id);
  1544. TemplateArgs = nullptr;
  1545. }
  1546. }
  1547. static void emitEmptyLookupTypoDiagnostic(
  1548. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1549. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1550. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1551. DeclContext *Ctx =
  1552. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1553. if (!TC) {
  1554. // Emit a special diagnostic for failed member lookups.
  1555. // FIXME: computing the declaration context might fail here (?)
  1556. if (Ctx)
  1557. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1558. << SS.getRange();
  1559. else
  1560. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1561. return;
  1562. }
  1563. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1564. bool DroppedSpecifier =
  1565. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1566. unsigned NoteID =
  1567. (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
  1568. ? diag::note_implicit_param_decl
  1569. : diag::note_previous_decl;
  1570. if (!Ctx)
  1571. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1572. SemaRef.PDiag(NoteID));
  1573. else
  1574. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1575. << Typo << Ctx << DroppedSpecifier
  1576. << SS.getRange(),
  1577. SemaRef.PDiag(NoteID));
  1578. }
  1579. /// Diagnose an empty lookup.
  1580. ///
  1581. /// \return false if new lookup candidates were found
  1582. bool
  1583. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1584. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1585. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1586. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1587. DeclarationName Name = R.getLookupName();
  1588. unsigned diagnostic = diag::err_undeclared_var_use;
  1589. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1590. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1591. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1592. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1593. diagnostic = diag::err_undeclared_use;
  1594. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1595. }
  1596. // If the original lookup was an unqualified lookup, fake an
  1597. // unqualified lookup. This is useful when (for example) the
  1598. // original lookup would not have found something because it was a
  1599. // dependent name.
  1600. DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
  1601. ? CurContext : nullptr;
  1602. while (DC) {
  1603. if (isa<CXXRecordDecl>(DC)) {
  1604. LookupQualifiedName(R, DC);
  1605. if (!R.empty()) {
  1606. // Don't give errors about ambiguities in this lookup.
  1607. R.suppressDiagnostics();
  1608. // During a default argument instantiation the CurContext points
  1609. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1610. // function parameter list, hence add an explicit check.
  1611. bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
  1612. ActiveTemplateInstantiations.back().Kind ==
  1613. ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  1614. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1615. bool isInstance = CurMethod &&
  1616. CurMethod->isInstance() &&
  1617. DC == CurMethod->getParent() && !isDefaultArgument;
  1618. // Give a code modification hint to insert 'this->'.
  1619. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1620. // Actually quite difficult!
  1621. if (getLangOpts().MSVCCompat)
  1622. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1623. if (isInstance) {
  1624. Diag(R.getNameLoc(), diagnostic) << Name
  1625. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1626. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
  1627. CallsUndergoingInstantiation.back()->getCallee());
  1628. CXXMethodDecl *DepMethod;
  1629. if (CurMethod->isDependentContext())
  1630. DepMethod = CurMethod;
  1631. else if (CurMethod->getTemplatedKind() ==
  1632. FunctionDecl::TK_FunctionTemplateSpecialization)
  1633. DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
  1634. getInstantiatedFromMemberTemplate()->getTemplatedDecl());
  1635. else
  1636. DepMethod = cast<CXXMethodDecl>(
  1637. CurMethod->getInstantiatedFromMemberFunction());
  1638. assert(DepMethod && "No template pattern found");
  1639. QualType DepThisType = DepMethod->getThisType(Context);
  1640. CheckCXXThisCapture(R.getNameLoc());
  1641. CXXThisExpr *DepThis = new (Context) CXXThisExpr(
  1642. R.getNameLoc(), DepThisType, false);
  1643. TemplateArgumentListInfo TList;
  1644. if (ULE->hasExplicitTemplateArgs())
  1645. ULE->copyTemplateArgumentsInto(TList);
  1646. CXXScopeSpec SS;
  1647. SS.Adopt(ULE->getQualifierLoc());
  1648. CXXDependentScopeMemberExpr *DepExpr =
  1649. CXXDependentScopeMemberExpr::Create(
  1650. Context, DepThis, DepThisType, true, SourceLocation(),
  1651. SS.getWithLocInContext(Context),
  1652. ULE->getTemplateKeywordLoc(), nullptr,
  1653. R.getLookupNameInfo(),
  1654. ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
  1655. CallsUndergoingInstantiation.back()->setCallee(DepExpr);
  1656. } else {
  1657. Diag(R.getNameLoc(), diagnostic) << Name;
  1658. }
  1659. // Do we really want to note all of these?
  1660. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  1661. Diag((*I)->getLocation(), diag::note_dependent_var_use);
  1662. // Return true if we are inside a default argument instantiation
  1663. // and the found name refers to an instance member function, otherwise
  1664. // the function calling DiagnoseEmptyLookup will try to create an
  1665. // implicit member call and this is wrong for default argument.
  1666. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1667. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1668. return true;
  1669. }
  1670. // Tell the callee to try to recover.
  1671. return false;
  1672. }
  1673. R.clear();
  1674. }
  1675. // In Microsoft mode, if we are performing lookup from within a friend
  1676. // function definition declared at class scope then we must set
  1677. // DC to the lexical parent to be able to search into the parent
  1678. // class.
  1679. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1680. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1681. DC->getLexicalParent()->isRecord())
  1682. DC = DC->getLexicalParent();
  1683. else
  1684. DC = DC->getParent();
  1685. }
  1686. // We didn't find anything, so try to correct for a typo.
  1687. TypoCorrection Corrected;
  1688. if (S && Out) {
  1689. SourceLocation TypoLoc = R.getNameLoc();
  1690. assert(!ExplicitTemplateArgs &&
  1691. "Diagnosing an empty lookup with explicit template args!");
  1692. *Out = CorrectTypoDelayed(
  1693. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1694. [=](const TypoCorrection &TC) {
  1695. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1696. diagnostic, diagnostic_suggest);
  1697. },
  1698. nullptr, CTK_ErrorRecovery);
  1699. if (*Out)
  1700. return true;
  1701. } else if (S && (Corrected =
  1702. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1703. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1704. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1705. bool DroppedSpecifier =
  1706. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1707. R.setLookupName(Corrected.getCorrection());
  1708. bool AcceptableWithRecovery = false;
  1709. bool AcceptableWithoutRecovery = false;
  1710. NamedDecl *ND = Corrected.getCorrectionDecl();
  1711. if (ND) {
  1712. if (Corrected.isOverloaded()) {
  1713. OverloadCandidateSet OCS(R.getNameLoc(),
  1714. OverloadCandidateSet::CSK_Normal);
  1715. OverloadCandidateSet::iterator Best;
  1716. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  1717. CDEnd = Corrected.end();
  1718. CD != CDEnd; ++CD) {
  1719. if (FunctionTemplateDecl *FTD =
  1720. dyn_cast<FunctionTemplateDecl>(*CD))
  1721. AddTemplateOverloadCandidate(
  1722. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1723. Args, OCS);
  1724. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  1725. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1726. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1727. Args, OCS);
  1728. }
  1729. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1730. case OR_Success:
  1731. ND = Best->Function;
  1732. Corrected.setCorrectionDecl(ND);
  1733. break;
  1734. default:
  1735. // FIXME: Arbitrarily pick the first declaration for the note.
  1736. Corrected.setCorrectionDecl(ND);
  1737. break;
  1738. }
  1739. }
  1740. R.addDecl(ND);
  1741. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1742. CXXRecordDecl *Record = nullptr;
  1743. if (Corrected.getCorrectionSpecifier()) {
  1744. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1745. Record = Ty->getAsCXXRecordDecl();
  1746. }
  1747. if (!Record)
  1748. Record = cast<CXXRecordDecl>(
  1749. ND->getDeclContext()->getRedeclContext());
  1750. R.setNamingClass(Record);
  1751. }
  1752. AcceptableWithRecovery =
  1753. isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
  1754. // FIXME: If we ended up with a typo for a type name or
  1755. // Objective-C class name, we're in trouble because the parser
  1756. // is in the wrong place to recover. Suggest the typo
  1757. // correction, but don't make it a fix-it since we're not going
  1758. // to recover well anyway.
  1759. AcceptableWithoutRecovery =
  1760. isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1761. } else {
  1762. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1763. // because we aren't able to recover.
  1764. AcceptableWithoutRecovery = true;
  1765. }
  1766. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1767. unsigned NoteID = (Corrected.getCorrectionDecl() &&
  1768. isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
  1769. ? diag::note_implicit_param_decl
  1770. : diag::note_previous_decl;
  1771. if (SS.isEmpty())
  1772. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1773. PDiag(NoteID), AcceptableWithRecovery);
  1774. else
  1775. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1776. << Name << computeDeclContext(SS, false)
  1777. << DroppedSpecifier << SS.getRange(),
  1778. PDiag(NoteID), AcceptableWithRecovery);
  1779. // Tell the callee whether to try to recover.
  1780. return !AcceptableWithRecovery;
  1781. }
  1782. }
  1783. R.clear();
  1784. // Emit a special diagnostic for failed member lookups.
  1785. // FIXME: computing the declaration context might fail here (?)
  1786. if (!SS.isEmpty()) {
  1787. Diag(R.getNameLoc(), diag::err_no_member)
  1788. << Name << computeDeclContext(SS, false)
  1789. << SS.getRange();
  1790. return true;
  1791. }
  1792. // Give up, we can't recover.
  1793. Diag(R.getNameLoc(), diagnostic) << Name;
  1794. return true;
  1795. }
  1796. /// In Microsoft mode, if we are inside a template class whose parent class has
  1797. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1798. /// assume the identifier is a member of a dependent base class. We can only
  1799. /// recover successfully in static methods, instance methods, and other contexts
  1800. /// where 'this' is available. This doesn't precisely match MSVC's
  1801. /// instantiation model, but it's close enough.
  1802. static Expr *
  1803. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1804. DeclarationNameInfo &NameInfo,
  1805. SourceLocation TemplateKWLoc,
  1806. const TemplateArgumentListInfo *TemplateArgs) {
  1807. // Only try to recover from lookup into dependent bases in static methods or
  1808. // contexts where 'this' is available.
  1809. QualType ThisType = S.getCurrentThisType();
  1810. const CXXRecordDecl *RD = nullptr;
  1811. if (!ThisType.isNull())
  1812. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1813. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1814. RD = MD->getParent();
  1815. if (!RD || !RD->hasAnyDependentBases())
  1816. return nullptr;
  1817. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1818. // is available, suggest inserting 'this->' as a fixit.
  1819. SourceLocation Loc = NameInfo.getLoc();
  1820. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1821. DB << NameInfo.getName() << RD;
  1822. if (!ThisType.isNull()) {
  1823. DB << FixItHint::CreateInsertion(Loc, "this->");
  1824. return CXXDependentScopeMemberExpr::Create(
  1825. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1826. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1827. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1828. }
  1829. // Synthesize a fake NNS that points to the derived class. This will
  1830. // perform name lookup during template instantiation.
  1831. CXXScopeSpec SS;
  1832. auto *NNS =
  1833. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1834. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1835. return DependentScopeDeclRefExpr::Create(
  1836. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1837. TemplateArgs);
  1838. }
  1839. ExprResult
  1840. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1841. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1842. bool HasTrailingLParen, bool IsAddressOfOperand,
  1843. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1844. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1845. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1846. "cannot be direct & operand and have a trailing lparen");
  1847. if (SS.isInvalid())
  1848. return ExprError();
  1849. TemplateArgumentListInfo TemplateArgsBuffer;
  1850. // Decompose the UnqualifiedId into the following data.
  1851. DeclarationNameInfo NameInfo;
  1852. const TemplateArgumentListInfo *TemplateArgs;
  1853. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1854. DeclarationName Name = NameInfo.getName();
  1855. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1856. SourceLocation NameLoc = NameInfo.getLoc();
  1857. // C++ [temp.dep.expr]p3:
  1858. // An id-expression is type-dependent if it contains:
  1859. // -- an identifier that was declared with a dependent type,
  1860. // (note: handled after lookup)
  1861. // -- a template-id that is dependent,
  1862. // (note: handled in BuildTemplateIdExpr)
  1863. // -- a conversion-function-id that specifies a dependent type,
  1864. // -- a nested-name-specifier that contains a class-name that
  1865. // names a dependent type.
  1866. // Determine whether this is a member of an unknown specialization;
  1867. // we need to handle these differently.
  1868. bool DependentID = false;
  1869. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1870. Name.getCXXNameType()->isDependentType()) {
  1871. DependentID = true;
  1872. } else if (SS.isSet()) {
  1873. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1874. if (RequireCompleteDeclContext(SS, DC))
  1875. return ExprError();
  1876. } else {
  1877. DependentID = true;
  1878. }
  1879. }
  1880. if (DependentID)
  1881. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1882. IsAddressOfOperand, TemplateArgs);
  1883. // Perform the required lookup.
  1884. LookupResult R(*this, NameInfo,
  1885. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1886. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1887. if (TemplateArgs) {
  1888. // Lookup the template name again to correctly establish the context in
  1889. // which it was found. This is really unfortunate as we already did the
  1890. // lookup to determine that it was a template name in the first place. If
  1891. // this becomes a performance hit, we can work harder to preserve those
  1892. // results until we get here but it's likely not worth it.
  1893. bool MemberOfUnknownSpecialization;
  1894. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1895. MemberOfUnknownSpecialization);
  1896. if (MemberOfUnknownSpecialization ||
  1897. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1898. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1899. IsAddressOfOperand, TemplateArgs);
  1900. } else {
  1901. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1902. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1903. // If the result might be in a dependent base class, this is a dependent
  1904. // id-expression.
  1905. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1906. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1907. IsAddressOfOperand, TemplateArgs);
  1908. // If this reference is in an Objective-C method, then we need to do
  1909. // some special Objective-C lookup, too.
  1910. if (IvarLookupFollowUp) {
  1911. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1912. if (E.isInvalid())
  1913. return ExprError();
  1914. if (Expr *Ex = E.getAs<Expr>())
  1915. return Ex;
  1916. }
  1917. }
  1918. if (R.isAmbiguous())
  1919. return ExprError();
  1920. // This could be an implicitly declared function reference (legal in C90,
  1921. // extension in C99, forbidden in C++).
  1922. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1923. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1924. if (D) R.addDecl(D);
  1925. }
  1926. // Determine whether this name might be a candidate for
  1927. // argument-dependent lookup.
  1928. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1929. if (R.empty() && !ADL) {
  1930. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1931. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1932. TemplateKWLoc, TemplateArgs))
  1933. return E;
  1934. }
  1935. // Don't diagnose an empty lookup for inline assembly.
  1936. if (IsInlineAsmIdentifier)
  1937. return ExprError();
  1938. // If this name wasn't predeclared and if this is not a function
  1939. // call, diagnose the problem.
  1940. TypoExpr *TE = nullptr;
  1941. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1942. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1943. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1944. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1945. "Typo correction callback misconfigured");
  1946. if (CCC) {
  1947. // Make sure the callback knows what the typo being diagnosed is.
  1948. CCC->setTypoName(II);
  1949. if (SS.isValid())
  1950. CCC->setTypoNNS(SS.getScopeRep());
  1951. }
  1952. if (DiagnoseEmptyLookup(S, SS, R,
  1953. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1954. nullptr, None, &TE)) {
  1955. if (TE && KeywordReplacement) {
  1956. auto &State = getTypoExprState(TE);
  1957. auto BestTC = State.Consumer->getNextCorrection();
  1958. if (BestTC.isKeyword()) {
  1959. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1960. if (State.DiagHandler)
  1961. State.DiagHandler(BestTC);
  1962. KeywordReplacement->startToken();
  1963. KeywordReplacement->setKind(II->getTokenID());
  1964. KeywordReplacement->setIdentifierInfo(II);
  1965. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1966. // Clean up the state associated with the TypoExpr, since it has
  1967. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1968. clearDelayedTypo(TE);
  1969. // Signal that a correction to a keyword was performed by returning a
  1970. // valid-but-null ExprResult.
  1971. return (Expr*)nullptr;
  1972. }
  1973. State.Consumer->resetCorrectionStream();
  1974. }
  1975. return TE ? TE : ExprError();
  1976. }
  1977. assert(!R.empty() &&
  1978. "DiagnoseEmptyLookup returned false but added no results");
  1979. // If we found an Objective-C instance variable, let
  1980. // LookupInObjCMethod build the appropriate expression to
  1981. // reference the ivar.
  1982. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1983. R.clear();
  1984. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1985. // In a hopelessly buggy code, Objective-C instance variable
  1986. // lookup fails and no expression will be built to reference it.
  1987. if (!E.isInvalid() && !E.get())
  1988. return ExprError();
  1989. return E;
  1990. }
  1991. }
  1992. // This is guaranteed from this point on.
  1993. assert(!R.empty() || ADL);
  1994. // Check whether this might be a C++ implicit instance member access.
  1995. // C++ [class.mfct.non-static]p3:
  1996. // When an id-expression that is not part of a class member access
  1997. // syntax and not used to form a pointer to member is used in the
  1998. // body of a non-static member function of class X, if name lookup
  1999. // resolves the name in the id-expression to a non-static non-type
  2000. // member of some class C, the id-expression is transformed into a
  2001. // class member access expression using (*this) as the
  2002. // postfix-expression to the left of the . operator.
  2003. //
  2004. // But we don't actually need to do this for '&' operands if R
  2005. // resolved to a function or overloaded function set, because the
  2006. // expression is ill-formed if it actually works out to be a
  2007. // non-static member function:
  2008. //
  2009. // C++ [expr.ref]p4:
  2010. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2011. // [t]he expression can be used only as the left-hand operand of a
  2012. // member function call.
  2013. //
  2014. // There are other safeguards against such uses, but it's important
  2015. // to get this right here so that we don't end up making a
  2016. // spuriously dependent expression if we're inside a dependent
  2017. // instance method.
  2018. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2019. bool MightBeImplicitMember;
  2020. if (!IsAddressOfOperand)
  2021. MightBeImplicitMember = true;
  2022. else if (!SS.isEmpty())
  2023. MightBeImplicitMember = false;
  2024. else if (R.isOverloadedResult())
  2025. MightBeImplicitMember = false;
  2026. else if (R.isUnresolvableResult())
  2027. MightBeImplicitMember = true;
  2028. else
  2029. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2030. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2031. isa<MSPropertyDecl>(R.getFoundDecl());
  2032. if (MightBeImplicitMember)
  2033. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2034. R, TemplateArgs);
  2035. }
  2036. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2037. // In C++1y, if this is a variable template id, then check it
  2038. // in BuildTemplateIdExpr().
  2039. // The single lookup result must be a variable template declaration.
  2040. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  2041. Id.TemplateId->Kind == TNK_Var_template) {
  2042. assert(R.getAsSingle<VarTemplateDecl>() &&
  2043. "There should only be one declaration found.");
  2044. }
  2045. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2046. }
  2047. return BuildDeclarationNameExpr(SS, R, ADL);
  2048. }
  2049. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2050. /// declaration name, generally during template instantiation.
  2051. /// There's a large number of things which don't need to be done along
  2052. /// this path.
  2053. ExprResult
  2054. Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
  2055. const DeclarationNameInfo &NameInfo,
  2056. bool IsAddressOfOperand,
  2057. TypeSourceInfo **RecoveryTSI) {
  2058. DeclContext *DC = computeDeclContext(SS, false);
  2059. if (!DC)
  2060. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2061. NameInfo, /*TemplateArgs=*/nullptr);
  2062. if (RequireCompleteDeclContext(SS, DC))
  2063. return ExprError();
  2064. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2065. LookupQualifiedName(R, DC);
  2066. if (R.isAmbiguous())
  2067. return ExprError();
  2068. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2069. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2070. NameInfo, /*TemplateArgs=*/nullptr);
  2071. if (R.empty()) {
  2072. Diag(NameInfo.getLoc(), diag::err_no_member)
  2073. << NameInfo.getName() << DC << SS.getRange();
  2074. return ExprError();
  2075. }
  2076. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2077. // Diagnose a missing typename if this resolved unambiguously to a type in
  2078. // a dependent context. If we can recover with a type, downgrade this to
  2079. // a warning in Microsoft compatibility mode.
  2080. unsigned DiagID = diag::err_typename_missing;
  2081. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2082. DiagID = diag::ext_typename_missing;
  2083. SourceLocation Loc = SS.getBeginLoc();
  2084. auto D = Diag(Loc, DiagID);
  2085. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2086. << SourceRange(Loc, NameInfo.getEndLoc());
  2087. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2088. // context.
  2089. if (!RecoveryTSI)
  2090. return ExprError();
  2091. // Only issue the fixit if we're prepared to recover.
  2092. D << FixItHint::CreateInsertion(Loc, "typename ");
  2093. // Recover by pretending this was an elaborated type.
  2094. QualType Ty = Context.getTypeDeclType(TD);
  2095. TypeLocBuilder TLB;
  2096. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2097. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2098. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2099. QTL.setElaboratedKeywordLoc(SourceLocation());
  2100. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2101. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2102. return ExprEmpty();
  2103. }
  2104. // Defend against this resolving to an implicit member access. We usually
  2105. // won't get here if this might be a legitimate a class member (we end up in
  2106. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2107. // a pointer-to-member or in an unevaluated context in C++11.
  2108. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2109. return BuildPossibleImplicitMemberExpr(SS,
  2110. /*TemplateKWLoc=*/SourceLocation(),
  2111. R, /*TemplateArgs=*/nullptr);
  2112. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2113. }
  2114. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2115. /// detected that we're currently inside an ObjC method. Perform some
  2116. /// additional lookup.
  2117. ///
  2118. /// Ideally, most of this would be done by lookup, but there's
  2119. /// actually quite a lot of extra work involved.
  2120. ///
  2121. /// Returns a null sentinel to indicate trivial success.
  2122. ExprResult
  2123. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2124. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2125. SourceLocation Loc = Lookup.getNameLoc();
  2126. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2127. // Check for error condition which is already reported.
  2128. if (!CurMethod)
  2129. return ExprError();
  2130. // There are two cases to handle here. 1) scoped lookup could have failed,
  2131. // in which case we should look for an ivar. 2) scoped lookup could have
  2132. // found a decl, but that decl is outside the current instance method (i.e.
  2133. // a global variable). In these two cases, we do a lookup for an ivar with
  2134. // this name, if the lookup sucedes, we replace it our current decl.
  2135. // If we're in a class method, we don't normally want to look for
  2136. // ivars. But if we don't find anything else, and there's an
  2137. // ivar, that's an error.
  2138. bool IsClassMethod = CurMethod->isClassMethod();
  2139. bool LookForIvars;
  2140. if (Lookup.empty())
  2141. LookForIvars = true;
  2142. else if (IsClassMethod)
  2143. LookForIvars = false;
  2144. else
  2145. LookForIvars = (Lookup.isSingleResult() &&
  2146. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2147. ObjCInterfaceDecl *IFace = nullptr;
  2148. if (LookForIvars) {
  2149. IFace = CurMethod->getClassInterface();
  2150. ObjCInterfaceDecl *ClassDeclared;
  2151. ObjCIvarDecl *IV = nullptr;
  2152. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2153. // Diagnose using an ivar in a class method.
  2154. if (IsClassMethod)
  2155. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2156. << IV->getDeclName());
  2157. // If we're referencing an invalid decl, just return this as a silent
  2158. // error node. The error diagnostic was already emitted on the decl.
  2159. if (IV->isInvalidDecl())
  2160. return ExprError();
  2161. // Check if referencing a field with __attribute__((deprecated)).
  2162. if (DiagnoseUseOfDecl(IV, Loc))
  2163. return ExprError();
  2164. // Diagnose the use of an ivar outside of the declaring class.
  2165. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2166. !declaresSameEntity(ClassDeclared, IFace) &&
  2167. !getLangOpts().DebuggerSupport)
  2168. Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
  2169. // FIXME: This should use a new expr for a direct reference, don't
  2170. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2171. IdentifierInfo &II = Context.Idents.get("self");
  2172. UnqualifiedId SelfName;
  2173. SelfName.setIdentifier(&II, SourceLocation());
  2174. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2175. CXXScopeSpec SelfScopeSpec;
  2176. SourceLocation TemplateKWLoc;
  2177. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2178. SelfName, false, false);
  2179. if (SelfExpr.isInvalid())
  2180. return ExprError();
  2181. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2182. if (SelfExpr.isInvalid())
  2183. return ExprError();
  2184. MarkAnyDeclReferenced(Loc, IV, true);
  2185. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2186. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2187. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2188. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2189. ObjCIvarRefExpr *Result = new (Context)
  2190. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2191. IV->getLocation(), SelfExpr.get(), true, true);
  2192. if (getLangOpts().ObjCAutoRefCount) {
  2193. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2194. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2195. recordUseOfEvaluatedWeak(Result);
  2196. }
  2197. if (CurContext->isClosure())
  2198. Diag(Loc, diag::warn_implicitly_retains_self)
  2199. << FixItHint::CreateInsertion(Loc, "self->");
  2200. }
  2201. return Result;
  2202. }
  2203. } else if (CurMethod->isInstanceMethod()) {
  2204. // We should warn if a local variable hides an ivar.
  2205. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2206. ObjCInterfaceDecl *ClassDeclared;
  2207. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2208. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2209. declaresSameEntity(IFace, ClassDeclared))
  2210. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2211. }
  2212. }
  2213. } else if (Lookup.isSingleResult() &&
  2214. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2215. // If accessing a stand-alone ivar in a class method, this is an error.
  2216. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2217. return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
  2218. << IV->getDeclName());
  2219. }
  2220. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2221. // FIXME. Consolidate this with similar code in LookupName.
  2222. if (unsigned BuiltinID = II->getBuiltinID()) {
  2223. if (!(getLangOpts().CPlusPlus &&
  2224. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2225. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2226. S, Lookup.isForRedeclaration(),
  2227. Lookup.getNameLoc());
  2228. if (D) Lookup.addDecl(D);
  2229. }
  2230. }
  2231. }
  2232. // Sentinel value saying that we didn't do anything special.
  2233. return ExprResult((Expr *)nullptr);
  2234. }
  2235. /// \brief Cast a base object to a member's actual type.
  2236. ///
  2237. /// Logically this happens in three phases:
  2238. ///
  2239. /// * First we cast from the base type to the naming class.
  2240. /// The naming class is the class into which we were looking
  2241. /// when we found the member; it's the qualifier type if a
  2242. /// qualifier was provided, and otherwise it's the base type.
  2243. ///
  2244. /// * Next we cast from the naming class to the declaring class.
  2245. /// If the member we found was brought into a class's scope by
  2246. /// a using declaration, this is that class; otherwise it's
  2247. /// the class declaring the member.
  2248. ///
  2249. /// * Finally we cast from the declaring class to the "true"
  2250. /// declaring class of the member. This conversion does not
  2251. /// obey access control.
  2252. ExprResult
  2253. Sema::PerformObjectMemberConversion(Expr *From,
  2254. NestedNameSpecifier *Qualifier,
  2255. NamedDecl *FoundDecl,
  2256. NamedDecl *Member) {
  2257. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2258. if (!RD)
  2259. return From;
  2260. QualType DestRecordType;
  2261. QualType DestType;
  2262. QualType FromRecordType;
  2263. QualType FromType = From->getType();
  2264. bool PointerConversions = false;
  2265. if (isa<FieldDecl>(Member)) {
  2266. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2267. if (FromType->getAs<PointerType>()) {
  2268. DestType = Context.getPointerType(DestRecordType);
  2269. FromRecordType = FromType->getPointeeType();
  2270. PointerConversions = true;
  2271. } else {
  2272. DestType = DestRecordType;
  2273. FromRecordType = FromType;
  2274. }
  2275. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2276. if (Method->isStatic())
  2277. return From;
  2278. DestType = Method->getThisType(Context);
  2279. DestRecordType = DestType->getPointeeType();
  2280. if (FromType->getAs<PointerType>()) {
  2281. FromRecordType = FromType->getPointeeType();
  2282. PointerConversions = true;
  2283. } else {
  2284. FromRecordType = FromType;
  2285. DestType = DestRecordType;
  2286. }
  2287. } else {
  2288. // No conversion necessary.
  2289. return From;
  2290. }
  2291. if (DestType->isDependentType() || FromType->isDependentType())
  2292. return From;
  2293. // If the unqualified types are the same, no conversion is necessary.
  2294. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2295. return From;
  2296. SourceRange FromRange = From->getSourceRange();
  2297. SourceLocation FromLoc = FromRange.getBegin();
  2298. ExprValueKind VK = From->getValueKind();
  2299. // C++ [class.member.lookup]p8:
  2300. // [...] Ambiguities can often be resolved by qualifying a name with its
  2301. // class name.
  2302. //
  2303. // If the member was a qualified name and the qualified referred to a
  2304. // specific base subobject type, we'll cast to that intermediate type
  2305. // first and then to the object in which the member is declared. That allows
  2306. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2307. //
  2308. // class Base { public: int x; };
  2309. // class Derived1 : public Base { };
  2310. // class Derived2 : public Base { };
  2311. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2312. //
  2313. // void VeryDerived::f() {
  2314. // x = 17; // error: ambiguous base subobjects
  2315. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2316. // }
  2317. if (Qualifier && Qualifier->getAsType()) {
  2318. QualType QType = QualType(Qualifier->getAsType(), 0);
  2319. assert(QType->isRecordType() && "lookup done with non-record type");
  2320. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2321. // In C++98, the qualifier type doesn't actually have to be a base
  2322. // type of the object type, in which case we just ignore it.
  2323. // Otherwise build the appropriate casts.
  2324. if (IsDerivedFrom(FromRecordType, QRecordType)) {
  2325. CXXCastPath BasePath;
  2326. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2327. FromLoc, FromRange, &BasePath))
  2328. return ExprError();
  2329. if (PointerConversions)
  2330. QType = Context.getPointerType(QType);
  2331. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2332. VK, &BasePath).get();
  2333. FromType = QType;
  2334. FromRecordType = QRecordType;
  2335. // If the qualifier type was the same as the destination type,
  2336. // we're done.
  2337. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2338. return From;
  2339. }
  2340. }
  2341. bool IgnoreAccess = false;
  2342. // If we actually found the member through a using declaration, cast
  2343. // down to the using declaration's type.
  2344. //
  2345. // Pointer equality is fine here because only one declaration of a
  2346. // class ever has member declarations.
  2347. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2348. assert(isa<UsingShadowDecl>(FoundDecl));
  2349. QualType URecordType = Context.getTypeDeclType(
  2350. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2351. // We only need to do this if the naming-class to declaring-class
  2352. // conversion is non-trivial.
  2353. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2354. assert(IsDerivedFrom(FromRecordType, URecordType));
  2355. CXXCastPath BasePath;
  2356. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2357. FromLoc, FromRange, &BasePath))
  2358. return ExprError();
  2359. QualType UType = URecordType;
  2360. if (PointerConversions)
  2361. UType = Context.getPointerType(UType);
  2362. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2363. VK, &BasePath).get();
  2364. FromType = UType;
  2365. FromRecordType = URecordType;
  2366. }
  2367. // We don't do access control for the conversion from the
  2368. // declaring class to the true declaring class.
  2369. IgnoreAccess = true;
  2370. }
  2371. CXXCastPath BasePath;
  2372. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2373. FromLoc, FromRange, &BasePath,
  2374. IgnoreAccess))
  2375. return ExprError();
  2376. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2377. VK, &BasePath);
  2378. }
  2379. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2380. const LookupResult &R,
  2381. bool HasTrailingLParen) {
  2382. // Only when used directly as the postfix-expression of a call.
  2383. if (!HasTrailingLParen)
  2384. return false;
  2385. // Never if a scope specifier was provided.
  2386. if (SS.isSet())
  2387. return false;
  2388. // Only in C++ or ObjC++.
  2389. if (!getLangOpts().CPlusPlus)
  2390. return false;
  2391. // Turn off ADL when we find certain kinds of declarations during
  2392. // normal lookup:
  2393. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2394. NamedDecl *D = *I;
  2395. // C++0x [basic.lookup.argdep]p3:
  2396. // -- a declaration of a class member
  2397. // Since using decls preserve this property, we check this on the
  2398. // original decl.
  2399. if (D->isCXXClassMember())
  2400. return false;
  2401. // C++0x [basic.lookup.argdep]p3:
  2402. // -- a block-scope function declaration that is not a
  2403. // using-declaration
  2404. // NOTE: we also trigger this for function templates (in fact, we
  2405. // don't check the decl type at all, since all other decl types
  2406. // turn off ADL anyway).
  2407. if (isa<UsingShadowDecl>(D))
  2408. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2409. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2410. return false;
  2411. // C++0x [basic.lookup.argdep]p3:
  2412. // -- a declaration that is neither a function or a function
  2413. // template
  2414. // And also for builtin functions.
  2415. if (isa<FunctionDecl>(D)) {
  2416. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2417. // But also builtin functions.
  2418. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2419. return false;
  2420. } else if (!isa<FunctionTemplateDecl>(D))
  2421. return false;
  2422. }
  2423. return true;
  2424. }
  2425. /// Diagnoses obvious problems with the use of the given declaration
  2426. /// as an expression. This is only actually called for lookups that
  2427. /// were not overloaded, and it doesn't promise that the declaration
  2428. /// will in fact be used.
  2429. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2430. if (isa<TypedefNameDecl>(D)) {
  2431. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2432. return true;
  2433. }
  2434. if (isa<ObjCInterfaceDecl>(D)) {
  2435. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2436. return true;
  2437. }
  2438. if (isa<NamespaceDecl>(D)) {
  2439. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2440. return true;
  2441. }
  2442. return false;
  2443. }
  2444. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2445. LookupResult &R, bool NeedsADL,
  2446. bool AcceptInvalidDecl) {
  2447. // If this is a single, fully-resolved result and we don't need ADL,
  2448. // just build an ordinary singleton decl ref.
  2449. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2450. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2451. R.getRepresentativeDecl(), nullptr,
  2452. AcceptInvalidDecl);
  2453. // We only need to check the declaration if there's exactly one
  2454. // result, because in the overloaded case the results can only be
  2455. // functions and function templates.
  2456. if (R.isSingleResult() &&
  2457. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2458. return ExprError();
  2459. // Otherwise, just build an unresolved lookup expression. Suppress
  2460. // any lookup-related diagnostics; we'll hash these out later, when
  2461. // we've picked a target.
  2462. R.suppressDiagnostics();
  2463. UnresolvedLookupExpr *ULE
  2464. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2465. SS.getWithLocInContext(Context),
  2466. R.getLookupNameInfo(),
  2467. NeedsADL, R.isOverloadedResult(),
  2468. R.begin(), R.end());
  2469. return ULE;
  2470. }
  2471. /// \brief Complete semantic analysis for a reference to the given declaration.
  2472. ExprResult Sema::BuildDeclarationNameExpr(
  2473. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2474. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2475. bool AcceptInvalidDecl) {
  2476. assert(D && "Cannot refer to a NULL declaration");
  2477. assert(!isa<FunctionTemplateDecl>(D) &&
  2478. "Cannot refer unambiguously to a function template");
  2479. SourceLocation Loc = NameInfo.getLoc();
  2480. if (CheckDeclInExpr(*this, Loc, D))
  2481. return ExprError();
  2482. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2483. // Specifically diagnose references to class templates that are missing
  2484. // a template argument list.
  2485. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2486. << Template << SS.getRange();
  2487. if (Template->getLocation().isValid()) { // HLSL Change - ellide location notes for built-ins
  2488. Diag(Template->getLocation(), diag::note_template_decl_here);
  2489. }
  2490. return ExprError();
  2491. }
  2492. // Make sure that we're referring to a value.
  2493. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2494. if (!VD) {
  2495. Diag(Loc, diag::err_ref_non_value)
  2496. << D << SS.getRange();
  2497. Diag(D->getLocation(), diag::note_declared_at);
  2498. return ExprError();
  2499. }
  2500. // Check whether this declaration can be used. Note that we suppress
  2501. // this check when we're going to perform argument-dependent lookup
  2502. // on this function name, because this might not be the function
  2503. // that overload resolution actually selects.
  2504. if (DiagnoseUseOfDecl(VD, Loc))
  2505. return ExprError();
  2506. // Only create DeclRefExpr's for valid Decl's.
  2507. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2508. return ExprError();
  2509. // Handle members of anonymous structs and unions. If we got here,
  2510. // and the reference is to a class member indirect field, then this
  2511. // must be the subject of a pointer-to-member expression.
  2512. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2513. if (!indirectField->isCXXClassMember())
  2514. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2515. indirectField);
  2516. {
  2517. QualType type = VD->getType();
  2518. ExprValueKind valueKind = VK_RValue;
  2519. switch (D->getKind()) {
  2520. // Ignore all the non-ValueDecl kinds.
  2521. #define ABSTRACT_DECL(kind)
  2522. #define VALUE(type, base)
  2523. #define DECL(type, base) \
  2524. case Decl::type:
  2525. #include "clang/AST/DeclNodes.inc"
  2526. llvm_unreachable("invalid value decl kind");
  2527. // These shouldn't make it here.
  2528. case Decl::ObjCAtDefsField:
  2529. case Decl::ObjCIvar:
  2530. llvm_unreachable("forming non-member reference to ivar?");
  2531. // Enum constants are always r-values and never references.
  2532. // Unresolved using declarations are dependent.
  2533. case Decl::EnumConstant:
  2534. case Decl::UnresolvedUsingValue:
  2535. valueKind = VK_RValue;
  2536. break;
  2537. // Fields and indirect fields that got here must be for
  2538. // pointer-to-member expressions; we just call them l-values for
  2539. // internal consistency, because this subexpression doesn't really
  2540. // exist in the high-level semantics.
  2541. case Decl::Field:
  2542. case Decl::IndirectField:
  2543. assert(getLangOpts().CPlusPlus &&
  2544. "building reference to field in C?");
  2545. // These can't have reference type in well-formed programs, but
  2546. // for internal consistency we do this anyway.
  2547. type = type.getNonReferenceType();
  2548. valueKind = VK_LValue;
  2549. break;
  2550. // Non-type template parameters are either l-values or r-values
  2551. // depending on the type.
  2552. case Decl::NonTypeTemplateParm: {
  2553. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2554. type = reftype->getPointeeType();
  2555. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2556. break;
  2557. }
  2558. // For non-references, we need to strip qualifiers just in case
  2559. // the template parameter was declared as 'const int' or whatever.
  2560. valueKind = VK_RValue;
  2561. type = type.getUnqualifiedType();
  2562. break;
  2563. }
  2564. case Decl::Var:
  2565. case Decl::VarTemplateSpecialization:
  2566. case Decl::VarTemplatePartialSpecialization:
  2567. // In C, "extern void blah;" is valid and is an r-value.
  2568. if (!getLangOpts().CPlusPlus &&
  2569. !type.hasQualifiers() &&
  2570. type->isVoidType()) {
  2571. valueKind = VK_RValue;
  2572. break;
  2573. }
  2574. // fallthrough
  2575. case Decl::ImplicitParam:
  2576. case Decl::ParmVar: {
  2577. // These are always l-values.
  2578. valueKind = VK_LValue;
  2579. type = type.getNonReferenceType();
  2580. // FIXME: Does the addition of const really only apply in
  2581. // potentially-evaluated contexts? Since the variable isn't actually
  2582. // captured in an unevaluated context, it seems that the answer is no.
  2583. if (!isUnevaluatedContext()) {
  2584. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2585. if (!CapturedType.isNull())
  2586. type = CapturedType;
  2587. }
  2588. break;
  2589. }
  2590. case Decl::Function: {
  2591. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2592. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2593. type = Context.BuiltinFnTy;
  2594. valueKind = VK_RValue;
  2595. break;
  2596. }
  2597. }
  2598. const FunctionType *fty = type->castAs<FunctionType>();
  2599. // If we're referring to a function with an __unknown_anytype
  2600. // result type, make the entire expression __unknown_anytype.
  2601. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2602. type = Context.UnknownAnyTy;
  2603. valueKind = VK_RValue;
  2604. break;
  2605. }
  2606. // Functions are l-values in C++.
  2607. if (getLangOpts().CPlusPlus) {
  2608. valueKind = VK_LValue;
  2609. break;
  2610. }
  2611. // C99 DR 316 says that, if a function type comes from a
  2612. // function definition (without a prototype), that type is only
  2613. // used for checking compatibility. Therefore, when referencing
  2614. // the function, we pretend that we don't have the full function
  2615. // type.
  2616. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2617. isa<FunctionProtoType>(fty))
  2618. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2619. fty->getExtInfo());
  2620. // Functions are r-values in C.
  2621. valueKind = VK_RValue;
  2622. break;
  2623. }
  2624. case Decl::MSProperty:
  2625. valueKind = VK_LValue;
  2626. break;
  2627. case Decl::CXXMethod:
  2628. // If we're referring to a method with an __unknown_anytype
  2629. // result type, make the entire expression __unknown_anytype.
  2630. // This should only be possible with a type written directly.
  2631. if (const FunctionProtoType *proto
  2632. = dyn_cast<FunctionProtoType>(VD->getType()))
  2633. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2634. type = Context.UnknownAnyTy;
  2635. valueKind = VK_RValue;
  2636. break;
  2637. }
  2638. // C++ methods are l-values if static, r-values if non-static.
  2639. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2640. valueKind = VK_LValue;
  2641. break;
  2642. }
  2643. // fallthrough
  2644. case Decl::CXXConversion:
  2645. case Decl::CXXDestructor:
  2646. case Decl::CXXConstructor:
  2647. valueKind = VK_RValue;
  2648. break;
  2649. }
  2650. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2651. TemplateArgs);
  2652. }
  2653. }
  2654. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2655. SmallString<32> &Target) {
  2656. Target.resize(CharByteWidth * (Source.size() + 1));
  2657. char *ResultPtr = &Target[0];
  2658. const UTF8 *ErrorPtr;
  2659. bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2660. (void)success;
  2661. assert(success);
  2662. Target.resize(ResultPtr - &Target[0]);
  2663. }
  2664. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2665. PredefinedExpr::IdentType IT) {
  2666. // Pick the current block, lambda, captured statement or function.
  2667. Decl *currentDecl = nullptr;
  2668. if (const BlockScopeInfo *BSI = getCurBlock())
  2669. currentDecl = BSI->TheDecl;
  2670. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2671. currentDecl = LSI->CallOperator;
  2672. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2673. currentDecl = CSI->TheCapturedDecl;
  2674. else
  2675. currentDecl = getCurFunctionOrMethodDecl();
  2676. if (!currentDecl) {
  2677. Diag(Loc, diag::ext_predef_outside_function);
  2678. currentDecl = Context.getTranslationUnitDecl();
  2679. }
  2680. QualType ResTy;
  2681. StringLiteral *SL = nullptr;
  2682. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2683. ResTy = Context.DependentTy;
  2684. else {
  2685. // Pre-defined identifiers are of type char[x], where x is the length of
  2686. // the string.
  2687. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2688. unsigned Length = Str.length();
  2689. llvm::APInt LengthI(32, Length + 1);
  2690. if (IT == PredefinedExpr::LFunction) {
  2691. ResTy = Context.WideCharTy.withConst();
  2692. SmallString<32> RawChars;
  2693. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2694. Str, RawChars);
  2695. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2696. /*IndexTypeQuals*/ 0);
  2697. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2698. /*Pascal*/ false, ResTy, Loc);
  2699. } else {
  2700. ResTy = Context.CharTy.withConst();
  2701. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2702. /*IndexTypeQuals*/ 0);
  2703. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2704. /*Pascal*/ false, ResTy, Loc);
  2705. }
  2706. }
  2707. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2708. }
  2709. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2710. PredefinedExpr::IdentType IT;
  2711. switch (Kind) {
  2712. default: llvm_unreachable("Unknown simple primary expr!");
  2713. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2714. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2715. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2716. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2717. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2718. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2719. }
  2720. return BuildPredefinedExpr(Loc, IT);
  2721. }
  2722. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2723. SmallString<16> CharBuffer;
  2724. bool Invalid = false;
  2725. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2726. if (Invalid)
  2727. return ExprError();
  2728. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2729. PP, Tok.getKind());
  2730. if (Literal.hadError())
  2731. return ExprError();
  2732. // HLSL Change Starts
  2733. if (getLangOpts().HLSL) {
  2734. if (Literal.isWide() || Literal.isUTF16() || Literal.isUTF32() || Literal.isMultiChar()) {
  2735. Diag(Tok.getLocation(), diag::err_hlsl_unsupported_char_literal);
  2736. return ExprError();
  2737. }
  2738. Expr *CharLit = new (Context)CharacterLiteral(Literal.getValue(), CharacterLiteral::Ascii, Context.CharTy,
  2739. Tok.getLocation());
  2740. Expr* Result = ImplicitCastExpr::Create(Context,
  2741. Context.UnsignedIntTy, CK_IntegralCast, CharLit, nullptr, VK_RValue);
  2742. return Result;
  2743. }
  2744. // HLSL Change Ends
  2745. QualType Ty;
  2746. if (Literal.isWide())
  2747. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2748. else if (Literal.isUTF16())
  2749. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2750. else if (Literal.isUTF32())
  2751. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2752. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2753. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2754. else
  2755. Ty = Context.CharTy; // 'x' -> char in C++
  2756. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2757. if (Literal.isWide())
  2758. Kind = CharacterLiteral::Wide;
  2759. else if (Literal.isUTF16())
  2760. Kind = CharacterLiteral::UTF16;
  2761. else if (Literal.isUTF32())
  2762. Kind = CharacterLiteral::UTF32;
  2763. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2764. Tok.getLocation());
  2765. if (Literal.getUDSuffix().empty())
  2766. return Lit;
  2767. // We're building a user-defined literal.
  2768. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2769. SourceLocation UDSuffixLoc =
  2770. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2771. // Make sure we're allowed user-defined literals here.
  2772. if (!UDLScope)
  2773. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2774. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2775. // operator "" X (ch)
  2776. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2777. Lit, Tok.getLocation());
  2778. }
  2779. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2780. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2781. // HLSL Change Starts - HLSL literal int
  2782. QualType Ty;
  2783. if (getLangOpts().HLSL) {
  2784. IntSize = 64;
  2785. Ty = Context.LitIntTy;
  2786. } else
  2787. Ty = Context.IntTy;
  2788. // HLSL Change Ends
  2789. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2790. Ty, Loc); // HLSL Change
  2791. }
  2792. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2793. QualType Ty, SourceLocation Loc) {
  2794. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2795. using llvm::APFloat;
  2796. APFloat Val(Format);
  2797. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2798. // Overflow is always an error, but underflow is only an error if
  2799. // we underflowed to zero (APFloat reports denormals as underflow).
  2800. if ((result & APFloat::opOverflow) ||
  2801. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2802. unsigned diagnostic;
  2803. SmallString<20> buffer;
  2804. if (result & APFloat::opOverflow) {
  2805. diagnostic = diag::warn_float_overflow;
  2806. APFloat::getLargest(Format).toString(buffer);
  2807. } else {
  2808. diagnostic = diag::warn_float_underflow;
  2809. APFloat::getSmallest(Format).toString(buffer);
  2810. }
  2811. S.Diag(Loc, diagnostic)
  2812. << Ty
  2813. << StringRef(buffer.data(), buffer.size());
  2814. }
  2815. bool isExact = (result == APFloat::opOK);
  2816. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2817. }
  2818. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2819. assert(E && "Invalid expression");
  2820. if (E->isValueDependent())
  2821. return false;
  2822. QualType QT = E->getType();
  2823. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2824. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2825. return true;
  2826. }
  2827. llvm::APSInt ValueAPS;
  2828. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2829. if (R.isInvalid())
  2830. return true;
  2831. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2832. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2833. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2834. << ValueAPS.toString(10) << ValueIsPositive;
  2835. return true;
  2836. }
  2837. return false;
  2838. }
  2839. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2840. // Fast path for a single digit (which is quite common). A single digit
  2841. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2842. if (Tok.getLength() == 1) {
  2843. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2844. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2845. }
  2846. SmallString<128> SpellingBuffer;
  2847. // NumericLiteralParser wants to overread by one character. Add padding to
  2848. // the buffer in case the token is copied to the buffer. If getSpelling()
  2849. // returns a StringRef to the memory buffer, it should have a null char at
  2850. // the EOF, so it is also safe.
  2851. SpellingBuffer.resize(Tok.getLength() + 1);
  2852. // Get the spelling of the token, which eliminates trigraphs, etc.
  2853. bool Invalid = false;
  2854. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2855. if (Invalid)
  2856. return ExprError();
  2857. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2858. if (Literal.hadError)
  2859. return ExprError();
  2860. if (Literal.hasUDSuffix()) {
  2861. // We're building a user-defined literal.
  2862. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2863. SourceLocation UDSuffixLoc =
  2864. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2865. // Make sure we're allowed user-defined literals here.
  2866. if (!UDLScope)
  2867. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2868. QualType CookedTy;
  2869. if (Literal.isFloatingLiteral()) {
  2870. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2871. // long double, the literal is treated as a call of the form
  2872. // operator "" X (f L)
  2873. CookedTy = Context.LongDoubleTy;
  2874. } else {
  2875. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2876. // unsigned long long, the literal is treated as a call of the form
  2877. // operator "" X (n ULL)
  2878. CookedTy = Context.UnsignedLongLongTy;
  2879. }
  2880. DeclarationName OpName =
  2881. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2882. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2883. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2884. SourceLocation TokLoc = Tok.getLocation();
  2885. // Perform literal operator lookup to determine if we're building a raw
  2886. // literal or a cooked one.
  2887. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2888. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2889. /*AllowRaw*/true, /*AllowTemplate*/true,
  2890. /*AllowStringTemplate*/false)) {
  2891. case LOLR_Error:
  2892. return ExprError();
  2893. case LOLR_Cooked: {
  2894. Expr *Lit;
  2895. if (Literal.isFloatingLiteral()) {
  2896. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2897. } else {
  2898. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2899. if (Literal.GetIntegerValue(ResultVal))
  2900. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2901. << /* Unsigned */ 1;
  2902. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2903. Tok.getLocation());
  2904. }
  2905. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2906. }
  2907. case LOLR_Raw: {
  2908. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2909. // literal is treated as a call of the form
  2910. // operator "" X ("n")
  2911. unsigned Length = Literal.getUDSuffixOffset();
  2912. QualType StrTy = Context.getConstantArrayType(
  2913. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2914. ArrayType::Normal, 0);
  2915. Expr *Lit = StringLiteral::Create(
  2916. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2917. /*Pascal*/false, StrTy, &TokLoc, 1);
  2918. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2919. }
  2920. case LOLR_Template: {
  2921. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2922. // template), L is treated as a call fo the form
  2923. // operator "" X <'c1', 'c2', ... 'ck'>()
  2924. // where n is the source character sequence c1 c2 ... ck.
  2925. TemplateArgumentListInfo ExplicitArgs;
  2926. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2927. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2928. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2929. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2930. Value = TokSpelling[I];
  2931. TemplateArgument Arg(Context, Value, Context.CharTy);
  2932. TemplateArgumentLocInfo ArgInfo;
  2933. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2934. }
  2935. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2936. &ExplicitArgs);
  2937. }
  2938. case LOLR_StringTemplate:
  2939. llvm_unreachable("unexpected literal operator lookup result");
  2940. }
  2941. }
  2942. Expr *Res;
  2943. if (Literal.isFloatingLiteral()) {
  2944. QualType Ty;
  2945. if (Literal.isFloat)
  2946. Ty = Context.FloatTy;
  2947. // HLSL Change Starts
  2948. else if (getLangOpts().HLSL && !Literal.isLong && !Literal.isHalf)
  2949. Ty = Context.LitFloatTy;
  2950. else if (getLangOpts().HLSL && Literal.isLong)
  2951. Ty = Context.DoubleTy;
  2952. else if (getLangOpts().HLSL && Literal.isHalf) {
  2953. Ty = getLangOpts().UseMinPrecision ? Context.FloatTy : Context.HalfTy;
  2954. }
  2955. // HLSL Change Ends
  2956. else if (!Literal.isLong)
  2957. Ty = Context.DoubleTy;
  2958. else
  2959. Ty = Context.LongDoubleTy;
  2960. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2961. if (Ty == Context.DoubleTy) {
  2962. if (getLangOpts().SinglePrecisionConstants) {
  2963. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2964. } else if (getLangOpts().OpenCL &&
  2965. !((getLangOpts().OpenCLVersion >= 120) ||
  2966. getOpenCLOptions().cl_khr_fp64)) {
  2967. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2968. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2969. }
  2970. }
  2971. } else if (!Literal.isIntegerLiteral()) {
  2972. return ExprError();
  2973. // HLSL Change Starts
  2974. } else if (getLangOpts().HLSL) {
  2975. QualType Ty;
  2976. unsigned Width = 64;
  2977. llvm::APInt ResultVal(Width, 0);
  2978. if (!Literal.isLong && !Literal.isLongLong &&
  2979. !Literal.isUnsigned && Literal.getRadix() == 10) {
  2980. // in HLSL, unspecific literal ints are LitIntTy, using 64-bit
  2981. Ty = Context.LitIntTy;
  2982. if (Literal.GetIntegerValue(ResultVal)) {
  2983. // If this value didn't fit into 64-bit literal int, report error.
  2984. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  2985. }
  2986. } else {
  2987. if (Literal.GetIntegerValue(ResultVal)) {
  2988. Diag(Tok.getLocation(), diag::err_integer_literal_too_large);
  2989. }
  2990. if (Literal.isLongLong) {
  2991. if (Literal.isUnsigned)
  2992. Ty = Context.UnsignedLongLongTy;
  2993. else
  2994. Ty = Context.LongLongTy;
  2995. }
  2996. else {
  2997. // long is the same as int for HLSL, so ignore isLong here
  2998. Width = 32;
  2999. ResultVal = ResultVal.trunc(Width);
  3000. if (Literal.isUnsigned || Literal.getRadix() != 10)
  3001. Ty = Context.UnsignedIntTy;
  3002. else
  3003. Ty = Context.IntTy;
  3004. }
  3005. }
  3006. return IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3007. // HLSL Change Ends
  3008. } else {
  3009. QualType Ty;
  3010. // 'long long' is a C99 or C++11 feature.
  3011. if (!getLangOpts().C99 && Literal.isLongLong) {
  3012. if (getLangOpts().CPlusPlus)
  3013. Diag(Tok.getLocation(),
  3014. getLangOpts().CPlusPlus11 ?
  3015. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3016. else
  3017. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3018. }
  3019. // Get the value in the widest-possible width.
  3020. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3021. // The microsoft literal suffix extensions support 128-bit literals, which
  3022. // may be wider than [u]intmax_t.
  3023. // FIXME: Actually, they don't. We seem to have accidentally invented the
  3024. // i128 suffix.
  3025. if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
  3026. Context.getTargetInfo().hasInt128Type())
  3027. MaxWidth = 128;
  3028. llvm::APInt ResultVal(MaxWidth, 0);
  3029. if (Literal.GetIntegerValue(ResultVal)) {
  3030. // If this value didn't fit into uintmax_t, error and force to ull.
  3031. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3032. << /* Unsigned */ 1;
  3033. Ty = Context.UnsignedLongLongTy;
  3034. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3035. "long long is not intmax_t?");
  3036. } else {
  3037. // If this value fits into a ULL, try to figure out what else it fits into
  3038. // according to the rules of C99 6.4.4.1p5.
  3039. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3040. // be an unsigned int.
  3041. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3042. // Check from smallest to largest, picking the smallest type we can.
  3043. unsigned Width = 0;
  3044. // Microsoft specific integer suffixes are explicitly sized.
  3045. if (Literal.MicrosoftInteger) {
  3046. if (Literal.MicrosoftInteger > MaxWidth) {
  3047. // If this target doesn't support __int128, error and force to ull.
  3048. Diag(Tok.getLocation(), diag::err_int128_unsupported);
  3049. Width = MaxWidth;
  3050. Ty = Context.getIntMaxType();
  3051. } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3052. Width = 8;
  3053. Ty = Context.CharTy;
  3054. } else {
  3055. Width = Literal.MicrosoftInteger;
  3056. Ty = Context.getIntTypeForBitwidth(Width,
  3057. /*Signed=*/!Literal.isUnsigned);
  3058. }
  3059. }
  3060. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3061. // Are int/unsigned possibilities?
  3062. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3063. // Does it fit in a unsigned int?
  3064. if (ResultVal.isIntN(IntSize)) {
  3065. // Does it fit in a signed int?
  3066. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3067. Ty = Context.IntTy;
  3068. else if (AllowUnsigned)
  3069. Ty = Context.UnsignedIntTy;
  3070. Width = IntSize;
  3071. }
  3072. }
  3073. // Are long/unsigned long possibilities?
  3074. if (Ty.isNull() && !Literal.isLongLong) {
  3075. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3076. // Does it fit in a unsigned long?
  3077. if (ResultVal.isIntN(LongSize)) {
  3078. // Does it fit in a signed long?
  3079. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3080. Ty = Context.LongTy;
  3081. else if (AllowUnsigned)
  3082. Ty = Context.UnsignedLongTy;
  3083. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3084. // is compatible.
  3085. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3086. const unsigned LongLongSize =
  3087. Context.getTargetInfo().getLongLongWidth();
  3088. Diag(Tok.getLocation(),
  3089. getLangOpts().CPlusPlus
  3090. ? Literal.isLong
  3091. ? diag::warn_old_implicitly_unsigned_long_cxx
  3092. : /*C++98 UB*/ diag::
  3093. ext_old_implicitly_unsigned_long_cxx
  3094. : diag::warn_old_implicitly_unsigned_long)
  3095. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3096. : /*will be ill-formed*/ 1);
  3097. Ty = Context.UnsignedLongTy;
  3098. }
  3099. Width = LongSize;
  3100. }
  3101. }
  3102. // Check long long if needed.
  3103. if (Ty.isNull()) {
  3104. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3105. // Does it fit in a unsigned long long?
  3106. if (ResultVal.isIntN(LongLongSize)) {
  3107. // Does it fit in a signed long long?
  3108. // To be compatible with MSVC, hex integer literals ending with the
  3109. // LL or i64 suffix are always signed in Microsoft mode.
  3110. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3111. (getLangOpts().MicrosoftExt && Literal.isLongLong)))
  3112. Ty = Context.LongLongTy;
  3113. else if (AllowUnsigned)
  3114. Ty = Context.UnsignedLongLongTy;
  3115. Width = LongLongSize;
  3116. }
  3117. }
  3118. // If we still couldn't decide a type, we probably have something that
  3119. // does not fit in a signed long long, but has no U suffix.
  3120. if (Ty.isNull()) {
  3121. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3122. Ty = Context.UnsignedLongLongTy;
  3123. Width = Context.getTargetInfo().getLongLongWidth();
  3124. }
  3125. if (ResultVal.getBitWidth() != Width)
  3126. ResultVal = ResultVal.trunc(Width);
  3127. }
  3128. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3129. }
  3130. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3131. if (Literal.isImaginary)
  3132. Res = new (Context) ImaginaryLiteral(Res,
  3133. Context.getComplexType(Res->getType()));
  3134. return Res;
  3135. }
  3136. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3137. assert(E && "ActOnParenExpr() missing expr");
  3138. return new (Context) ParenExpr(L, R, E);
  3139. }
  3140. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3141. SourceLocation Loc,
  3142. SourceRange ArgRange) {
  3143. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3144. // scalar or vector data type argument..."
  3145. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3146. // type (C99 6.2.5p18) or void.
  3147. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3148. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3149. << T << ArgRange;
  3150. return true;
  3151. }
  3152. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3153. "Scalar types should always be complete");
  3154. return false;
  3155. }
  3156. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3157. SourceLocation Loc,
  3158. SourceRange ArgRange,
  3159. UnaryExprOrTypeTrait TraitKind) {
  3160. // Invalid types must be hard errors for SFINAE in C++.
  3161. if (S.LangOpts.CPlusPlus)
  3162. return true;
  3163. // C99 6.5.3.4p1:
  3164. if (T->isFunctionType() &&
  3165. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3166. // sizeof(function)/alignof(function) is allowed as an extension.
  3167. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3168. << TraitKind << ArgRange;
  3169. return false;
  3170. }
  3171. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3172. // this is an error (OpenCL v1.1 s6.3.k)
  3173. if (T->isVoidType()) {
  3174. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3175. : diag::ext_sizeof_alignof_void_type;
  3176. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3177. return false;
  3178. }
  3179. return true;
  3180. }
  3181. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3182. SourceLocation Loc,
  3183. SourceRange ArgRange,
  3184. UnaryExprOrTypeTrait TraitKind) {
  3185. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3186. // runtime doesn't allow it.
  3187. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3188. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3189. << T << (TraitKind == UETT_SizeOf)
  3190. << ArgRange;
  3191. return true;
  3192. }
  3193. return false;
  3194. }
  3195. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3196. /// pointer type is equal to T) and emit a warning if it is.
  3197. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3198. Expr *E) {
  3199. // Don't warn if the operation changed the type.
  3200. if (T != E->getType())
  3201. return;
  3202. // Now look for array decays.
  3203. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3204. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3205. return;
  3206. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3207. << ICE->getType()
  3208. << ICE->getSubExpr()->getType();
  3209. }
  3210. /// \brief Check the constraints on expression operands to unary type expression
  3211. /// and type traits.
  3212. ///
  3213. /// Completes any types necessary and validates the constraints on the operand
  3214. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3215. /// the expression as it completes the type for that expression through template
  3216. /// instantiation, etc.
  3217. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3218. UnaryExprOrTypeTrait ExprKind) {
  3219. QualType ExprTy = E->getType();
  3220. assert(!ExprTy->isReferenceType());
  3221. if (ExprKind == UETT_VecStep)
  3222. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3223. E->getSourceRange());
  3224. // Whitelist some types as extensions
  3225. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3226. E->getSourceRange(), ExprKind))
  3227. return false;
  3228. // 'alignof' applied to an expression only requires the base element type of
  3229. // the expression to be complete. 'sizeof' requires the expression's type to
  3230. // be complete (and will attempt to complete it if it's an array of unknown
  3231. // bound).
  3232. if (ExprKind == UETT_AlignOf) {
  3233. if (RequireCompleteType(E->getExprLoc(),
  3234. Context.getBaseElementType(E->getType()),
  3235. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3236. E->getSourceRange()))
  3237. return true;
  3238. } else {
  3239. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3240. ExprKind, E->getSourceRange()))
  3241. return true;
  3242. }
  3243. // Completing the expression's type may have changed it.
  3244. ExprTy = E->getType();
  3245. assert(!ExprTy->isReferenceType());
  3246. if (ExprTy->isFunctionType()) {
  3247. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3248. << ExprKind << E->getSourceRange();
  3249. return true;
  3250. }
  3251. // The operand for sizeof and alignof is in an unevaluated expression context,
  3252. // so side effects could result in unintended consequences.
  3253. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3254. ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
  3255. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3256. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3257. E->getSourceRange(), ExprKind))
  3258. return true;
  3259. if (ExprKind == UETT_SizeOf) {
  3260. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3261. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3262. QualType OType = PVD->getOriginalType();
  3263. QualType Type = PVD->getType();
  3264. if (Type->isPointerType() && OType->isArrayType()) {
  3265. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3266. << Type << OType;
  3267. Diag(PVD->getLocation(), diag::note_declared_at);
  3268. }
  3269. }
  3270. }
  3271. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3272. // decays into a pointer and returns an unintended result. This is most
  3273. // likely a typo for "sizeof(array) op x".
  3274. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3275. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3276. BO->getLHS());
  3277. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3278. BO->getRHS());
  3279. }
  3280. }
  3281. return false;
  3282. }
  3283. /// \brief Check the constraints on operands to unary expression and type
  3284. /// traits.
  3285. ///
  3286. /// This will complete any types necessary, and validate the various constraints
  3287. /// on those operands.
  3288. ///
  3289. /// The UsualUnaryConversions() function is *not* called by this routine.
  3290. /// C99 6.3.2.1p[2-4] all state:
  3291. /// Except when it is the operand of the sizeof operator ...
  3292. ///
  3293. /// C++ [expr.sizeof]p4
  3294. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3295. /// standard conversions are not applied to the operand of sizeof.
  3296. ///
  3297. /// This policy is followed for all of the unary trait expressions.
  3298. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3299. SourceLocation OpLoc,
  3300. SourceRange ExprRange,
  3301. UnaryExprOrTypeTrait ExprKind) {
  3302. if (ExprType->isDependentType())
  3303. return false;
  3304. // C++ [expr.sizeof]p2:
  3305. // When applied to a reference or a reference type, the result
  3306. // is the size of the referenced type.
  3307. // C++11 [expr.alignof]p3:
  3308. // When alignof is applied to a reference type, the result
  3309. // shall be the alignment of the referenced type.
  3310. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3311. ExprType = Ref->getPointeeType();
  3312. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3313. // When alignof or _Alignof is applied to an array type, the result
  3314. // is the alignment of the element type.
  3315. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3316. ExprType = Context.getBaseElementType(ExprType);
  3317. if (ExprKind == UETT_VecStep)
  3318. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3319. // Whitelist some types as extensions
  3320. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3321. ExprKind))
  3322. return false;
  3323. if (RequireCompleteType(OpLoc, ExprType,
  3324. diag::err_sizeof_alignof_incomplete_type,
  3325. ExprKind, ExprRange))
  3326. return true;
  3327. if (ExprType->isFunctionType()) {
  3328. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3329. << ExprKind << ExprRange;
  3330. return true;
  3331. }
  3332. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3333. ExprKind))
  3334. return true;
  3335. return false;
  3336. }
  3337. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3338. E = E->IgnoreParens();
  3339. // Cannot know anything else if the expression is dependent.
  3340. if (E->isTypeDependent())
  3341. return false;
  3342. if (E->getObjectKind() == OK_BitField) {
  3343. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
  3344. << 1 << E->getSourceRange();
  3345. return true;
  3346. }
  3347. ValueDecl *D = nullptr;
  3348. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3349. D = DRE->getDecl();
  3350. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3351. D = ME->getMemberDecl();
  3352. }
  3353. // If it's a field, require the containing struct to have a
  3354. // complete definition so that we can compute the layout.
  3355. //
  3356. // This can happen in C++11 onwards, either by naming the member
  3357. // in a way that is not transformed into a member access expression
  3358. // (in an unevaluated operand, for instance), or by naming the member
  3359. // in a trailing-return-type.
  3360. //
  3361. // For the record, since __alignof__ on expressions is a GCC
  3362. // extension, GCC seems to permit this but always gives the
  3363. // nonsensical answer 0.
  3364. //
  3365. // We don't really need the layout here --- we could instead just
  3366. // directly check for all the appropriate alignment-lowing
  3367. // attributes --- but that would require duplicating a lot of
  3368. // logic that just isn't worth duplicating for such a marginal
  3369. // use-case.
  3370. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3371. // Fast path this check, since we at least know the record has a
  3372. // definition if we can find a member of it.
  3373. if (!FD->getParent()->isCompleteDefinition()) {
  3374. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3375. << E->getSourceRange();
  3376. return true;
  3377. }
  3378. // Otherwise, if it's a field, and the field doesn't have
  3379. // reference type, then it must have a complete type (or be a
  3380. // flexible array member, which we explicitly want to
  3381. // white-list anyway), which makes the following checks trivial.
  3382. if (!FD->getType()->isReferenceType())
  3383. return false;
  3384. }
  3385. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3386. }
  3387. bool Sema::CheckVecStepExpr(Expr *E) {
  3388. E = E->IgnoreParens();
  3389. // Cannot know anything else if the expression is dependent.
  3390. if (E->isTypeDependent())
  3391. return false;
  3392. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3393. }
  3394. /// \brief Build a sizeof or alignof expression given a type operand.
  3395. ExprResult
  3396. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3397. SourceLocation OpLoc,
  3398. UnaryExprOrTypeTrait ExprKind,
  3399. SourceRange R) {
  3400. if (!TInfo)
  3401. return ExprError();
  3402. QualType T = TInfo->getType();
  3403. if (!T->isDependentType() &&
  3404. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3405. return ExprError();
  3406. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3407. return new (Context) UnaryExprOrTypeTraitExpr(
  3408. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3409. }
  3410. /// \brief Build a sizeof or alignof expression given an expression
  3411. /// operand.
  3412. ExprResult
  3413. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3414. UnaryExprOrTypeTrait ExprKind) {
  3415. ExprResult PE = CheckPlaceholderExpr(E);
  3416. if (PE.isInvalid())
  3417. return ExprError();
  3418. E = PE.get();
  3419. // Verify that the operand is valid.
  3420. bool isInvalid = false;
  3421. if (E->isTypeDependent()) {
  3422. // Delay type-checking for type-dependent expressions.
  3423. } else if (ExprKind == UETT_AlignOf) {
  3424. isInvalid = CheckAlignOfExpr(*this, E);
  3425. } else if (ExprKind == UETT_VecStep) {
  3426. isInvalid = CheckVecStepExpr(E);
  3427. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3428. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3429. isInvalid = true;
  3430. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3431. Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
  3432. isInvalid = true;
  3433. } else {
  3434. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3435. }
  3436. if (isInvalid)
  3437. return ExprError();
  3438. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3439. PE = TransformToPotentiallyEvaluated(E);
  3440. if (PE.isInvalid()) return ExprError();
  3441. E = PE.get();
  3442. }
  3443. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3444. return new (Context) UnaryExprOrTypeTraitExpr(
  3445. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3446. }
  3447. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3448. /// expr and the same for @c alignof and @c __alignof
  3449. /// Note that the ArgRange is invalid if isType is false.
  3450. ExprResult
  3451. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3452. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3453. void *TyOrEx, const SourceRange &ArgRange) {
  3454. // If error parsing type, ignore.
  3455. if (!TyOrEx) return ExprError();
  3456. if (IsType) {
  3457. TypeSourceInfo *TInfo;
  3458. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3459. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3460. }
  3461. Expr *ArgEx = (Expr *)TyOrEx;
  3462. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3463. return Result;
  3464. }
  3465. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3466. bool IsReal) {
  3467. if (V.get()->isTypeDependent())
  3468. return S.Context.DependentTy;
  3469. // _Real and _Imag are only l-values for normal l-values.
  3470. if (V.get()->getObjectKind() != OK_Ordinary) {
  3471. V = S.DefaultLvalueConversion(V.get());
  3472. if (V.isInvalid())
  3473. return QualType();
  3474. }
  3475. // These operators return the element type of a complex type.
  3476. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3477. return CT->getElementType();
  3478. // Otherwise they pass through real integer and floating point types here.
  3479. if (V.get()->getType()->isArithmeticType())
  3480. return V.get()->getType();
  3481. // Test for placeholders.
  3482. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3483. if (PR.isInvalid()) return QualType();
  3484. if (PR.get() != V.get()) {
  3485. V = PR;
  3486. return CheckRealImagOperand(S, V, Loc, IsReal);
  3487. }
  3488. // Reject anything else.
  3489. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3490. << (IsReal ? "__real" : "__imag");
  3491. return QualType();
  3492. }
  3493. ExprResult
  3494. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3495. tok::TokenKind Kind, Expr *Input) {
  3496. UnaryOperatorKind Opc;
  3497. switch (Kind) {
  3498. default: llvm_unreachable("Unknown unary op!");
  3499. case tok::plusplus: Opc = UO_PostInc; break;
  3500. case tok::minusminus: Opc = UO_PostDec; break;
  3501. }
  3502. // Since this might is a postfix expression, get rid of ParenListExprs.
  3503. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3504. if (Result.isInvalid()) return ExprError();
  3505. Input = Result.get();
  3506. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3507. }
  3508. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3509. ///
  3510. /// \return true on error
  3511. static bool checkArithmeticOnObjCPointer(Sema &S,
  3512. SourceLocation opLoc,
  3513. Expr *op) {
  3514. assert(op->getType()->isObjCObjectPointerType());
  3515. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3516. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3517. return false;
  3518. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3519. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3520. << op->getSourceRange();
  3521. return true;
  3522. }
  3523. ExprResult
  3524. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3525. Expr *idx, SourceLocation rbLoc) {
  3526. // Since this might be a postfix expression, get rid of ParenListExprs.
  3527. if (isa<ParenListExpr>(base)) {
  3528. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3529. if (result.isInvalid()) return ExprError();
  3530. base = result.get();
  3531. }
  3532. // Handle any non-overload placeholder types in the base and index
  3533. // expressions. We can't handle overloads here because the other
  3534. // operand might be an overloadable type, in which case the overload
  3535. // resolution for the operator overload should get the first crack
  3536. // at the overload.
  3537. if (base->getType()->isNonOverloadPlaceholderType()) {
  3538. ExprResult result = CheckPlaceholderExpr(base);
  3539. if (result.isInvalid()) return ExprError();
  3540. base = result.get();
  3541. }
  3542. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3543. ExprResult result = CheckPlaceholderExpr(idx);
  3544. if (result.isInvalid()) return ExprError();
  3545. idx = result.get();
  3546. }
  3547. // Build an unanalyzed expression if either operand is type-dependent.
  3548. if (getLangOpts().CPlusPlus &&
  3549. (base->isTypeDependent() || idx->isTypeDependent())) {
  3550. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3551. VK_LValue, OK_Ordinary, rbLoc);
  3552. }
  3553. // Use C++ overloaded-operator rules if either operand has record
  3554. // type. The spec says to do this if either type is *overloadable*,
  3555. // but enum types can't declare subscript operators or conversion
  3556. // operators, so there's nothing interesting for overload resolution
  3557. // to do if there aren't any record types involved.
  3558. //
  3559. // ObjC pointers have their own subscripting logic that is not tied
  3560. // to overload resolution and so should not take this path.
  3561. if (getLangOpts().CPlusPlus &&
  3562. (base->getType()->isRecordType() ||
  3563. (!base->getType()->isObjCObjectPointerType() &&
  3564. idx->getType()->isRecordType()))) {
  3565. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3566. }
  3567. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3568. }
  3569. ExprResult
  3570. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3571. Expr *Idx, SourceLocation RLoc) {
  3572. Expr *LHSExp = Base;
  3573. Expr *RHSExp = Idx;
  3574. // Perform default conversions.
  3575. if (!LHSExp->getType()->getAs<VectorType>()) {
  3576. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3577. if (Result.isInvalid())
  3578. return ExprError();
  3579. LHSExp = Result.get();
  3580. }
  3581. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3582. if (Result.isInvalid())
  3583. return ExprError();
  3584. RHSExp = Result.get();
  3585. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3586. ExprValueKind VK = VK_LValue;
  3587. ExprObjectKind OK = OK_Ordinary;
  3588. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3589. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3590. // in the subscript position. As a result, we need to derive the array base
  3591. // and index from the expression types.
  3592. Expr *BaseExpr, *IndexExpr;
  3593. QualType ResultType;
  3594. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3595. BaseExpr = LHSExp;
  3596. IndexExpr = RHSExp;
  3597. ResultType = Context.DependentTy;
  3598. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3599. BaseExpr = LHSExp;
  3600. IndexExpr = RHSExp;
  3601. ResultType = PTy->getPointeeType();
  3602. } else if (const ObjCObjectPointerType *PTy =
  3603. LHSTy->getAs<ObjCObjectPointerType>()) {
  3604. BaseExpr = LHSExp;
  3605. IndexExpr = RHSExp;
  3606. // Use custom logic if this should be the pseudo-object subscript
  3607. // expression.
  3608. if (!LangOpts.isSubscriptPointerArithmetic())
  3609. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3610. nullptr);
  3611. ResultType = PTy->getPointeeType();
  3612. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3613. // Handle the uncommon case of "123[Ptr]".
  3614. BaseExpr = RHSExp;
  3615. IndexExpr = LHSExp;
  3616. ResultType = PTy->getPointeeType();
  3617. } else if (const ObjCObjectPointerType *PTy =
  3618. RHSTy->getAs<ObjCObjectPointerType>()) {
  3619. // Handle the uncommon case of "123[Ptr]".
  3620. BaseExpr = RHSExp;
  3621. IndexExpr = LHSExp;
  3622. ResultType = PTy->getPointeeType();
  3623. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3624. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3625. << ResultType << BaseExpr->getSourceRange();
  3626. return ExprError();
  3627. }
  3628. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3629. BaseExpr = LHSExp; // vectors: V[123]
  3630. IndexExpr = RHSExp;
  3631. VK = LHSExp->getValueKind();
  3632. if (VK != VK_RValue)
  3633. OK = OK_VectorComponent;
  3634. // FIXME: need to deal with const...
  3635. ResultType = VTy->getElementType();
  3636. } else if (LHSTy->isArrayType()) {
  3637. // If we see an array that wasn't promoted by
  3638. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3639. // wasn't promoted because of the C90 rule that doesn't
  3640. // allow promoting non-lvalue arrays. Warn, then
  3641. // force the promotion here.
  3642. // HLSL Change Starts - arrays won't decay
  3643. if (getLangOpts().HLSL) {
  3644. BaseExpr = LHSExp;
  3645. IndexExpr = RHSExp;
  3646. ResultType = LHSTy->getAsArrayTypeUnsafe()->getElementType();
  3647. } else {
  3648. // HLSL Change Ends
  3649. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3650. LHSExp->getSourceRange();
  3651. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3652. CK_ArrayToPointerDecay).get();
  3653. LHSTy = LHSExp->getType();
  3654. BaseExpr = LHSExp;
  3655. IndexExpr = RHSExp;
  3656. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3657. } // HLSL Change - end else block
  3658. } else if (RHSTy->isArrayType()) {
  3659. // Same as previous, except for 123[f().a] case
  3660. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3661. RHSExp->getSourceRange();
  3662. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3663. CK_ArrayToPointerDecay).get();
  3664. RHSTy = RHSExp->getType();
  3665. BaseExpr = RHSExp;
  3666. IndexExpr = LHSExp;
  3667. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3668. } else {
  3669. // HLSL Change: use HLSL variation of error message
  3670. return ExprError(Diag(LLoc, getLangOpts().HLSL ? diag::err_hlsl_typecheck_subscript_value : diag::err_typecheck_subscript_value)
  3671. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3672. }
  3673. // HLSL Change Starts
  3674. if (getLangOpts().HLSL && BaseExpr != LHSExp) {
  3675. Diag(RHSExp->getLocStart(), diag::err_hlsl_unsupported_subscript_base_rhs);
  3676. }
  3677. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent() &&
  3678. IndexExpr->getType()->isFloatingType()) {
  3679. IndexExpr = ImpCastExprToType(IndexExpr, Context.UnsignedIntTy,
  3680. CK_FloatingToIntegral).get();
  3681. }
  3682. // HLSL Change Ends
  3683. // C99 6.5.2.1p1
  3684. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3685. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3686. << IndexExpr->getSourceRange());
  3687. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3688. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3689. && !IndexExpr->isTypeDependent())
  3690. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3691. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3692. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3693. // type. Note that Functions are not objects, and that (in C99 parlance)
  3694. // incomplete types are not object types.
  3695. if (ResultType->isFunctionType()) {
  3696. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3697. << ResultType << BaseExpr->getSourceRange();
  3698. return ExprError();
  3699. }
  3700. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3701. // GNU extension: subscripting on pointer to void
  3702. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3703. << BaseExpr->getSourceRange();
  3704. // C forbids expressions of unqualified void type from being l-values.
  3705. // See IsCForbiddenLValueType.
  3706. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3707. } else if (!ResultType->isDependentType() &&
  3708. RequireCompleteType(LLoc, ResultType,
  3709. diag::err_subscript_incomplete_type, BaseExpr))
  3710. return ExprError();
  3711. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3712. !ResultType.isCForbiddenLValueType());
  3713. if (getLangOpts().HLSL) RHSExp = IndexExpr; // HLSL Change - refer to right-hands side as indexer
  3714. return new (Context)
  3715. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3716. }
  3717. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  3718. FunctionDecl *FD,
  3719. ParmVarDecl *Param) {
  3720. if (Param->hasUnparsedDefaultArg()) {
  3721. Diag(CallLoc,
  3722. diag::err_use_of_default_argument_to_function_declared_later) <<
  3723. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3724. Diag(UnparsedDefaultArgLocs[Param],
  3725. diag::note_default_argument_declared_here);
  3726. return ExprError();
  3727. }
  3728. if (Param->hasUninstantiatedDefaultArg()) {
  3729. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3730. EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
  3731. Param);
  3732. // Instantiate the expression.
  3733. MultiLevelTemplateArgumentList MutiLevelArgList
  3734. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3735. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3736. MutiLevelArgList.getInnermost());
  3737. if (Inst.isInvalid())
  3738. return ExprError();
  3739. ExprResult Result;
  3740. {
  3741. // C++ [dcl.fct.default]p5:
  3742. // The names in the [default argument] expression are bound, and
  3743. // the semantic constraints are checked, at the point where the
  3744. // default argument expression appears.
  3745. ContextRAII SavedContext(*this, FD);
  3746. LocalInstantiationScope Local(*this);
  3747. Result = SubstExpr(UninstExpr, MutiLevelArgList);
  3748. }
  3749. if (Result.isInvalid())
  3750. return ExprError();
  3751. // Check the expression as an initializer for the parameter.
  3752. InitializedEntity Entity
  3753. = InitializedEntity::InitializeParameter(Context, Param);
  3754. InitializationKind Kind
  3755. = InitializationKind::CreateCopy(Param->getLocation(),
  3756. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3757. Expr *ResultE = Result.getAs<Expr>();
  3758. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3759. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3760. if (Result.isInvalid())
  3761. return ExprError();
  3762. Expr *Arg = Result.getAs<Expr>();
  3763. CheckCompletedExpr(Arg, Param->getOuterLocStart());
  3764. // Build the default argument expression.
  3765. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
  3766. }
  3767. // If the default expression creates temporaries, we need to
  3768. // push them to the current stack of expression temporaries so they'll
  3769. // be properly destroyed.
  3770. // FIXME: We should really be rebuilding the default argument with new
  3771. // bound temporaries; see the comment in PR5810.
  3772. // We don't need to do that with block decls, though, because
  3773. // blocks in default argument expression can never capture anything.
  3774. if (isa<ExprWithCleanups>(Param->getInit())) {
  3775. // Set the "needs cleanups" bit regardless of whether there are
  3776. // any explicit objects.
  3777. ExprNeedsCleanups = true;
  3778. // Append all the objects to the cleanup list. Right now, this
  3779. // should always be a no-op, because blocks in default argument
  3780. // expressions should never be able to capture anything.
  3781. assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
  3782. "default argument expression has capturing blocks?");
  3783. }
  3784. // We already type-checked the argument, so we know it works.
  3785. // Just mark all of the declarations in this potentially-evaluated expression
  3786. // as being "referenced".
  3787. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  3788. /*SkipLocalVariables=*/true);
  3789. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  3790. }
  3791. Sema::VariadicCallType
  3792. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  3793. Expr *Fn) {
  3794. if (Proto && Proto->isVariadic()) {
  3795. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  3796. return VariadicConstructor;
  3797. else if (Fn && Fn->getType()->isBlockPointerType())
  3798. return VariadicBlock;
  3799. else if (FDecl) {
  3800. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  3801. if (Method->isInstance())
  3802. return VariadicMethod;
  3803. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  3804. return VariadicMethod;
  3805. return VariadicFunction;
  3806. }
  3807. return VariadicDoesNotApply;
  3808. }
  3809. namespace {
  3810. class FunctionCallCCC : public FunctionCallFilterCCC {
  3811. public:
  3812. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  3813. unsigned NumArgs, MemberExpr *ME)
  3814. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  3815. FunctionName(FuncName) {}
  3816. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3817. if (!candidate.getCorrectionSpecifier() ||
  3818. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  3819. return false;
  3820. }
  3821. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  3822. }
  3823. private:
  3824. const IdentifierInfo *const FunctionName;
  3825. };
  3826. }
  3827. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  3828. FunctionDecl *FDecl,
  3829. ArrayRef<Expr *> Args) {
  3830. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  3831. DeclarationName FuncName = FDecl->getDeclName();
  3832. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  3833. if (TypoCorrection Corrected = S.CorrectTypo(
  3834. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  3835. S.getScopeForContext(S.CurContext), nullptr,
  3836. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  3837. Args.size(), ME),
  3838. Sema::CTK_ErrorRecovery)) {
  3839. if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
  3840. if (Corrected.isOverloaded()) {
  3841. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  3842. OverloadCandidateSet::iterator Best;
  3843. for (TypoCorrection::decl_iterator CD = Corrected.begin(),
  3844. CDEnd = Corrected.end();
  3845. CD != CDEnd; ++CD) {
  3846. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
  3847. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  3848. OCS);
  3849. }
  3850. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  3851. case OR_Success:
  3852. ND = Best->Function;
  3853. Corrected.setCorrectionDecl(ND);
  3854. break;
  3855. default:
  3856. break;
  3857. }
  3858. }
  3859. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
  3860. return Corrected;
  3861. }
  3862. }
  3863. }
  3864. return TypoCorrection();
  3865. }
  3866. /// ConvertArgumentsForCall - Converts the arguments specified in
  3867. /// Args/NumArgs to the parameter types of the function FDecl with
  3868. /// function prototype Proto. Call is the call expression itself, and
  3869. /// Fn is the function expression. For a C++ member function, this
  3870. /// routine does not attempt to convert the object argument. Returns
  3871. /// true if the call is ill-formed.
  3872. bool
  3873. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  3874. FunctionDecl *FDecl,
  3875. const FunctionProtoType *Proto,
  3876. ArrayRef<Expr *> Args,
  3877. SourceLocation RParenLoc,
  3878. bool IsExecConfig) {
  3879. // Bail out early if calling a builtin with custom typechecking.
  3880. if (FDecl)
  3881. if (unsigned ID = FDecl->getBuiltinID())
  3882. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  3883. return false;
  3884. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  3885. // assignment, to the types of the corresponding parameter, ...
  3886. unsigned NumParams = Proto->getNumParams();
  3887. bool Invalid = false;
  3888. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  3889. unsigned FnKind = Fn->getType()->isBlockPointerType()
  3890. ? 1 /* block */
  3891. : (IsExecConfig ? 3 /* kernel function (exec config) */
  3892. : 0 /* function */);
  3893. // If too few arguments are available (and we don't have default
  3894. // arguments for the remaining parameters), don't make the call.
  3895. if (Args.size() < NumParams) {
  3896. if (Args.size() < MinArgs) {
  3897. TypoCorrection TC;
  3898. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3899. unsigned diag_id =
  3900. MinArgs == NumParams && !Proto->isVariadic()
  3901. ? diag::err_typecheck_call_too_few_args_suggest
  3902. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  3903. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  3904. << static_cast<unsigned>(Args.size())
  3905. << TC.getCorrectionRange());
  3906. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  3907. Diag(RParenLoc,
  3908. MinArgs == NumParams && !Proto->isVariadic()
  3909. ? diag::err_typecheck_call_too_few_args_one
  3910. : diag::err_typecheck_call_too_few_args_at_least_one)
  3911. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  3912. else
  3913. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  3914. ? diag::err_typecheck_call_too_few_args
  3915. : diag::err_typecheck_call_too_few_args_at_least)
  3916. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  3917. << Fn->getSourceRange();
  3918. // Emit the location of the prototype.
  3919. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3920. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3921. << FDecl;
  3922. return true;
  3923. }
  3924. Call->setNumArgs(Context, NumParams);
  3925. }
  3926. // If too many are passed and not variadic, error on the extras and drop
  3927. // them.
  3928. if (Args.size() > NumParams) {
  3929. if (!Proto->isVariadic()) {
  3930. TypoCorrection TC;
  3931. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  3932. unsigned diag_id =
  3933. MinArgs == NumParams && !Proto->isVariadic()
  3934. ? diag::err_typecheck_call_too_many_args_suggest
  3935. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  3936. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  3937. << static_cast<unsigned>(Args.size())
  3938. << TC.getCorrectionRange());
  3939. } else if (NumParams == 1 && FDecl &&
  3940. FDecl->getParamDecl(0)->getDeclName())
  3941. Diag(Args[NumParams]->getLocStart(),
  3942. MinArgs == NumParams
  3943. ? diag::err_typecheck_call_too_many_args_one
  3944. : diag::err_typecheck_call_too_many_args_at_most_one)
  3945. << FnKind << FDecl->getParamDecl(0)
  3946. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  3947. << SourceRange(Args[NumParams]->getLocStart(),
  3948. Args.back()->getLocEnd());
  3949. else
  3950. Diag(Args[NumParams]->getLocStart(),
  3951. MinArgs == NumParams
  3952. ? diag::err_typecheck_call_too_many_args
  3953. : diag::err_typecheck_call_too_many_args_at_most)
  3954. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  3955. << Fn->getSourceRange()
  3956. << SourceRange(Args[NumParams]->getLocStart(),
  3957. Args.back()->getLocEnd());
  3958. // Emit the location of the prototype.
  3959. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  3960. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  3961. << FDecl;
  3962. // This deletes the extra arguments.
  3963. Call->setNumArgs(Context, NumParams);
  3964. return true;
  3965. }
  3966. }
  3967. SmallVector<Expr *, 8> AllArgs;
  3968. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  3969. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  3970. Proto, 0, Args, AllArgs, CallType);
  3971. if (Invalid)
  3972. return true;
  3973. unsigned TotalNumArgs = AllArgs.size();
  3974. for (unsigned i = 0; i < TotalNumArgs; ++i)
  3975. Call->setArg(i, AllArgs[i]);
  3976. return false;
  3977. }
  3978. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  3979. const FunctionProtoType *Proto,
  3980. unsigned FirstParam, ArrayRef<Expr *> Args,
  3981. SmallVectorImpl<Expr *> &AllArgs,
  3982. VariadicCallType CallType, bool AllowExplicit,
  3983. bool IsListInitialization) {
  3984. unsigned NumParams = Proto->getNumParams();
  3985. bool Invalid = false;
  3986. unsigned ArgIx = 0;
  3987. // Continue to check argument types (even if we have too few/many args).
  3988. for (unsigned i = FirstParam; i < NumParams; i++) {
  3989. QualType ProtoArgType = Proto->getParamType(i);
  3990. Expr *Arg;
  3991. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  3992. if (ArgIx < Args.size()) {
  3993. Arg = Args[ArgIx++];
  3994. if (!(getLangOpts().HLSL && ProtoArgType->isIncompleteArrayType()) && // HLSL Change: allow incomplete array
  3995. RequireCompleteType(Arg->getLocStart(),
  3996. ProtoArgType,
  3997. diag::err_call_incomplete_argument, Arg))
  3998. return true;
  3999. // Strip the unbridged-cast placeholder expression off, if applicable.
  4000. bool CFAudited = false;
  4001. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4002. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4003. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4004. Arg = stripARCUnbridgedCast(Arg);
  4005. else if (getLangOpts().ObjCAutoRefCount &&
  4006. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4007. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4008. CFAudited = true;
  4009. InitializedEntity Entity =
  4010. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4011. ProtoArgType)
  4012. : InitializedEntity::InitializeParameter(
  4013. Context, ProtoArgType, Proto->isParamConsumed(i));
  4014. // Remember that parameter belongs to a CF audited API.
  4015. if (CFAudited)
  4016. Entity.setParameterCFAudited();
  4017. ExprResult ArgE = PerformCopyInitialization(
  4018. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4019. if (ArgE.isInvalid())
  4020. return true;
  4021. Arg = ArgE.getAs<Expr>();
  4022. } else {
  4023. assert(Param && "can't use default arguments without a known callee");
  4024. ExprResult ArgExpr =
  4025. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4026. if (ArgExpr.isInvalid())
  4027. return true;
  4028. Arg = ArgExpr.getAs<Expr>();
  4029. }
  4030. // Check for array bounds violations for each argument to the call. This
  4031. // check only triggers warnings when the argument isn't a more complex Expr
  4032. // with its own checking, such as a BinaryOperator.
  4033. CheckArrayAccess(Arg);
  4034. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4035. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4036. AllArgs.push_back(Arg);
  4037. }
  4038. // If this is a variadic call, handle args passed through "...".
  4039. if (CallType != VariadicDoesNotApply) {
  4040. // Assume that extern "C" functions with variadic arguments that
  4041. // return __unknown_anytype aren't *really* variadic.
  4042. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4043. FDecl->isExternC()) {
  4044. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4045. QualType paramType; // ignored
  4046. ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
  4047. Invalid |= arg.isInvalid();
  4048. AllArgs.push_back(arg.get());
  4049. }
  4050. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4051. } else {
  4052. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
  4053. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
  4054. FDecl);
  4055. Invalid |= Arg.isInvalid();
  4056. AllArgs.push_back(Arg.get());
  4057. }
  4058. }
  4059. // Check for array bounds violations.
  4060. for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
  4061. CheckArrayAccess(Args[i]);
  4062. }
  4063. return Invalid;
  4064. }
  4065. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4066. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4067. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4068. TL = DTL.getOriginalLoc();
  4069. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4070. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4071. << ATL.getLocalSourceRange();
  4072. }
  4073. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4074. /// array parameter, check that it is non-null, and that if it is formed by
  4075. /// array-to-pointer decay, the underlying array is sufficiently large.
  4076. ///
  4077. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4078. /// array type derivation, then for each call to the function, the value of the
  4079. /// corresponding actual argument shall provide access to the first element of
  4080. /// an array with at least as many elements as specified by the size expression.
  4081. void
  4082. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4083. ParmVarDecl *Param,
  4084. const Expr *ArgExpr) {
  4085. // Static array parameters are not supported in C++.
  4086. if (!Param || getLangOpts().CPlusPlus)
  4087. return;
  4088. QualType OrigTy = Param->getOriginalType();
  4089. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4090. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4091. return;
  4092. if (ArgExpr->isNullPointerConstant(Context,
  4093. Expr::NPC_NeverValueDependent)) {
  4094. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4095. DiagnoseCalleeStaticArrayParam(*this, Param);
  4096. return;
  4097. }
  4098. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4099. if (!CAT)
  4100. return;
  4101. const ConstantArrayType *ArgCAT =
  4102. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4103. if (!ArgCAT)
  4104. return;
  4105. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4106. Diag(CallLoc, diag::warn_static_array_too_small)
  4107. << ArgExpr->getSourceRange()
  4108. << (unsigned) ArgCAT->getSize().getZExtValue()
  4109. << (unsigned) CAT->getSize().getZExtValue();
  4110. DiagnoseCalleeStaticArrayParam(*this, Param);
  4111. }
  4112. }
  4113. /// Given a function expression of unknown-any type, try to rebuild it
  4114. /// to have a function type.
  4115. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4116. /// Is the given type a placeholder that we need to lower out
  4117. /// immediately during argument processing?
  4118. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4119. // Placeholders are never sugared.
  4120. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4121. if (!placeholder) return false;
  4122. switch (placeholder->getKind()) {
  4123. // Ignore all the non-placeholder types.
  4124. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4125. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4126. #include "clang/AST/BuiltinTypes.def"
  4127. return false;
  4128. // We cannot lower out overload sets; they might validly be resolved
  4129. // by the call machinery.
  4130. case BuiltinType::Overload:
  4131. return false;
  4132. // Unbridged casts in ARC can be handled in some call positions and
  4133. // should be left in place.
  4134. case BuiltinType::ARCUnbridgedCast:
  4135. return false;
  4136. // Pseudo-objects should be converted as soon as possible.
  4137. case BuiltinType::PseudoObject:
  4138. return true;
  4139. // The debugger mode could theoretically but currently does not try
  4140. // to resolve unknown-typed arguments based on known parameter types.
  4141. case BuiltinType::UnknownAny:
  4142. return true;
  4143. // These are always invalid as call arguments and should be reported.
  4144. case BuiltinType::BoundMember:
  4145. case BuiltinType::BuiltinFn:
  4146. return true;
  4147. }
  4148. llvm_unreachable("bad builtin type kind");
  4149. }
  4150. /// Check an argument list for placeholders that we won't try to
  4151. /// handle later.
  4152. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4153. // Apply this processing to all the arguments at once instead of
  4154. // dying at the first failure.
  4155. bool hasInvalid = false;
  4156. for (size_t i = 0, e = args.size(); i != e; i++) {
  4157. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4158. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4159. if (result.isInvalid()) hasInvalid = true;
  4160. else args[i] = result.get();
  4161. } else if (hasInvalid) {
  4162. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4163. }
  4164. }
  4165. return hasInvalid;
  4166. }
  4167. /// If a builtin function has a pointer argument with no explicit address
  4168. /// space, than it should be able to accept a pointer to any address
  4169. /// space as input. In order to do this, we need to replace the
  4170. /// standard builtin declaration with one that uses the same address space
  4171. /// as the call.
  4172. ///
  4173. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4174. /// it does not contain any pointer arguments without
  4175. /// an address space qualifer. Otherwise the rewritten
  4176. /// FunctionDecl is returned.
  4177. /// TODO: Handle pointer return types.
  4178. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4179. const FunctionDecl *FDecl,
  4180. MultiExprArg ArgExprs) {
  4181. QualType DeclType = FDecl->getType();
  4182. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4183. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4184. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4185. return nullptr;
  4186. bool NeedsNewDecl = false;
  4187. unsigned i = 0;
  4188. SmallVector<QualType, 8> OverloadParams;
  4189. for (QualType ParamType : FT->param_types()) {
  4190. // Convert array arguments to pointer to simplify type lookup.
  4191. Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
  4192. QualType ArgType = Arg->getType();
  4193. if (!ParamType->isPointerType() ||
  4194. ParamType.getQualifiers().hasAddressSpace() ||
  4195. !ArgType->isPointerType() ||
  4196. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4197. OverloadParams.push_back(ParamType);
  4198. continue;
  4199. }
  4200. NeedsNewDecl = true;
  4201. unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
  4202. QualType PointeeType = ParamType->getPointeeType();
  4203. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4204. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4205. }
  4206. if (!NeedsNewDecl)
  4207. return nullptr;
  4208. FunctionProtoType::ExtProtoInfo EPI;
  4209. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4210. OverloadParams, EPI,
  4211. FT->getParamMods()); // HLSL Change
  4212. DeclContext *Parent = Context.getTranslationUnitDecl();
  4213. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4214. FDecl->getLocation(),
  4215. FDecl->getLocation(),
  4216. FDecl->getIdentifier(),
  4217. OverloadTy,
  4218. /*TInfo=*/nullptr,
  4219. SC_Extern, false,
  4220. /*hasPrototype=*/true);
  4221. SmallVector<ParmVarDecl*, 16> Params;
  4222. FT = cast<FunctionProtoType>(OverloadTy);
  4223. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4224. QualType ParamType = FT->getParamType(i);
  4225. ParmVarDecl *Parm =
  4226. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4227. SourceLocation(), nullptr, ParamType,
  4228. /*TInfo=*/nullptr, SC_None, nullptr);
  4229. Parm->setScopeInfo(0, i);
  4230. Params.push_back(Parm);
  4231. }
  4232. OverloadDecl->setParams(Params);
  4233. return OverloadDecl;
  4234. }
  4235. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4236. /// This provides the location of the left/right parens and a list of comma
  4237. /// locations.
  4238. ExprResult
  4239. Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
  4240. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4241. Expr *ExecConfig, bool IsExecConfig) {
  4242. // Since this might be a postfix expression, get rid of ParenListExprs.
  4243. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
  4244. if (Result.isInvalid()) return ExprError();
  4245. Fn = Result.get();
  4246. if (checkArgsForPlaceholders(*this, ArgExprs))
  4247. return ExprError();
  4248. if (getLangOpts().CPlusPlus) {
  4249. // If this is a pseudo-destructor expression, build the call immediately.
  4250. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4251. if (!ArgExprs.empty()) {
  4252. // Pseudo-destructor calls should not have any arguments.
  4253. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4254. << FixItHint::CreateRemoval(
  4255. SourceRange(ArgExprs[0]->getLocStart(),
  4256. ArgExprs.back()->getLocEnd()));
  4257. }
  4258. return new (Context)
  4259. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4260. }
  4261. if (Fn->getType() == Context.PseudoObjectTy) {
  4262. ExprResult result = CheckPlaceholderExpr(Fn);
  4263. if (result.isInvalid()) return ExprError();
  4264. Fn = result.get();
  4265. }
  4266. // Determine whether this is a dependent call inside a C++ template,
  4267. // in which case we won't do any semantic analysis now.
  4268. // FIXME: Will need to cache the results of name lookup (including ADL) in
  4269. // Fn.
  4270. bool Dependent = false;
  4271. if (Fn->isTypeDependent())
  4272. Dependent = true;
  4273. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4274. Dependent = true;
  4275. if (Dependent) {
  4276. if (ExecConfig) {
  4277. return new (Context) CUDAKernelCallExpr(
  4278. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4279. Context.DependentTy, VK_RValue, RParenLoc);
  4280. } else {
  4281. return new (Context) CallExpr(
  4282. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4283. }
  4284. }
  4285. // Determine whether this is a call to an object (C++ [over.call.object]).
  4286. if (Fn->getType()->isRecordType())
  4287. return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
  4288. RParenLoc);
  4289. if (Fn->getType() == Context.UnknownAnyTy) {
  4290. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4291. if (result.isInvalid()) return ExprError();
  4292. Fn = result.get();
  4293. }
  4294. if (Fn->getType() == Context.BoundMemberTy) {
  4295. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
  4296. }
  4297. }
  4298. // Check for overloaded calls. This can happen even in C due to extensions.
  4299. if (Fn->getType() == Context.OverloadTy) {
  4300. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4301. // We aren't supposed to apply this logic for if there's an '&' involved.
  4302. if (!find.HasFormOfMemberPointer) {
  4303. OverloadExpr *ovl = find.Expression;
  4304. if (isa<UnresolvedLookupExpr>(ovl)) {
  4305. UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
  4306. return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
  4307. RParenLoc, ExecConfig);
  4308. } else {
  4309. return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
  4310. RParenLoc);
  4311. }
  4312. }
  4313. }
  4314. // If we're directly calling a function, get the appropriate declaration.
  4315. if (Fn->getType() == Context.UnknownAnyTy) {
  4316. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4317. if (result.isInvalid()) return ExprError();
  4318. Fn = result.get();
  4319. }
  4320. Expr *NakedFn = Fn->IgnoreParens();
  4321. NamedDecl *NDecl = nullptr;
  4322. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
  4323. if (UnOp->getOpcode() == UO_AddrOf)
  4324. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4325. if (isa<DeclRefExpr>(NakedFn)) {
  4326. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4327. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4328. if (FDecl && FDecl->getBuiltinID()) {
  4329. // Rewrite the function decl for this builtin by replacing paramaters
  4330. // with no explicit address space with the address space of the arguments
  4331. // in ArgExprs.
  4332. if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4333. NDecl = FDecl;
  4334. Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
  4335. SourceLocation(), FDecl, false,
  4336. SourceLocation(), FDecl->getType(),
  4337. Fn->getValueKind(), FDecl);
  4338. }
  4339. }
  4340. } else if (isa<MemberExpr>(NakedFn))
  4341. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4342. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4343. if (FD->hasAttr<EnableIfAttr>()) {
  4344. if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
  4345. Diag(Fn->getLocStart(),
  4346. isa<CXXMethodDecl>(FD) ?
  4347. diag::err_ovl_no_viable_member_function_in_call :
  4348. diag::err_ovl_no_viable_function_in_call)
  4349. << FD << FD->getSourceRange();
  4350. Diag(FD->getLocation(),
  4351. diag::note_ovl_candidate_disabled_by_enable_if_attr)
  4352. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4353. }
  4354. }
  4355. }
  4356. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4357. ExecConfig, IsExecConfig);
  4358. }
  4359. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4360. ///
  4361. /// __builtin_astype( value, dst type )
  4362. ///
  4363. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4364. SourceLocation BuiltinLoc,
  4365. SourceLocation RParenLoc) {
  4366. ExprValueKind VK = VK_RValue;
  4367. ExprObjectKind OK = OK_Ordinary;
  4368. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4369. QualType SrcTy = E->getType();
  4370. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4371. return ExprError(Diag(BuiltinLoc,
  4372. diag::err_invalid_astype_of_different_size)
  4373. << DstTy
  4374. << SrcTy
  4375. << E->getSourceRange());
  4376. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4377. }
  4378. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4379. /// provided arguments.
  4380. ///
  4381. /// __builtin_convertvector( value, dst type )
  4382. ///
  4383. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4384. SourceLocation BuiltinLoc,
  4385. SourceLocation RParenLoc) {
  4386. TypeSourceInfo *TInfo;
  4387. GetTypeFromParser(ParsedDestTy, &TInfo);
  4388. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4389. }
  4390. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4391. /// i.e. an expression not of \p OverloadTy. The expression should
  4392. /// unary-convert to an expression of function-pointer or
  4393. /// block-pointer type.
  4394. ///
  4395. /// \param NDecl the declaration being called, if available
  4396. ExprResult
  4397. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4398. SourceLocation LParenLoc,
  4399. ArrayRef<Expr *> Args,
  4400. SourceLocation RParenLoc,
  4401. Expr *Config, bool IsExecConfig) {
  4402. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4403. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4404. // Promote the function operand.
  4405. // We special-case function promotion here because we only allow promoting
  4406. // builtin functions to function pointers in the callee of a call.
  4407. ExprResult Result;
  4408. if (BuiltinID &&
  4409. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4410. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4411. CK_BuiltinFnToFnPtr).get();
  4412. } else {
  4413. Result = CallExprUnaryConversions(Fn);
  4414. }
  4415. if (Result.isInvalid())
  4416. return ExprError();
  4417. Fn = Result.get();
  4418. // Make the call expr early, before semantic checks. This guarantees cleanup
  4419. // of arguments and function on error.
  4420. CallExpr *TheCall;
  4421. if (Config)
  4422. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4423. cast<CallExpr>(Config), Args,
  4424. Context.BoolTy, VK_RValue,
  4425. RParenLoc);
  4426. else
  4427. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4428. VK_RValue, RParenLoc);
  4429. if (!getLangOpts().CPlusPlus) {
  4430. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4431. // function calls as their argument checking don't necessarily handle
  4432. // dependent types properly, so make sure any TypoExprs have been
  4433. // dealt with.
  4434. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4435. if (!Result.isUsable()) return ExprError();
  4436. TheCall = dyn_cast<CallExpr>(Result.get());
  4437. if (!TheCall) return Result;
  4438. Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs());
  4439. }
  4440. // Bail out early if calling a builtin with custom typechecking.
  4441. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4442. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4443. retry:
  4444. const FunctionType *FuncT;
  4445. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4446. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4447. // have type pointer to function".
  4448. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4449. if (!FuncT)
  4450. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4451. << Fn->getType() << Fn->getSourceRange());
  4452. } else if (const BlockPointerType *BPT =
  4453. Fn->getType()->getAs<BlockPointerType>()) {
  4454. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4455. } else {
  4456. // Handle calls to expressions of unknown-any type.
  4457. if (Fn->getType() == Context.UnknownAnyTy) {
  4458. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4459. if (rewrite.isInvalid()) return ExprError();
  4460. Fn = rewrite.get();
  4461. TheCall->setCallee(Fn);
  4462. goto retry;
  4463. }
  4464. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4465. << Fn->getType() << Fn->getSourceRange());
  4466. }
  4467. if (getLangOpts().CUDA) {
  4468. if (Config) {
  4469. // CUDA: Kernel calls must be to global functions
  4470. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4471. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4472. << FDecl->getName() << Fn->getSourceRange());
  4473. // CUDA: Kernel function must have 'void' return type
  4474. if (!FuncT->getReturnType()->isVoidType())
  4475. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4476. << Fn->getType() << Fn->getSourceRange());
  4477. } else {
  4478. // CUDA: Calls to global functions must be configured
  4479. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4480. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4481. << FDecl->getName() << Fn->getSourceRange());
  4482. }
  4483. }
  4484. // Check for a valid return type
  4485. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4486. FDecl))
  4487. return ExprError();
  4488. // We know the result type of the call, set it.
  4489. TheCall->setType(FuncT->getCallResultType(Context));
  4490. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4491. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4492. if (Proto) {
  4493. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4494. IsExecConfig))
  4495. return ExprError();
  4496. } else {
  4497. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4498. if (FDecl) {
  4499. // Check if we have too few/too many template arguments, based
  4500. // on our knowledge of the function definition.
  4501. const FunctionDecl *Def = nullptr;
  4502. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4503. Proto = Def->getType()->getAs<FunctionProtoType>();
  4504. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4505. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4506. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4507. }
  4508. // If the function we're calling isn't a function prototype, but we have
  4509. // a function prototype from a prior declaratiom, use that prototype.
  4510. if (!FDecl->hasPrototype())
  4511. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4512. }
  4513. // Promote the arguments (C99 6.5.2.2p6).
  4514. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4515. Expr *Arg = Args[i];
  4516. if (Proto && i < Proto->getNumParams()) {
  4517. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4518. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4519. ExprResult ArgE =
  4520. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4521. if (ArgE.isInvalid())
  4522. return true;
  4523. Arg = ArgE.getAs<Expr>();
  4524. } else {
  4525. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4526. if (ArgE.isInvalid())
  4527. return true;
  4528. Arg = ArgE.getAs<Expr>();
  4529. }
  4530. if (RequireCompleteType(Arg->getLocStart(),
  4531. Arg->getType(),
  4532. diag::err_call_incomplete_argument, Arg))
  4533. return ExprError();
  4534. TheCall->setArg(i, Arg);
  4535. }
  4536. }
  4537. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4538. if (!Method->isStatic())
  4539. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4540. << Fn->getSourceRange());
  4541. // Check for sentinels
  4542. if (NDecl)
  4543. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4544. // Do special checking on direct calls to functions.
  4545. if (FDecl) {
  4546. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4547. return ExprError();
  4548. if (BuiltinID)
  4549. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4550. } else if (NDecl) {
  4551. if (CheckPointerCall(NDecl, TheCall, Proto))
  4552. return ExprError();
  4553. } else {
  4554. if (CheckOtherCall(TheCall, Proto))
  4555. return ExprError();
  4556. }
  4557. return MaybeBindToTemporary(TheCall);
  4558. }
  4559. ExprResult
  4560. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4561. SourceLocation RParenLoc, Expr *InitExpr) {
  4562. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4563. // FIXME: put back this assert when initializers are worked out.
  4564. //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
  4565. TypeSourceInfo *TInfo;
  4566. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4567. if (!TInfo)
  4568. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4569. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4570. }
  4571. ExprResult
  4572. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4573. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4574. QualType literalType = TInfo->getType();
  4575. if (literalType->isArrayType()) {
  4576. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4577. diag::err_illegal_decl_array_incomplete_type,
  4578. SourceRange(LParenLoc,
  4579. LiteralExpr->getSourceRange().getEnd())))
  4580. return ExprError();
  4581. if (literalType->isVariableArrayType())
  4582. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4583. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4584. } else if (!literalType->isDependentType() &&
  4585. RequireCompleteType(LParenLoc, literalType,
  4586. diag::err_typecheck_decl_incomplete_type,
  4587. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4588. return ExprError();
  4589. InitializedEntity Entity
  4590. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4591. InitializationKind Kind
  4592. = InitializationKind::CreateCStyleCast(LParenLoc,
  4593. SourceRange(LParenLoc, RParenLoc),
  4594. /*InitList=*/true);
  4595. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4596. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4597. &literalType);
  4598. if (Result.isInvalid())
  4599. return ExprError();
  4600. LiteralExpr = Result.get();
  4601. bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
  4602. if (isFileScope &&
  4603. !LiteralExpr->isTypeDependent() &&
  4604. !LiteralExpr->isValueDependent() &&
  4605. !literalType->isDependentType()) { // 6.5.2.5p3
  4606. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4607. return ExprError();
  4608. }
  4609. // In C, compound literals are l-values for some reason.
  4610. ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
  4611. return MaybeBindToTemporary(
  4612. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4613. VK, LiteralExpr, isFileScope));
  4614. }
  4615. ExprResult
  4616. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4617. SourceLocation RBraceLoc) {
  4618. // Immediately handle non-overload placeholders. Overloads can be
  4619. // resolved contextually, but everything else here can't.
  4620. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4621. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4622. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  4623. // Ignore failures; dropping the entire initializer list because
  4624. // of one failure would be terrible for indexing/etc.
  4625. if (result.isInvalid()) continue;
  4626. InitArgList[I] = result.get();
  4627. }
  4628. }
  4629. // Semantic analysis for initializers is done by ActOnDeclarator() and
  4630. // CheckInitializer() - it requires knowledge of the object being intialized.
  4631. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  4632. RBraceLoc);
  4633. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  4634. return E;
  4635. }
  4636. /// Do an explicit extend of the given block pointer if we're in ARC.
  4637. void Sema::maybeExtendBlockObject(ExprResult &E) {
  4638. assert(E.get()->getType()->isBlockPointerType());
  4639. assert(E.get()->isRValue());
  4640. // Only do this in an r-value context.
  4641. if (!getLangOpts().ObjCAutoRefCount) return;
  4642. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  4643. CK_ARCExtendBlockObject, E.get(),
  4644. /*base path*/ nullptr, VK_RValue);
  4645. ExprNeedsCleanups = true;
  4646. }
  4647. /// Prepare a conversion of the given expression to an ObjC object
  4648. /// pointer type.
  4649. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  4650. QualType type = E.get()->getType();
  4651. if (type->isObjCObjectPointerType()) {
  4652. return CK_BitCast;
  4653. } else if (type->isBlockPointerType()) {
  4654. maybeExtendBlockObject(E);
  4655. return CK_BlockPointerToObjCPointerCast;
  4656. } else {
  4657. assert(type->isPointerType());
  4658. return CK_CPointerToObjCPointerCast;
  4659. }
  4660. }
  4661. /// Prepares for a scalar cast, performing all the necessary stages
  4662. /// except the final cast and returning the kind required.
  4663. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  4664. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  4665. // Also, callers should have filtered out the invalid cases with
  4666. // pointers. Everything else should be possible.
  4667. QualType SrcTy = Src.get()->getType();
  4668. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  4669. return CK_NoOp;
  4670. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  4671. case Type::STK_MemberPointer:
  4672. llvm_unreachable("member pointer type in C");
  4673. case Type::STK_CPointer:
  4674. case Type::STK_BlockPointer:
  4675. case Type::STK_ObjCObjectPointer:
  4676. switch (DestTy->getScalarTypeKind()) {
  4677. case Type::STK_CPointer: {
  4678. unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
  4679. unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
  4680. if (SrcAS != DestAS)
  4681. return CK_AddressSpaceConversion;
  4682. return CK_BitCast;
  4683. }
  4684. case Type::STK_BlockPointer:
  4685. return (SrcKind == Type::STK_BlockPointer
  4686. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  4687. case Type::STK_ObjCObjectPointer:
  4688. if (SrcKind == Type::STK_ObjCObjectPointer)
  4689. return CK_BitCast;
  4690. if (SrcKind == Type::STK_CPointer)
  4691. return CK_CPointerToObjCPointerCast;
  4692. maybeExtendBlockObject(Src);
  4693. return CK_BlockPointerToObjCPointerCast;
  4694. case Type::STK_Bool:
  4695. return CK_PointerToBoolean;
  4696. case Type::STK_Integral:
  4697. return CK_PointerToIntegral;
  4698. case Type::STK_Floating:
  4699. case Type::STK_FloatingComplex:
  4700. case Type::STK_IntegralComplex:
  4701. case Type::STK_MemberPointer:
  4702. llvm_unreachable("illegal cast from pointer");
  4703. }
  4704. llvm_unreachable("Should have returned before this");
  4705. case Type::STK_Bool: // casting from bool is like casting from an integer
  4706. case Type::STK_Integral:
  4707. switch (DestTy->getScalarTypeKind()) {
  4708. case Type::STK_CPointer:
  4709. case Type::STK_ObjCObjectPointer:
  4710. case Type::STK_BlockPointer:
  4711. if (Src.get()->isNullPointerConstant(Context,
  4712. Expr::NPC_ValueDependentIsNull))
  4713. return CK_NullToPointer;
  4714. return CK_IntegralToPointer;
  4715. case Type::STK_Bool:
  4716. return CK_IntegralToBoolean;
  4717. case Type::STK_Integral:
  4718. return CK_IntegralCast;
  4719. case Type::STK_Floating:
  4720. return CK_IntegralToFloating;
  4721. case Type::STK_IntegralComplex:
  4722. Src = ImpCastExprToType(Src.get(),
  4723. DestTy->castAs<ComplexType>()->getElementType(),
  4724. CK_IntegralCast);
  4725. return CK_IntegralRealToComplex;
  4726. case Type::STK_FloatingComplex:
  4727. Src = ImpCastExprToType(Src.get(),
  4728. DestTy->castAs<ComplexType>()->getElementType(),
  4729. CK_IntegralToFloating);
  4730. return CK_FloatingRealToComplex;
  4731. case Type::STK_MemberPointer:
  4732. llvm_unreachable("member pointer type in C");
  4733. }
  4734. llvm_unreachable("Should have returned before this");
  4735. case Type::STK_Floating:
  4736. switch (DestTy->getScalarTypeKind()) {
  4737. case Type::STK_Floating:
  4738. return CK_FloatingCast;
  4739. case Type::STK_Bool:
  4740. return CK_FloatingToBoolean;
  4741. case Type::STK_Integral:
  4742. return CK_FloatingToIntegral;
  4743. case Type::STK_FloatingComplex:
  4744. Src = ImpCastExprToType(Src.get(),
  4745. DestTy->castAs<ComplexType>()->getElementType(),
  4746. CK_FloatingCast);
  4747. return CK_FloatingRealToComplex;
  4748. case Type::STK_IntegralComplex:
  4749. Src = ImpCastExprToType(Src.get(),
  4750. DestTy->castAs<ComplexType>()->getElementType(),
  4751. CK_FloatingToIntegral);
  4752. return CK_IntegralRealToComplex;
  4753. case Type::STK_CPointer:
  4754. case Type::STK_ObjCObjectPointer:
  4755. case Type::STK_BlockPointer:
  4756. llvm_unreachable("valid float->pointer cast?");
  4757. case Type::STK_MemberPointer:
  4758. llvm_unreachable("member pointer type in C");
  4759. }
  4760. llvm_unreachable("Should have returned before this");
  4761. case Type::STK_FloatingComplex:
  4762. switch (DestTy->getScalarTypeKind()) {
  4763. case Type::STK_FloatingComplex:
  4764. return CK_FloatingComplexCast;
  4765. case Type::STK_IntegralComplex:
  4766. return CK_FloatingComplexToIntegralComplex;
  4767. case Type::STK_Floating: {
  4768. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4769. if (Context.hasSameType(ET, DestTy))
  4770. return CK_FloatingComplexToReal;
  4771. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  4772. return CK_FloatingCast;
  4773. }
  4774. case Type::STK_Bool:
  4775. return CK_FloatingComplexToBoolean;
  4776. case Type::STK_Integral:
  4777. Src = ImpCastExprToType(Src.get(),
  4778. SrcTy->castAs<ComplexType>()->getElementType(),
  4779. CK_FloatingComplexToReal);
  4780. return CK_FloatingToIntegral;
  4781. case Type::STK_CPointer:
  4782. case Type::STK_ObjCObjectPointer:
  4783. case Type::STK_BlockPointer:
  4784. llvm_unreachable("valid complex float->pointer cast?");
  4785. case Type::STK_MemberPointer:
  4786. llvm_unreachable("member pointer type in C");
  4787. }
  4788. llvm_unreachable("Should have returned before this");
  4789. case Type::STK_IntegralComplex:
  4790. switch (DestTy->getScalarTypeKind()) {
  4791. case Type::STK_FloatingComplex:
  4792. return CK_IntegralComplexToFloatingComplex;
  4793. case Type::STK_IntegralComplex:
  4794. return CK_IntegralComplexCast;
  4795. case Type::STK_Integral: {
  4796. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  4797. if (Context.hasSameType(ET, DestTy))
  4798. return CK_IntegralComplexToReal;
  4799. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  4800. return CK_IntegralCast;
  4801. }
  4802. case Type::STK_Bool:
  4803. return CK_IntegralComplexToBoolean;
  4804. case Type::STK_Floating:
  4805. Src = ImpCastExprToType(Src.get(),
  4806. SrcTy->castAs<ComplexType>()->getElementType(),
  4807. CK_IntegralComplexToReal);
  4808. return CK_IntegralToFloating;
  4809. case Type::STK_CPointer:
  4810. case Type::STK_ObjCObjectPointer:
  4811. case Type::STK_BlockPointer:
  4812. llvm_unreachable("valid complex int->pointer cast?");
  4813. case Type::STK_MemberPointer:
  4814. llvm_unreachable("member pointer type in C");
  4815. }
  4816. llvm_unreachable("Should have returned before this");
  4817. }
  4818. llvm_unreachable("Unhandled scalar cast");
  4819. }
  4820. static bool breakDownVectorType(QualType type, uint64_t &len,
  4821. QualType &eltType) {
  4822. // Vectors are simple.
  4823. if (const VectorType *vecType = type->getAs<VectorType>()) {
  4824. len = vecType->getNumElements();
  4825. eltType = vecType->getElementType();
  4826. assert(eltType->isScalarType());
  4827. return true;
  4828. }
  4829. // We allow lax conversion to and from non-vector types, but only if
  4830. // they're real types (i.e. non-complex, non-pointer scalar types).
  4831. if (!type->isRealType()) return false;
  4832. len = 1;
  4833. eltType = type;
  4834. return true;
  4835. }
  4836. static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
  4837. uint64_t srcLen, destLen;
  4838. QualType srcElt, destElt;
  4839. if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
  4840. if (!breakDownVectorType(destTy, destLen, destElt)) return false;
  4841. // ASTContext::getTypeSize will return the size rounded up to a
  4842. // power of 2, so instead of using that, we need to use the raw
  4843. // element size multiplied by the element count.
  4844. uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
  4845. uint64_t destEltSize = S.Context.getTypeSize(destElt);
  4846. return (srcLen * srcEltSize == destLen * destEltSize);
  4847. }
  4848. /// Is this a legal conversion between two known vector types?
  4849. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  4850. assert(destTy->isVectorType() || srcTy->isVectorType());
  4851. if (!Context.getLangOpts().LaxVectorConversions)
  4852. return false;
  4853. return VectorTypesMatch(*this, srcTy, destTy);
  4854. }
  4855. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  4856. CastKind &Kind) {
  4857. assert(VectorTy->isVectorType() && "Not a vector type!");
  4858. if (Ty->isVectorType() || Ty->isIntegerType()) {
  4859. if (!VectorTypesMatch(*this, Ty, VectorTy))
  4860. return Diag(R.getBegin(),
  4861. Ty->isVectorType() ?
  4862. diag::err_invalid_conversion_between_vectors :
  4863. diag::err_invalid_conversion_between_vector_and_integer)
  4864. << VectorTy << Ty << R;
  4865. } else
  4866. return Diag(R.getBegin(),
  4867. diag::err_invalid_conversion_between_vector_and_scalar)
  4868. << VectorTy << Ty << R;
  4869. Kind = CK_BitCast;
  4870. return false;
  4871. }
  4872. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  4873. Expr *CastExpr, CastKind &Kind) {
  4874. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  4875. QualType SrcTy = CastExpr->getType();
  4876. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  4877. // an ExtVectorType.
  4878. // In OpenCL, casts between vectors of different types are not allowed.
  4879. // (See OpenCL 6.2).
  4880. if (SrcTy->isVectorType()) {
  4881. if (!VectorTypesMatch(*this, SrcTy, DestTy)
  4882. || (getLangOpts().OpenCL &&
  4883. (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
  4884. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  4885. << DestTy << SrcTy << R;
  4886. return ExprError();
  4887. }
  4888. Kind = CK_BitCast;
  4889. return CastExpr;
  4890. }
  4891. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  4892. // conversion will take place first from scalar to elt type, and then
  4893. // splat from elt type to vector.
  4894. if (SrcTy->isPointerType())
  4895. return Diag(R.getBegin(),
  4896. diag::err_invalid_conversion_between_vector_and_scalar)
  4897. << DestTy << SrcTy << R;
  4898. QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
  4899. ExprResult CastExprRes = CastExpr;
  4900. CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
  4901. if (CastExprRes.isInvalid())
  4902. return ExprError();
  4903. CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
  4904. Kind = CK_VectorSplat;
  4905. return CastExpr;
  4906. }
  4907. ExprResult
  4908. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  4909. Declarator &D, ParsedType &Ty,
  4910. SourceLocation RParenLoc, Expr *CastExpr) {
  4911. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  4912. "ActOnCastExpr(): missing type or expr");
  4913. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  4914. if (D.isInvalidType())
  4915. return ExprError();
  4916. if (getLangOpts().CPlusPlus) {
  4917. // Check that there are no default arguments (C++ only).
  4918. CheckExtraCXXDefaultArguments(D);
  4919. } else {
  4920. // Make sure any TypoExprs have been dealt with.
  4921. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  4922. if (!Res.isUsable())
  4923. return ExprError();
  4924. CastExpr = Res.get();
  4925. }
  4926. checkUnusedDeclAttributes(D);
  4927. QualType castType = castTInfo->getType();
  4928. Ty = CreateParsedType(castType, castTInfo);
  4929. bool isVectorLiteral = false;
  4930. // Check for an altivec or OpenCL literal,
  4931. // i.e. all the elements are integer constants.
  4932. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  4933. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  4934. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  4935. && castType->isVectorType() && (PE || PLE)) {
  4936. if (PLE && PLE->getNumExprs() == 0) {
  4937. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  4938. return ExprError();
  4939. }
  4940. if (PE || PLE->getNumExprs() == 1) {
  4941. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  4942. if (!E->getType()->isVectorType())
  4943. isVectorLiteral = true;
  4944. }
  4945. else
  4946. isVectorLiteral = true;
  4947. }
  4948. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  4949. // then handle it as such.
  4950. if (isVectorLiteral)
  4951. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  4952. // If the Expr being casted is a ParenListExpr, handle it specially.
  4953. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  4954. // sequence of BinOp comma operators.
  4955. if (isa<ParenListExpr>(CastExpr)) {
  4956. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  4957. if (Result.isInvalid()) return ExprError();
  4958. CastExpr = Result.get();
  4959. }
  4960. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  4961. !getSourceManager().isInSystemMacro(LParenLoc))
  4962. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  4963. #if 0 // HLSL Change - no support for ObjC constructs
  4964. CheckTollFreeBridgeCast(castType, CastExpr);
  4965. CheckObjCBridgeRelatedCast(castType, CastExpr);
  4966. #endif // HLSL Change
  4967. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  4968. }
  4969. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  4970. SourceLocation RParenLoc, Expr *E,
  4971. TypeSourceInfo *TInfo) {
  4972. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  4973. "Expected paren or paren list expression");
  4974. Expr **exprs;
  4975. unsigned numExprs;
  4976. Expr *subExpr;
  4977. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  4978. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  4979. LiteralLParenLoc = PE->getLParenLoc();
  4980. LiteralRParenLoc = PE->getRParenLoc();
  4981. exprs = PE->getExprs();
  4982. numExprs = PE->getNumExprs();
  4983. } else { // isa<ParenExpr> by assertion at function entrance
  4984. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  4985. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  4986. subExpr = cast<ParenExpr>(E)->getSubExpr();
  4987. exprs = &subExpr;
  4988. numExprs = 1;
  4989. }
  4990. QualType Ty = TInfo->getType();
  4991. assert(Ty->isVectorType() && "Expected vector type");
  4992. SmallVector<Expr *, 8> initExprs;
  4993. const VectorType *VTy = Ty->getAs<VectorType>();
  4994. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  4995. // '(...)' form of vector initialization in AltiVec: the number of
  4996. // initializers must be one or must match the size of the vector.
  4997. // If a single value is specified in the initializer then it will be
  4998. // replicated to all the components of the vector
  4999. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5000. // The number of initializers must be one or must match the size of the
  5001. // vector. If a single value is specified in the initializer then it will
  5002. // be replicated to all the components of the vector
  5003. if (numExprs == 1) {
  5004. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5005. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5006. if (Literal.isInvalid())
  5007. return ExprError();
  5008. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5009. PrepareScalarCast(Literal, ElemTy));
  5010. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5011. }
  5012. else if (numExprs < numElems) {
  5013. Diag(E->getExprLoc(),
  5014. diag::err_incorrect_number_of_vector_initializers);
  5015. return ExprError();
  5016. }
  5017. else
  5018. initExprs.append(exprs, exprs + numExprs);
  5019. }
  5020. else {
  5021. // For OpenCL, when the number of initializers is a single value,
  5022. // it will be replicated to all components of the vector.
  5023. if (getLangOpts().OpenCL &&
  5024. VTy->getVectorKind() == VectorType::GenericVector &&
  5025. numExprs == 1) {
  5026. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5027. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5028. if (Literal.isInvalid())
  5029. return ExprError();
  5030. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5031. PrepareScalarCast(Literal, ElemTy));
  5032. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5033. }
  5034. initExprs.append(exprs, exprs + numExprs);
  5035. }
  5036. // FIXME: This means that pretty-printing the final AST will produce curly
  5037. // braces instead of the original commas.
  5038. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5039. initExprs, LiteralRParenLoc);
  5040. initE->setType(Ty);
  5041. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5042. }
  5043. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5044. /// the ParenListExpr into a sequence of comma binary operators.
  5045. ExprResult
  5046. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5047. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5048. if (!E)
  5049. return OrigExpr;
  5050. ExprResult Result(E->getExpr(0));
  5051. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5052. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5053. E->getExpr(i));
  5054. if (Result.isInvalid()) return ExprError();
  5055. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5056. }
  5057. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5058. SourceLocation R,
  5059. MultiExprArg Val) {
  5060. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5061. return expr;
  5062. }
  5063. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  5064. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5065. /// emitted.
  5066. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5067. SourceLocation QuestionLoc) {
  5068. Expr *NullExpr = LHSExpr;
  5069. Expr *NonPointerExpr = RHSExpr;
  5070. Expr::NullPointerConstantKind NullKind =
  5071. NullExpr->isNullPointerConstant(Context,
  5072. Expr::NPC_ValueDependentIsNotNull);
  5073. if (NullKind == Expr::NPCK_NotNull) {
  5074. NullExpr = RHSExpr;
  5075. NonPointerExpr = LHSExpr;
  5076. NullKind =
  5077. NullExpr->isNullPointerConstant(Context,
  5078. Expr::NPC_ValueDependentIsNotNull);
  5079. }
  5080. if (NullKind == Expr::NPCK_NotNull)
  5081. return false;
  5082. if (NullKind == Expr::NPCK_ZeroExpression)
  5083. return false;
  5084. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5085. // In this case, check to make sure that we got here from a "NULL"
  5086. // string in the source code.
  5087. NullExpr = NullExpr->IgnoreParenImpCasts();
  5088. SourceLocation loc = NullExpr->getExprLoc();
  5089. if (!findMacroSpelling(loc, "NULL"))
  5090. return false;
  5091. }
  5092. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5093. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5094. << NonPointerExpr->getType() << DiagType
  5095. << NonPointerExpr->getSourceRange();
  5096. return true;
  5097. }
  5098. /// \brief Return false if the condition expression is valid, true otherwise.
  5099. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5100. QualType CondTy = Cond->getType();
  5101. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5102. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5103. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5104. << CondTy << Cond->getSourceRange();
  5105. return true;
  5106. }
  5107. // C99 6.5.15p2
  5108. if (CondTy->isScalarType()) return false;
  5109. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5110. << CondTy << Cond->getSourceRange();
  5111. return true;
  5112. }
  5113. /// \brief Handle when one or both operands are void type.
  5114. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5115. ExprResult &RHS) {
  5116. Expr *LHSExpr = LHS.get();
  5117. Expr *RHSExpr = RHS.get();
  5118. if (!LHSExpr->getType()->isVoidType())
  5119. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5120. << RHSExpr->getSourceRange();
  5121. if (!RHSExpr->getType()->isVoidType())
  5122. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5123. << LHSExpr->getSourceRange();
  5124. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5125. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5126. return S.Context.VoidTy;
  5127. }
  5128. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5129. /// true otherwise.
  5130. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5131. QualType PointerTy) {
  5132. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5133. !NullExpr.get()->isNullPointerConstant(S.Context,
  5134. Expr::NPC_ValueDependentIsNull))
  5135. return true;
  5136. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5137. return false;
  5138. }
  5139. /// \brief Checks compatibility between two pointers and return the resulting
  5140. /// type.
  5141. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5142. ExprResult &RHS,
  5143. SourceLocation Loc) {
  5144. QualType LHSTy = LHS.get()->getType();
  5145. QualType RHSTy = RHS.get()->getType();
  5146. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5147. // Two identical pointers types are always compatible.
  5148. return LHSTy;
  5149. }
  5150. QualType lhptee, rhptee;
  5151. // Get the pointee types.
  5152. bool IsBlockPointer = false;
  5153. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5154. lhptee = LHSBTy->getPointeeType();
  5155. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5156. IsBlockPointer = true;
  5157. } else {
  5158. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5159. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5160. }
  5161. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5162. // differently qualified versions of compatible types, the result type is
  5163. // a pointer to an appropriately qualified version of the composite
  5164. // type.
  5165. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5166. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5167. // be incompatible with address space 3: they may live on different devices or
  5168. // anything.
  5169. Qualifiers lhQual = lhptee.getQualifiers();
  5170. Qualifiers rhQual = rhptee.getQualifiers();
  5171. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5172. lhQual.removeCVRQualifiers();
  5173. rhQual.removeCVRQualifiers();
  5174. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5175. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5176. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5177. if (CompositeTy.isNull()) {
  5178. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5179. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5180. << RHS.get()->getSourceRange();
  5181. // In this situation, we assume void* type. No especially good
  5182. // reason, but this is what gcc does, and we do have to pick
  5183. // to get a consistent AST.
  5184. QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
  5185. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5186. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5187. return incompatTy;
  5188. }
  5189. // The pointer types are compatible.
  5190. QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
  5191. if (IsBlockPointer)
  5192. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5193. else
  5194. ResultTy = S.Context.getPointerType(ResultTy);
  5195. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
  5196. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
  5197. return ResultTy;
  5198. }
  5199. /// \brief Return the resulting type when the operands are both block pointers.
  5200. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5201. ExprResult &LHS,
  5202. ExprResult &RHS,
  5203. SourceLocation Loc) {
  5204. QualType LHSTy = LHS.get()->getType();
  5205. QualType RHSTy = RHS.get()->getType();
  5206. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5207. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5208. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5209. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5210. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5211. return destType;
  5212. }
  5213. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5214. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5215. << RHS.get()->getSourceRange();
  5216. return QualType();
  5217. }
  5218. // We have 2 block pointer types.
  5219. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5220. }
  5221. /// \brief Return the resulting type when the operands are both pointers.
  5222. static QualType
  5223. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5224. ExprResult &RHS,
  5225. SourceLocation Loc) {
  5226. // get the pointer types
  5227. QualType LHSTy = LHS.get()->getType();
  5228. QualType RHSTy = RHS.get()->getType();
  5229. // get the "pointed to" types
  5230. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5231. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5232. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5233. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5234. // Figure out necessary qualifiers (C99 6.5.15p6)
  5235. QualType destPointee
  5236. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5237. QualType destType = S.Context.getPointerType(destPointee);
  5238. // Add qualifiers if necessary.
  5239. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5240. // Promote to void*.
  5241. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5242. return destType;
  5243. }
  5244. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5245. QualType destPointee
  5246. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5247. QualType destType = S.Context.getPointerType(destPointee);
  5248. // Add qualifiers if necessary.
  5249. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5250. // Promote to void*.
  5251. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5252. return destType;
  5253. }
  5254. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5255. }
  5256. /// \brief Return false if the first expression is not an integer and the second
  5257. /// expression is not a pointer, true otherwise.
  5258. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5259. Expr* PointerExpr, SourceLocation Loc,
  5260. bool IsIntFirstExpr) {
  5261. if (!PointerExpr->getType()->isPointerType() ||
  5262. !Int.get()->getType()->isIntegerType())
  5263. return false;
  5264. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5265. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5266. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5267. << Expr1->getType() << Expr2->getType()
  5268. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5269. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5270. CK_IntegralToPointer);
  5271. return true;
  5272. }
  5273. /// \brief Simple conversion between integer and floating point types.
  5274. ///
  5275. /// Used when handling the OpenCL conditional operator where the
  5276. /// condition is a vector while the other operands are scalar.
  5277. ///
  5278. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5279. /// types are either integer or floating type. Between the two
  5280. /// operands, the type with the higher rank is defined as the "result
  5281. /// type". The other operand needs to be promoted to the same type. No
  5282. /// other type promotion is allowed. We cannot use
  5283. /// UsualArithmeticConversions() for this purpose, since it always
  5284. /// promotes promotable types.
  5285. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5286. ExprResult &RHS,
  5287. SourceLocation QuestionLoc) {
  5288. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5289. if (LHS.isInvalid())
  5290. return QualType();
  5291. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5292. if (RHS.isInvalid())
  5293. return QualType();
  5294. // For conversion purposes, we ignore any qualifiers.
  5295. // For example, "const float" and "float" are equivalent.
  5296. QualType LHSType =
  5297. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5298. QualType RHSType =
  5299. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5300. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5301. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5302. << LHSType << LHS.get()->getSourceRange();
  5303. return QualType();
  5304. }
  5305. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5306. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5307. << RHSType << RHS.get()->getSourceRange();
  5308. return QualType();
  5309. }
  5310. // If both types are identical, no conversion is needed.
  5311. if (LHSType == RHSType)
  5312. return LHSType;
  5313. // Now handle "real" floating types (i.e. float, double, long double).
  5314. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5315. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5316. /*IsCompAssign = */ false);
  5317. // Finally, we have two differing integer types.
  5318. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5319. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5320. }
  5321. /// \brief Convert scalar operands to a vector that matches the
  5322. /// condition in length.
  5323. ///
  5324. /// Used when handling the OpenCL conditional operator where the
  5325. /// condition is a vector while the other operands are scalar.
  5326. ///
  5327. /// We first compute the "result type" for the scalar operands
  5328. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5329. /// into a vector of that type where the length matches the condition
  5330. /// vector type. s6.11.6 requires that the element types of the result
  5331. /// and the condition must have the same number of bits.
  5332. static QualType
  5333. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5334. QualType CondTy, SourceLocation QuestionLoc) {
  5335. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5336. if (ResTy.isNull()) return QualType();
  5337. const VectorType *CV = CondTy->getAs<VectorType>();
  5338. assert(CV);
  5339. // Determine the vector result type
  5340. unsigned NumElements = CV->getNumElements();
  5341. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5342. // Ensure that all types have the same number of bits
  5343. if (S.Context.getTypeSize(CV->getElementType())
  5344. != S.Context.getTypeSize(ResTy)) {
  5345. // Since VectorTy is created internally, it does not pretty print
  5346. // with an OpenCL name. Instead, we just print a description.
  5347. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5348. SmallString<64> Str;
  5349. llvm::raw_svector_ostream OS(Str);
  5350. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5351. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5352. << CondTy << OS.str();
  5353. return QualType();
  5354. }
  5355. // Convert operands to the vector result type
  5356. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5357. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5358. return VectorTy;
  5359. }
  5360. /// \brief Return false if this is a valid OpenCL condition vector
  5361. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5362. SourceLocation QuestionLoc) {
  5363. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5364. // integral type.
  5365. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5366. assert(CondTy);
  5367. QualType EleTy = CondTy->getElementType();
  5368. if (EleTy->isIntegerType()) return false;
  5369. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5370. << Cond->getType() << Cond->getSourceRange();
  5371. return true;
  5372. }
  5373. /// \brief Return false if the vector condition type and the vector
  5374. /// result type are compatible.
  5375. ///
  5376. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5377. /// number of elements, and their element types have the same number
  5378. /// of bits.
  5379. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5380. SourceLocation QuestionLoc) {
  5381. const VectorType *CV = CondTy->getAs<VectorType>();
  5382. const VectorType *RV = VecResTy->getAs<VectorType>();
  5383. assert(CV && RV);
  5384. if (CV->getNumElements() != RV->getNumElements()) {
  5385. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5386. << CondTy << VecResTy;
  5387. return true;
  5388. }
  5389. QualType CVE = CV->getElementType();
  5390. QualType RVE = RV->getElementType();
  5391. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5392. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5393. << CondTy << VecResTy;
  5394. return true;
  5395. }
  5396. return false;
  5397. }
  5398. /// \brief Return the resulting type for the conditional operator in
  5399. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5400. /// s6.3.i) when the condition is a vector type.
  5401. static QualType
  5402. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5403. ExprResult &LHS, ExprResult &RHS,
  5404. SourceLocation QuestionLoc) {
  5405. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5406. if (Cond.isInvalid())
  5407. return QualType();
  5408. QualType CondTy = Cond.get()->getType();
  5409. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5410. return QualType();
  5411. // If either operand is a vector then find the vector type of the
  5412. // result as specified in OpenCL v1.1 s6.3.i.
  5413. if (LHS.get()->getType()->isVectorType() ||
  5414. RHS.get()->getType()->isVectorType()) {
  5415. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5416. /*isCompAssign*/false,
  5417. /*AllowBothBool*/true,
  5418. /*AllowBoolConversions*/false);
  5419. if (VecResTy.isNull()) return QualType();
  5420. // The result type must match the condition type as specified in
  5421. // OpenCL v1.1 s6.11.6.
  5422. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5423. return QualType();
  5424. return VecResTy;
  5425. }
  5426. // Both operands are scalar.
  5427. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5428. }
  5429. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5430. /// In that case, LHS = cond.
  5431. /// C99 6.5.15
  5432. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5433. ExprResult &RHS, ExprValueKind &VK,
  5434. ExprObjectKind &OK,
  5435. SourceLocation QuestionLoc) {
  5436. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5437. if (!LHSResult.isUsable()) return QualType();
  5438. LHS = LHSResult;
  5439. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5440. if (!RHSResult.isUsable()) return QualType();
  5441. RHS = RHSResult;
  5442. // HLSL Change Starts: HLSL supports a vector condition and is
  5443. // sufficiently different to merit its own checker.
  5444. if (getLangOpts().HLSL)
  5445. return hlsl::CheckVectorConditional(this, Cond, LHS, RHS, QuestionLoc);
  5446. // HLSL Change Ends
  5447. // C++ is sufficiently different to merit its own checker.
  5448. if (getLangOpts().CPlusPlus)
  5449. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5450. VK = VK_RValue;
  5451. OK = OK_Ordinary;
  5452. // The OpenCL operator with a vector condition is sufficiently
  5453. // different to merit its own checker.
  5454. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5455. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5456. // First, check the condition.
  5457. Cond = UsualUnaryConversions(Cond.get());
  5458. if (Cond.isInvalid())
  5459. return QualType();
  5460. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5461. return QualType();
  5462. // Now check the two expressions.
  5463. if (LHS.get()->getType()->isVectorType() ||
  5464. RHS.get()->getType()->isVectorType())
  5465. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5466. /*AllowBothBool*/true,
  5467. /*AllowBoolConversions*/false);
  5468. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5469. if (LHS.isInvalid() || RHS.isInvalid())
  5470. return QualType();
  5471. QualType LHSTy = LHS.get()->getType();
  5472. QualType RHSTy = RHS.get()->getType();
  5473. // If both operands have arithmetic type, do the usual arithmetic conversions
  5474. // to find a common type: C99 6.5.15p3,5.
  5475. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5476. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5477. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5478. return ResTy;
  5479. }
  5480. // If both operands are the same structure or union type, the result is that
  5481. // type.
  5482. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5483. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5484. if (LHSRT->getDecl() == RHSRT->getDecl())
  5485. // "If both the operands have structure or union type, the result has
  5486. // that type." This implies that CV qualifiers are dropped.
  5487. return LHSTy.getUnqualifiedType();
  5488. // FIXME: Type of conditional expression must be complete in C mode.
  5489. }
  5490. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5491. // The following || allows only one side to be void (a GCC-ism).
  5492. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5493. return checkConditionalVoidType(*this, LHS, RHS);
  5494. }
  5495. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5496. // the type of the other operand."
  5497. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5498. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5499. // All objective-c pointer type analysis is done here.
  5500. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5501. QuestionLoc);
  5502. if (LHS.isInvalid() || RHS.isInvalid())
  5503. return QualType();
  5504. if (!compositeType.isNull())
  5505. return compositeType;
  5506. // Handle block pointer types.
  5507. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  5508. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  5509. QuestionLoc);
  5510. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  5511. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  5512. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  5513. QuestionLoc);
  5514. // GCC compatibility: soften pointer/integer mismatch. Note that
  5515. // null pointers have been filtered out by this point.
  5516. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  5517. /*isIntFirstExpr=*/true))
  5518. return RHSTy;
  5519. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  5520. /*isIntFirstExpr=*/false))
  5521. return LHSTy;
  5522. // Emit a better diagnostic if one of the expressions is a null pointer
  5523. // constant and the other is not a pointer type. In this case, the user most
  5524. // likely forgot to take the address of the other expression.
  5525. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  5526. return QualType();
  5527. // Otherwise, the operands are not compatible.
  5528. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  5529. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5530. << RHS.get()->getSourceRange();
  5531. return QualType();
  5532. }
  5533. /// FindCompositeObjCPointerType - Helper method to find composite type of
  5534. /// two objective-c pointer types of the two input expressions.
  5535. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  5536. SourceLocation QuestionLoc) {
  5537. QualType LHSTy = LHS.get()->getType();
  5538. QualType RHSTy = RHS.get()->getType();
  5539. // Handle things like Class and struct objc_class*. Here we case the result
  5540. // to the pseudo-builtin, because that will be implicitly cast back to the
  5541. // redefinition type if an attempt is made to access its fields.
  5542. if (LHSTy->isObjCClassType() &&
  5543. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  5544. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5545. return LHSTy;
  5546. }
  5547. if (RHSTy->isObjCClassType() &&
  5548. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  5549. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5550. return RHSTy;
  5551. }
  5552. // And the same for struct objc_object* / id
  5553. if (LHSTy->isObjCIdType() &&
  5554. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  5555. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  5556. return LHSTy;
  5557. }
  5558. if (RHSTy->isObjCIdType() &&
  5559. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  5560. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  5561. return RHSTy;
  5562. }
  5563. // And the same for struct objc_selector* / SEL
  5564. if (Context.isObjCSelType(LHSTy) &&
  5565. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  5566. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  5567. return LHSTy;
  5568. }
  5569. if (Context.isObjCSelType(RHSTy) &&
  5570. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  5571. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  5572. return RHSTy;
  5573. }
  5574. // Check constraints for Objective-C object pointers types.
  5575. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  5576. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  5577. // Two identical object pointer types are always compatible.
  5578. return LHSTy;
  5579. }
  5580. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  5581. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  5582. QualType compositeType = LHSTy;
  5583. // If both operands are interfaces and either operand can be
  5584. // assigned to the other, use that type as the composite
  5585. // type. This allows
  5586. // xxx ? (A*) a : (B*) b
  5587. // where B is a subclass of A.
  5588. //
  5589. // Additionally, as for assignment, if either type is 'id'
  5590. // allow silent coercion. Finally, if the types are
  5591. // incompatible then make sure to use 'id' as the composite
  5592. // type so the result is acceptable for sending messages to.
  5593. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  5594. // It could return the composite type.
  5595. if (!(compositeType =
  5596. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  5597. // Nothing more to do.
  5598. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  5599. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  5600. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  5601. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  5602. } else if ((LHSTy->isObjCQualifiedIdType() ||
  5603. RHSTy->isObjCQualifiedIdType()) &&
  5604. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  5605. // Need to handle "id<xx>" explicitly.
  5606. // GCC allows qualified id and any Objective-C type to devolve to
  5607. // id. Currently localizing to here until clear this should be
  5608. // part of ObjCQualifiedIdTypesAreCompatible.
  5609. compositeType = Context.getObjCIdType();
  5610. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  5611. compositeType = Context.getObjCIdType();
  5612. } else {
  5613. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  5614. << LHSTy << RHSTy
  5615. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5616. QualType incompatTy = Context.getObjCIdType();
  5617. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  5618. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  5619. return incompatTy;
  5620. }
  5621. // The object pointer types are compatible.
  5622. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  5623. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  5624. return compositeType;
  5625. }
  5626. // Check Objective-C object pointer types and 'void *'
  5627. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  5628. if (getLangOpts().ObjCAutoRefCount) {
  5629. // ARC forbids the implicit conversion of object pointers to 'void *',
  5630. // so these types are not compatible.
  5631. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5632. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5633. LHS = RHS = true;
  5634. return QualType();
  5635. }
  5636. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5637. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5638. QualType destPointee
  5639. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5640. QualType destType = Context.getPointerType(destPointee);
  5641. // Add qualifiers if necessary.
  5642. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5643. // Promote to void*.
  5644. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5645. return destType;
  5646. }
  5647. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  5648. if (getLangOpts().ObjCAutoRefCount) {
  5649. // ARC forbids the implicit conversion of object pointers to 'void *',
  5650. // so these types are not compatible.
  5651. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  5652. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5653. LHS = RHS = true;
  5654. return QualType();
  5655. }
  5656. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  5657. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5658. QualType destPointee
  5659. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5660. QualType destType = Context.getPointerType(destPointee);
  5661. // Add qualifiers if necessary.
  5662. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5663. // Promote to void*.
  5664. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5665. return destType;
  5666. }
  5667. return QualType();
  5668. }
  5669. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  5670. /// ParenRange in parentheses.
  5671. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  5672. const PartialDiagnostic &Note,
  5673. SourceRange ParenRange) {
  5674. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
  5675. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  5676. EndLoc.isValid()) {
  5677. Self.Diag(Loc, Note)
  5678. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  5679. << FixItHint::CreateInsertion(EndLoc, ")");
  5680. } else {
  5681. // We can't display the parentheses, so just show the bare note.
  5682. Self.Diag(Loc, Note) << ParenRange;
  5683. }
  5684. }
  5685. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  5686. return Opc >= BO_Mul && Opc <= BO_Shr;
  5687. }
  5688. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  5689. /// expression, either using a built-in or overloaded operator,
  5690. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  5691. /// expression.
  5692. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  5693. Expr **RHSExprs) {
  5694. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  5695. E = E->IgnoreImpCasts();
  5696. E = E->IgnoreConversionOperator();
  5697. E = E->IgnoreImpCasts();
  5698. // Built-in binary operator.
  5699. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  5700. if (IsArithmeticOp(OP->getOpcode())) {
  5701. *Opcode = OP->getOpcode();
  5702. *RHSExprs = OP->getRHS();
  5703. return true;
  5704. }
  5705. }
  5706. // Overloaded operator.
  5707. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  5708. if (Call->getNumArgs() != 2)
  5709. return false;
  5710. // Make sure this is really a binary operator that is safe to pass into
  5711. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  5712. OverloadedOperatorKind OO = Call->getOperator();
  5713. if (OO < OO_Plus || OO > OO_Arrow ||
  5714. OO == OO_PlusPlus || OO == OO_MinusMinus)
  5715. return false;
  5716. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  5717. if (IsArithmeticOp(OpKind)) {
  5718. *Opcode = OpKind;
  5719. *RHSExprs = Call->getArg(1);
  5720. return true;
  5721. }
  5722. }
  5723. return false;
  5724. }
  5725. static bool IsLogicOp(BinaryOperatorKind Opc) {
  5726. return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
  5727. }
  5728. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  5729. /// or is a logical expression such as (x==y) which has int type, but is
  5730. /// commonly interpreted as boolean.
  5731. static bool ExprLooksBoolean(Expr *E) {
  5732. E = E->IgnoreParenImpCasts();
  5733. if (E->getType()->isBooleanType())
  5734. return true;
  5735. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  5736. return IsLogicOp(OP->getOpcode());
  5737. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  5738. return OP->getOpcode() == UO_LNot;
  5739. if (E->getType()->isPointerType())
  5740. return true;
  5741. return false;
  5742. }
  5743. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  5744. /// and binary operator are mixed in a way that suggests the programmer assumed
  5745. /// the conditional operator has higher precedence, for example:
  5746. /// "int x = a + someBinaryCondition ? 1 : 2".
  5747. static void DiagnoseConditionalPrecedence(Sema &Self,
  5748. SourceLocation OpLoc,
  5749. Expr *Condition,
  5750. Expr *LHSExpr,
  5751. Expr *RHSExpr) {
  5752. BinaryOperatorKind CondOpcode;
  5753. Expr *CondRHS;
  5754. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  5755. return;
  5756. if (!ExprLooksBoolean(CondRHS))
  5757. return;
  5758. // The condition is an arithmetic binary expression, with a right-
  5759. // hand side that looks boolean, so warn.
  5760. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  5761. << Condition->getSourceRange()
  5762. << BinaryOperator::getOpcodeStr(CondOpcode);
  5763. SuggestParentheses(Self, OpLoc,
  5764. Self.PDiag(diag::note_precedence_silence)
  5765. << BinaryOperator::getOpcodeStr(CondOpcode),
  5766. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  5767. SuggestParentheses(Self, OpLoc,
  5768. Self.PDiag(diag::note_precedence_conditional_first),
  5769. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  5770. }
  5771. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  5772. /// in the case of a the GNU conditional expr extension.
  5773. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  5774. SourceLocation ColonLoc,
  5775. Expr *CondExpr, Expr *LHSExpr,
  5776. Expr *RHSExpr) {
  5777. if (!getLangOpts().CPlusPlus) {
  5778. // C cannot handle TypoExpr nodes in the condition because it
  5779. // doesn't handle dependent types properly, so make sure any TypoExprs have
  5780. // been dealt with before checking the operands.
  5781. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  5782. if (!CondResult.isUsable()) return ExprError();
  5783. CondExpr = CondResult.get();
  5784. }
  5785. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  5786. // was the condition.
  5787. OpaqueValueExpr *opaqueValue = nullptr;
  5788. Expr *commonExpr = nullptr;
  5789. if (!LHSExpr) {
  5790. commonExpr = CondExpr;
  5791. // Lower out placeholder types first. This is important so that we don't
  5792. // try to capture a placeholder. This happens in few cases in C++; such
  5793. // as Objective-C++'s dictionary subscripting syntax.
  5794. if (commonExpr->hasPlaceholderType()) {
  5795. ExprResult result = CheckPlaceholderExpr(commonExpr);
  5796. if (!result.isUsable()) return ExprError();
  5797. commonExpr = result.get();
  5798. }
  5799. // We usually want to apply unary conversions *before* saving, except
  5800. // in the special case of a C++ l-value conditional.
  5801. if (!(getLangOpts().CPlusPlus
  5802. && !commonExpr->isTypeDependent()
  5803. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  5804. && commonExpr->isGLValue()
  5805. && commonExpr->isOrdinaryOrBitFieldObject()
  5806. && RHSExpr->isOrdinaryOrBitFieldObject()
  5807. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  5808. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  5809. if (commonRes.isInvalid())
  5810. return ExprError();
  5811. commonExpr = commonRes.get();
  5812. }
  5813. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  5814. commonExpr->getType(),
  5815. commonExpr->getValueKind(),
  5816. commonExpr->getObjectKind(),
  5817. commonExpr);
  5818. LHSExpr = CondExpr = opaqueValue;
  5819. }
  5820. ExprValueKind VK = VK_RValue;
  5821. ExprObjectKind OK = OK_Ordinary;
  5822. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  5823. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  5824. VK, OK, QuestionLoc);
  5825. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  5826. RHS.isInvalid())
  5827. return ExprError();
  5828. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  5829. RHS.get());
  5830. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  5831. if (!commonExpr)
  5832. return new (Context)
  5833. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  5834. RHS.get(), result, VK, OK);
  5835. return new (Context) BinaryConditionalOperator(
  5836. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  5837. ColonLoc, result, VK, OK);
  5838. }
  5839. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  5840. // being closely modeled after the C99 spec:-). The odd characteristic of this
  5841. // routine is it effectively iqnores the qualifiers on the top level pointee.
  5842. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  5843. // FIXME: add a couple examples in this comment.
  5844. static Sema::AssignConvertType
  5845. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  5846. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5847. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5848. // get the "pointed to" type (ignoring qualifiers at the top level)
  5849. const Type *lhptee, *rhptee;
  5850. Qualifiers lhq, rhq;
  5851. std::tie(lhptee, lhq) =
  5852. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  5853. std::tie(rhptee, rhq) =
  5854. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  5855. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5856. // C99 6.5.16.1p1: This following citation is common to constraints
  5857. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  5858. // qualifiers of the type *pointed to* by the right;
  5859. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  5860. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  5861. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  5862. // Ignore lifetime for further calculation.
  5863. lhq.removeObjCLifetime();
  5864. rhq.removeObjCLifetime();
  5865. }
  5866. if (!lhq.compatiblyIncludes(rhq)) {
  5867. // Treat address-space mismatches as fatal. TODO: address subspaces
  5868. if (!lhq.isAddressSpaceSupersetOf(rhq))
  5869. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5870. // It's okay to add or remove GC or lifetime qualifiers when converting to
  5871. // and from void*.
  5872. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  5873. .compatiblyIncludes(
  5874. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  5875. && (lhptee->isVoidType() || rhptee->isVoidType()))
  5876. ; // keep old
  5877. // Treat lifetime mismatches as fatal.
  5878. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  5879. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  5880. // For GCC compatibility, other qualifier mismatches are treated
  5881. // as still compatible in C.
  5882. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5883. }
  5884. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  5885. // incomplete type and the other is a pointer to a qualified or unqualified
  5886. // version of void...
  5887. if (lhptee->isVoidType()) {
  5888. if (rhptee->isIncompleteOrObjectType())
  5889. return ConvTy;
  5890. // As an extension, we allow cast to/from void* to function pointer.
  5891. assert(rhptee->isFunctionType());
  5892. return Sema::FunctionVoidPointer;
  5893. }
  5894. if (rhptee->isVoidType()) {
  5895. if (lhptee->isIncompleteOrObjectType())
  5896. return ConvTy;
  5897. // As an extension, we allow cast to/from void* to function pointer.
  5898. assert(lhptee->isFunctionType());
  5899. return Sema::FunctionVoidPointer;
  5900. }
  5901. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  5902. // unqualified versions of compatible types, ...
  5903. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  5904. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  5905. // Check if the pointee types are compatible ignoring the sign.
  5906. // We explicitly check for char so that we catch "char" vs
  5907. // "unsigned char" on systems where "char" is unsigned.
  5908. if (lhptee->isCharType())
  5909. ltrans = S.Context.UnsignedCharTy;
  5910. else if (lhptee->hasSignedIntegerRepresentation())
  5911. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  5912. if (rhptee->isCharType())
  5913. rtrans = S.Context.UnsignedCharTy;
  5914. else if (rhptee->hasSignedIntegerRepresentation())
  5915. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  5916. if (ltrans == rtrans) {
  5917. // Types are compatible ignoring the sign. Qualifier incompatibility
  5918. // takes priority over sign incompatibility because the sign
  5919. // warning can be disabled.
  5920. if (ConvTy != Sema::Compatible)
  5921. return ConvTy;
  5922. return Sema::IncompatiblePointerSign;
  5923. }
  5924. // If we are a multi-level pointer, it's possible that our issue is simply
  5925. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  5926. // the eventual target type is the same and the pointers have the same
  5927. // level of indirection, this must be the issue.
  5928. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  5929. do {
  5930. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  5931. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  5932. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  5933. if (lhptee == rhptee)
  5934. return Sema::IncompatibleNestedPointerQualifiers;
  5935. }
  5936. // General pointer incompatibility takes priority over qualifiers.
  5937. return Sema::IncompatiblePointer;
  5938. }
  5939. if (!S.getLangOpts().CPlusPlus &&
  5940. S.IsNoReturnConversion(ltrans, rtrans, ltrans))
  5941. return Sema::IncompatiblePointer;
  5942. return ConvTy;
  5943. }
  5944. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  5945. /// block pointer types are compatible or whether a block and normal pointer
  5946. /// are compatible. It is more restrict than comparing two function pointer
  5947. // types.
  5948. static Sema::AssignConvertType
  5949. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  5950. QualType RHSType) {
  5951. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  5952. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  5953. QualType lhptee, rhptee;
  5954. // get the "pointed to" type (ignoring qualifiers at the top level)
  5955. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  5956. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  5957. // In C++, the types have to match exactly.
  5958. if (S.getLangOpts().CPlusPlus)
  5959. return Sema::IncompatibleBlockPointer;
  5960. Sema::AssignConvertType ConvTy = Sema::Compatible;
  5961. // For blocks we enforce that qualifiers are identical.
  5962. if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
  5963. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  5964. if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  5965. return Sema::IncompatibleBlockPointer;
  5966. return ConvTy;
  5967. }
  5968. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  5969. /// for assignment compatibility.
  5970. static Sema::AssignConvertType
  5971. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  5972. QualType RHSType) {
  5973. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  5974. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  5975. if (LHSType->isObjCBuiltinType()) {
  5976. // Class is not compatible with ObjC object pointers.
  5977. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  5978. !RHSType->isObjCQualifiedClassType())
  5979. return Sema::IncompatiblePointer;
  5980. return Sema::Compatible;
  5981. }
  5982. if (RHSType->isObjCBuiltinType()) {
  5983. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  5984. !LHSType->isObjCQualifiedClassType())
  5985. return Sema::IncompatiblePointer;
  5986. return Sema::Compatible;
  5987. }
  5988. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5989. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  5990. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  5991. // make an exception for id<P>
  5992. !LHSType->isObjCQualifiedIdType())
  5993. return Sema::CompatiblePointerDiscardsQualifiers;
  5994. if (S.Context.typesAreCompatible(LHSType, RHSType))
  5995. return Sema::Compatible;
  5996. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  5997. return Sema::IncompatibleObjCQualifiedId;
  5998. return Sema::IncompatiblePointer;
  5999. }
  6000. Sema::AssignConvertType
  6001. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6002. QualType LHSType, QualType RHSType) {
  6003. // Fake up an opaque expression. We don't actually care about what
  6004. // cast operations are required, so if CheckAssignmentConstraints
  6005. // adds casts to this they'll be wasted, but fortunately that doesn't
  6006. // usually happen on valid code.
  6007. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6008. ExprResult RHSPtr = &RHSExpr;
  6009. CastKind K = CK_Invalid;
  6010. return CheckAssignmentConstraints(LHSType, RHSPtr, K);
  6011. }
  6012. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6013. /// has code to accommodate several GCC extensions when type checking
  6014. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6015. ///
  6016. /// int a, *pint;
  6017. /// short *pshort;
  6018. /// struct foo *pfoo;
  6019. ///
  6020. /// pint = pshort; // warning: assignment from incompatible pointer type
  6021. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6022. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6023. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6024. ///
  6025. /// As a result, the code for dealing with pointers is more complex than the
  6026. /// C99 spec dictates.
  6027. ///
  6028. /// Sets 'Kind' for any result kind except Incompatible.
  6029. Sema::AssignConvertType
  6030. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6031. CastKind &Kind) {
  6032. QualType RHSType = RHS.get()->getType();
  6033. QualType OrigLHSType = LHSType;
  6034. // Get canonical types. We're not formatting these types, just comparing
  6035. // them.
  6036. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6037. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6038. // Common case: no conversion required.
  6039. if (LHSType == RHSType) {
  6040. Kind = CK_NoOp;
  6041. return Compatible;
  6042. }
  6043. // If we have an atomic type, try a non-atomic assignment, then just add an
  6044. // atomic qualification step.
  6045. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6046. Sema::AssignConvertType result =
  6047. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6048. if (result != Compatible)
  6049. return result;
  6050. if (Kind != CK_NoOp)
  6051. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6052. Kind = CK_NonAtomicToAtomic;
  6053. return Compatible;
  6054. }
  6055. // If the left-hand side is a reference type, then we are in a
  6056. // (rare!) case where we've allowed the use of references in C,
  6057. // e.g., as a parameter type in a built-in function. In this case,
  6058. // just make sure that the type referenced is compatible with the
  6059. // right-hand side type. The caller is responsible for adjusting
  6060. // LHSType so that the resulting expression does not have reference
  6061. // type.
  6062. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6063. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6064. Kind = CK_LValueBitCast;
  6065. return Compatible;
  6066. }
  6067. return Incompatible;
  6068. }
  6069. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6070. // to the same ExtVector type.
  6071. if (LHSType->isExtVectorType()) {
  6072. if (RHSType->isExtVectorType())
  6073. return Incompatible;
  6074. if (RHSType->isArithmeticType()) {
  6075. // CK_VectorSplat does T -> vector T, so first cast to the
  6076. // element type.
  6077. QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
  6078. if (elType != RHSType) {
  6079. Kind = PrepareScalarCast(RHS, elType);
  6080. RHS = ImpCastExprToType(RHS.get(), elType, Kind);
  6081. }
  6082. Kind = CK_VectorSplat;
  6083. return Compatible;
  6084. }
  6085. }
  6086. // Conversions to or from vector type.
  6087. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6088. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6089. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6090. // vector type and vice versa
  6091. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6092. Kind = CK_BitCast;
  6093. return Compatible;
  6094. }
  6095. // If we are allowing lax vector conversions, and LHS and RHS are both
  6096. // vectors, the total size only needs to be the same. This is a bitcast;
  6097. // no bits are changed but the result type is different.
  6098. if (isLaxVectorConversion(RHSType, LHSType)) {
  6099. Kind = CK_BitCast;
  6100. return IncompatibleVectors;
  6101. }
  6102. }
  6103. return Incompatible;
  6104. }
  6105. // Arithmetic conversions.
  6106. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6107. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6108. Kind = PrepareScalarCast(RHS, LHSType);
  6109. return Compatible;
  6110. }
  6111. // Conversions to normal pointers.
  6112. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6113. // U* -> T*
  6114. if (isa<PointerType>(RHSType)) {
  6115. unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6116. unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6117. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6118. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6119. }
  6120. // int -> T*
  6121. if (RHSType->isIntegerType()) {
  6122. Kind = CK_IntegralToPointer; // FIXME: null?
  6123. return IntToPointer;
  6124. }
  6125. // C pointers are not compatible with ObjC object pointers,
  6126. // with two exceptions:
  6127. if (isa<ObjCObjectPointerType>(RHSType)) {
  6128. // - conversions to void*
  6129. if (LHSPointer->getPointeeType()->isVoidType()) {
  6130. Kind = CK_BitCast;
  6131. return Compatible;
  6132. }
  6133. // - conversions from 'Class' to the redefinition type
  6134. if (RHSType->isObjCClassType() &&
  6135. Context.hasSameType(LHSType,
  6136. Context.getObjCClassRedefinitionType())) {
  6137. Kind = CK_BitCast;
  6138. return Compatible;
  6139. }
  6140. Kind = CK_BitCast;
  6141. return IncompatiblePointer;
  6142. }
  6143. // U^ -> void*
  6144. if (RHSType->getAs<BlockPointerType>()) {
  6145. if (LHSPointer->getPointeeType()->isVoidType()) {
  6146. Kind = CK_BitCast;
  6147. return Compatible;
  6148. }
  6149. }
  6150. return Incompatible;
  6151. }
  6152. // Conversions to block pointers.
  6153. if (isa<BlockPointerType>(LHSType)) {
  6154. // U^ -> T^
  6155. if (RHSType->isBlockPointerType()) {
  6156. Kind = CK_BitCast;
  6157. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6158. }
  6159. // int or null -> T^
  6160. if (RHSType->isIntegerType()) {
  6161. Kind = CK_IntegralToPointer; // FIXME: null
  6162. return IntToBlockPointer;
  6163. }
  6164. // id -> T^
  6165. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6166. Kind = CK_AnyPointerToBlockPointerCast;
  6167. return Compatible;
  6168. }
  6169. // void* -> T^
  6170. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6171. if (RHSPT->getPointeeType()->isVoidType()) {
  6172. Kind = CK_AnyPointerToBlockPointerCast;
  6173. return Compatible;
  6174. }
  6175. return Incompatible;
  6176. }
  6177. // Conversions to Objective-C pointers.
  6178. if (isa<ObjCObjectPointerType>(LHSType)) {
  6179. // A* -> B*
  6180. if (RHSType->isObjCObjectPointerType()) {
  6181. Kind = CK_BitCast;
  6182. Sema::AssignConvertType result =
  6183. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6184. if (getLangOpts().ObjCAutoRefCount &&
  6185. result == Compatible &&
  6186. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6187. result = IncompatibleObjCWeakRef;
  6188. return result;
  6189. }
  6190. // int or null -> A*
  6191. if (RHSType->isIntegerType()) {
  6192. Kind = CK_IntegralToPointer; // FIXME: null
  6193. return IntToPointer;
  6194. }
  6195. // In general, C pointers are not compatible with ObjC object pointers,
  6196. // with two exceptions:
  6197. if (isa<PointerType>(RHSType)) {
  6198. Kind = CK_CPointerToObjCPointerCast;
  6199. // - conversions from 'void*'
  6200. if (RHSType->isVoidPointerType()) {
  6201. return Compatible;
  6202. }
  6203. // - conversions to 'Class' from its redefinition type
  6204. if (LHSType->isObjCClassType() &&
  6205. Context.hasSameType(RHSType,
  6206. Context.getObjCClassRedefinitionType())) {
  6207. return Compatible;
  6208. }
  6209. return IncompatiblePointer;
  6210. }
  6211. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6212. if (RHSType->isBlockPointerType() &&
  6213. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6214. maybeExtendBlockObject(RHS);
  6215. Kind = CK_BlockPointerToObjCPointerCast;
  6216. return Compatible;
  6217. }
  6218. return Incompatible;
  6219. }
  6220. // Conversions from pointers that are not covered by the above.
  6221. if (isa<PointerType>(RHSType)) {
  6222. // T* -> _Bool
  6223. if (LHSType == Context.BoolTy) {
  6224. Kind = CK_PointerToBoolean;
  6225. return Compatible;
  6226. }
  6227. // T* -> int
  6228. if (LHSType->isIntegerType()) {
  6229. Kind = CK_PointerToIntegral;
  6230. return PointerToInt;
  6231. }
  6232. return Incompatible;
  6233. }
  6234. // Conversions from Objective-C pointers that are not covered by the above.
  6235. if (isa<ObjCObjectPointerType>(RHSType)) {
  6236. // T* -> _Bool
  6237. if (LHSType == Context.BoolTy) {
  6238. Kind = CK_PointerToBoolean;
  6239. return Compatible;
  6240. }
  6241. // T* -> int
  6242. if (LHSType->isIntegerType()) {
  6243. Kind = CK_PointerToIntegral;
  6244. return PointerToInt;
  6245. }
  6246. return Incompatible;
  6247. }
  6248. // struct A -> struct B
  6249. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6250. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6251. Kind = CK_NoOp;
  6252. return Compatible;
  6253. }
  6254. }
  6255. return Incompatible;
  6256. }
  6257. /// \brief Constructs a transparent union from an expression that is
  6258. /// used to initialize the transparent union.
  6259. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6260. ExprResult &EResult, QualType UnionType,
  6261. FieldDecl *Field) {
  6262. // Build an initializer list that designates the appropriate member
  6263. // of the transparent union.
  6264. Expr *E = EResult.get();
  6265. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6266. E, SourceLocation());
  6267. Initializer->setType(UnionType);
  6268. Initializer->setInitializedFieldInUnion(Field);
  6269. // Build a compound literal constructing a value of the transparent
  6270. // union type from this initializer list.
  6271. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6272. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6273. VK_RValue, Initializer, false);
  6274. }
  6275. Sema::AssignConvertType
  6276. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6277. ExprResult &RHS) {
  6278. QualType RHSType = RHS.get()->getType();
  6279. // If the ArgType is a Union type, we want to handle a potential
  6280. // transparent_union GCC extension.
  6281. const RecordType *UT = ArgType->getAsUnionType();
  6282. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6283. return Incompatible;
  6284. // The field to initialize within the transparent union.
  6285. RecordDecl *UD = UT->getDecl();
  6286. FieldDecl *InitField = nullptr;
  6287. // It's compatible if the expression matches any of the fields.
  6288. for (auto *it : UD->fields()) {
  6289. if (it->getType()->isPointerType()) {
  6290. // If the transparent union contains a pointer type, we allow:
  6291. // 1) void pointer
  6292. // 2) null pointer constant
  6293. if (RHSType->isPointerType())
  6294. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6295. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6296. InitField = it;
  6297. break;
  6298. }
  6299. if (RHS.get()->isNullPointerConstant(Context,
  6300. Expr::NPC_ValueDependentIsNull)) {
  6301. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6302. CK_NullToPointer);
  6303. InitField = it;
  6304. break;
  6305. }
  6306. }
  6307. CastKind Kind = CK_Invalid;
  6308. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6309. == Compatible) {
  6310. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6311. InitField = it;
  6312. break;
  6313. }
  6314. }
  6315. if (!InitField)
  6316. return Incompatible;
  6317. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6318. return Compatible;
  6319. }
  6320. Sema::AssignConvertType
  6321. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6322. bool Diagnose,
  6323. bool DiagnoseCFAudited) {
  6324. // HLSL Change Starts
  6325. if (getLangOpts().HLSL) {
  6326. // DiagnoseAssignmentResultForHLSL will take care of diagnostics.
  6327. return Compatible;
  6328. }
  6329. // HLSL Change Ends
  6330. if (getLangOpts().CPlusPlus) {
  6331. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6332. // C++ 5.17p3: If the left operand is not of class type, the
  6333. // expression is implicitly converted (C++ 4) to the
  6334. // cv-unqualified type of the left operand.
  6335. ExprResult Res;
  6336. if (Diagnose) {
  6337. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6338. AA_Assigning);
  6339. } else {
  6340. ImplicitConversionSequence ICS =
  6341. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6342. /*SuppressUserConversions=*/false,
  6343. /*AllowExplicit=*/false,
  6344. /*InOverloadResolution=*/false,
  6345. /*CStyle=*/false,
  6346. /*AllowObjCWritebackConversion=*/false);
  6347. if (ICS.isFailure())
  6348. return Incompatible;
  6349. Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6350. ICS, AA_Assigning);
  6351. }
  6352. if (Res.isInvalid())
  6353. return Incompatible;
  6354. Sema::AssignConvertType result = Compatible;
  6355. if (getLangOpts().ObjCAutoRefCount &&
  6356. !CheckObjCARCUnavailableWeakConversion(LHSType,
  6357. RHS.get()->getType()))
  6358. result = IncompatibleObjCWeakRef;
  6359. RHS = Res;
  6360. return result;
  6361. }
  6362. // FIXME: Currently, we fall through and treat C++ classes like C
  6363. // structures.
  6364. // FIXME: We also fall through for atomics; not sure what should
  6365. // happen there, though.
  6366. }
  6367. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  6368. // a null pointer constant.
  6369. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  6370. LHSType->isBlockPointerType()) &&
  6371. RHS.get()->isNullPointerConstant(Context,
  6372. Expr::NPC_ValueDependentIsNull)) {
  6373. CastKind Kind;
  6374. CXXCastPath Path;
  6375. CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
  6376. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  6377. return Compatible;
  6378. }
  6379. // This check seems unnatural, however it is necessary to ensure the proper
  6380. // conversion of functions/arrays. If the conversion were done for all
  6381. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  6382. // expressions that suppress this implicit conversion (&, sizeof).
  6383. //
  6384. // Suppress this for references: C++ 8.5.3p5.
  6385. if (!LHSType->isReferenceType()) {
  6386. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6387. if (RHS.isInvalid())
  6388. return Incompatible;
  6389. }
  6390. Expr *PRE = RHS.get()->IgnoreParenCasts();
  6391. if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
  6392. ObjCProtocolDecl *PDecl = OPE->getProtocol();
  6393. if (PDecl && !PDecl->hasDefinition()) {
  6394. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  6395. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  6396. }
  6397. }
  6398. CastKind Kind = CK_Invalid;
  6399. Sema::AssignConvertType result =
  6400. CheckAssignmentConstraints(LHSType, RHS, Kind);
  6401. // C99 6.5.16.1p2: The value of the right operand is converted to the
  6402. // type of the assignment expression.
  6403. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  6404. // so that we can use references in built-in functions even in C.
  6405. // The getNonReferenceType() call makes sure that the resulting expression
  6406. // does not have reference type.
  6407. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  6408. QualType Ty = LHSType.getNonLValueExprType(Context);
  6409. Expr *E = RHS.get();
  6410. if (getLangOpts().ObjCAutoRefCount)
  6411. CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  6412. DiagnoseCFAudited);
  6413. if (getLangOpts().ObjC1 &&
  6414. (CheckObjCBridgeRelatedConversions(E->getLocStart(),
  6415. LHSType, E->getType(), E) ||
  6416. ConversionToObjCStringLiteralCheck(LHSType, E))) {
  6417. RHS = E;
  6418. return Compatible;
  6419. }
  6420. RHS = ImpCastExprToType(E, Ty, Kind);
  6421. }
  6422. return result;
  6423. }
  6424. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  6425. ExprResult &RHS) {
  6426. Diag(Loc, diag::err_typecheck_invalid_operands)
  6427. << LHS.get()->getType() << RHS.get()->getType()
  6428. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6429. return QualType();
  6430. }
  6431. /// Try to convert a value of non-vector type to a vector type by converting
  6432. /// the type to the element type of the vector and then performing a splat.
  6433. /// If the language is OpenCL, we only use conversions that promote scalar
  6434. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  6435. /// for float->int.
  6436. ///
  6437. /// \param scalar - if non-null, actually perform the conversions
  6438. /// \return true if the operation fails (but without diagnosing the failure)
  6439. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  6440. QualType scalarTy,
  6441. QualType vectorEltTy,
  6442. QualType vectorTy) {
  6443. // The conversion to apply to the scalar before splatting it,
  6444. // if necessary.
  6445. CastKind scalarCast = CK_Invalid;
  6446. if (vectorEltTy->isIntegralType(S.Context)) {
  6447. if (!scalarTy->isIntegralType(S.Context))
  6448. return true;
  6449. if (S.getLangOpts().OpenCL &&
  6450. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
  6451. return true;
  6452. scalarCast = CK_IntegralCast;
  6453. } else if (vectorEltTy->isRealFloatingType()) {
  6454. if (scalarTy->isRealFloatingType()) {
  6455. if (S.getLangOpts().OpenCL &&
  6456. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
  6457. return true;
  6458. scalarCast = CK_FloatingCast;
  6459. }
  6460. else if (scalarTy->isIntegralType(S.Context))
  6461. scalarCast = CK_IntegralToFloating;
  6462. else
  6463. return true;
  6464. } else {
  6465. return true;
  6466. }
  6467. // Adjust scalar if desired.
  6468. if (scalar) {
  6469. if (scalarCast != CK_Invalid)
  6470. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  6471. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  6472. }
  6473. return false;
  6474. }
  6475. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  6476. SourceLocation Loc, bool IsCompAssign,
  6477. bool AllowBothBool,
  6478. bool AllowBoolConversions) {
  6479. if (!IsCompAssign) {
  6480. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  6481. if (LHS.isInvalid())
  6482. return QualType();
  6483. }
  6484. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  6485. if (RHS.isInvalid())
  6486. return QualType();
  6487. // For conversion purposes, we ignore any qualifiers.
  6488. // For example, "const float" and "float" are equivalent.
  6489. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  6490. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  6491. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  6492. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  6493. assert(LHSVecType || RHSVecType);
  6494. // AltiVec-style "vector bool op vector bool" combinations are allowed
  6495. // for some operators but not others.
  6496. if (!AllowBothBool &&
  6497. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6498. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  6499. return InvalidOperands(Loc, LHS, RHS);
  6500. // If the vector types are identical, return.
  6501. if (Context.hasSameType(LHSType, RHSType))
  6502. return LHSType;
  6503. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  6504. if (LHSVecType && RHSVecType &&
  6505. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6506. if (isa<ExtVectorType>(LHSVecType)) {
  6507. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6508. return LHSType;
  6509. }
  6510. if (!IsCompAssign)
  6511. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6512. return RHSType;
  6513. }
  6514. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  6515. // can be mixed, with the result being the non-bool type. The non-bool
  6516. // operand must have integer element type.
  6517. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  6518. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  6519. (Context.getTypeSize(LHSVecType->getElementType()) ==
  6520. Context.getTypeSize(RHSVecType->getElementType()))) {
  6521. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6522. LHSVecType->getElementType()->isIntegerType() &&
  6523. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  6524. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  6525. return LHSType;
  6526. }
  6527. if (!IsCompAssign &&
  6528. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  6529. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  6530. RHSVecType->getElementType()->isIntegerType()) {
  6531. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  6532. return RHSType;
  6533. }
  6534. }
  6535. // If there's an ext-vector type and a scalar, try to convert the scalar to
  6536. // the vector element type and splat.
  6537. if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
  6538. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  6539. LHSVecType->getElementType(), LHSType))
  6540. return LHSType;
  6541. }
  6542. if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
  6543. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  6544. LHSType, RHSVecType->getElementType(),
  6545. RHSType))
  6546. return RHSType;
  6547. }
  6548. // If we're allowing lax vector conversions, only the total (data) size
  6549. // needs to be the same.
  6550. // FIXME: Should we really be allowing this?
  6551. // FIXME: We really just pick the LHS type arbitrarily?
  6552. if (isLaxVectorConversion(RHSType, LHSType)) {
  6553. QualType resultType = LHSType;
  6554. RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
  6555. return resultType;
  6556. }
  6557. // Okay, the expression is invalid.
  6558. // If there's a non-vector, non-real operand, diagnose that.
  6559. if ((!RHSVecType && !RHSType->isRealType()) ||
  6560. (!LHSVecType && !LHSType->isRealType())) {
  6561. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  6562. << LHSType << RHSType
  6563. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6564. return QualType();
  6565. }
  6566. // Otherwise, use the generic diagnostic.
  6567. Diag(Loc, diag::err_typecheck_vector_not_convertable)
  6568. << LHSType << RHSType
  6569. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6570. return QualType();
  6571. }
  6572. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  6573. // expression. These are mainly cases where the null pointer is used as an
  6574. // integer instead of a pointer.
  6575. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6576. SourceLocation Loc, bool IsCompare) {
  6577. // The canonical way to check for a GNU null is with isNullPointerConstant,
  6578. // but we use a bit of a hack here for speed; this is a relatively
  6579. // hot path, and isNullPointerConstant is slow.
  6580. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  6581. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  6582. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  6583. // Avoid analyzing cases where the result will either be invalid (and
  6584. // diagnosed as such) or entirely valid and not something to warn about.
  6585. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  6586. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  6587. return;
  6588. // Comparison operations would not make sense with a null pointer no matter
  6589. // what the other expression is.
  6590. if (!IsCompare) {
  6591. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  6592. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  6593. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  6594. return;
  6595. }
  6596. // The rest of the operations only make sense with a null pointer
  6597. // if the other expression is a pointer.
  6598. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  6599. NonNullType->canDecayToPointerType())
  6600. return;
  6601. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  6602. << LHSNull /* LHS is NULL */ << NonNullType
  6603. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6604. }
  6605. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  6606. SourceLocation Loc,
  6607. bool IsCompAssign, bool IsDiv) {
  6608. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6609. if (LHS.get()->getType()->isVectorType() ||
  6610. RHS.get()->getType()->isVectorType())
  6611. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6612. /*AllowBothBool*/getLangOpts().AltiVec,
  6613. /*AllowBoolConversions*/false);
  6614. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6615. if (LHS.isInvalid() || RHS.isInvalid())
  6616. return QualType();
  6617. if (compType.isNull() || !compType->isArithmeticType())
  6618. return InvalidOperands(Loc, LHS, RHS);
  6619. // Check for division by zero.
  6620. llvm::APSInt RHSValue;
  6621. if (IsDiv && !RHS.get()->isValueDependent() &&
  6622. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6623. DiagRuntimeBehavior(Loc, RHS.get(),
  6624. PDiag(diag::warn_division_by_zero)
  6625. << RHS.get()->getSourceRange());
  6626. return compType;
  6627. }
  6628. QualType Sema::CheckRemainderOperands(
  6629. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  6630. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6631. if (LHS.get()->getType()->isVectorType() ||
  6632. RHS.get()->getType()->isVectorType()) {
  6633. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  6634. RHS.get()->getType()->hasIntegerRepresentation())
  6635. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  6636. /*AllowBothBool*/getLangOpts().AltiVec,
  6637. /*AllowBoolConversions*/false);
  6638. return InvalidOperands(Loc, LHS, RHS);
  6639. }
  6640. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  6641. if (LHS.isInvalid() || RHS.isInvalid())
  6642. return QualType();
  6643. if (compType.isNull() || !compType->isIntegerType())
  6644. return InvalidOperands(Loc, LHS, RHS);
  6645. // Check for remainder by zero.
  6646. llvm::APSInt RHSValue;
  6647. if (!RHS.get()->isValueDependent() &&
  6648. RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
  6649. DiagRuntimeBehavior(Loc, RHS.get(),
  6650. PDiag(diag::warn_remainder_by_zero)
  6651. << RHS.get()->getSourceRange());
  6652. return compType;
  6653. }
  6654. /// \brief Diagnose invalid arithmetic on two void pointers.
  6655. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  6656. Expr *LHSExpr, Expr *RHSExpr) {
  6657. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6658. ? diag::err_typecheck_pointer_arith_void_type
  6659. : diag::ext_gnu_void_ptr)
  6660. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  6661. << RHSExpr->getSourceRange();
  6662. }
  6663. /// \brief Diagnose invalid arithmetic on a void pointer.
  6664. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  6665. Expr *Pointer) {
  6666. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6667. ? diag::err_typecheck_pointer_arith_void_type
  6668. : diag::ext_gnu_void_ptr)
  6669. << 0 /* one pointer */ << Pointer->getSourceRange();
  6670. }
  6671. /// \brief Diagnose invalid arithmetic on two function pointers.
  6672. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  6673. Expr *LHS, Expr *RHS) {
  6674. assert(LHS->getType()->isAnyPointerType());
  6675. assert(RHS->getType()->isAnyPointerType());
  6676. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6677. ? diag::err_typecheck_pointer_arith_function_type
  6678. : diag::ext_gnu_ptr_func_arith)
  6679. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  6680. // We only show the second type if it differs from the first.
  6681. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  6682. RHS->getType())
  6683. << RHS->getType()->getPointeeType()
  6684. << LHS->getSourceRange() << RHS->getSourceRange();
  6685. }
  6686. /// \brief Diagnose invalid arithmetic on a function pointer.
  6687. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  6688. Expr *Pointer) {
  6689. assert(Pointer->getType()->isAnyPointerType());
  6690. S.Diag(Loc, S.getLangOpts().CPlusPlus
  6691. ? diag::err_typecheck_pointer_arith_function_type
  6692. : diag::ext_gnu_ptr_func_arith)
  6693. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  6694. << 0 /* one pointer, so only one type */
  6695. << Pointer->getSourceRange();
  6696. }
  6697. /// \brief Emit error if Operand is incomplete pointer type
  6698. ///
  6699. /// \returns True if pointer has incomplete type
  6700. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  6701. Expr *Operand) {
  6702. QualType ResType = Operand->getType();
  6703. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6704. ResType = ResAtomicType->getValueType();
  6705. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  6706. QualType PointeeTy = ResType->getPointeeType();
  6707. return S.RequireCompleteType(Loc, PointeeTy,
  6708. diag::err_typecheck_arithmetic_incomplete_type,
  6709. PointeeTy, Operand->getSourceRange());
  6710. }
  6711. /// \brief Check the validity of an arithmetic pointer operand.
  6712. ///
  6713. /// If the operand has pointer type, this code will check for pointer types
  6714. /// which are invalid in arithmetic operations. These will be diagnosed
  6715. /// appropriately, including whether or not the use is supported as an
  6716. /// extension.
  6717. ///
  6718. /// \returns True when the operand is valid to use (even if as an extension).
  6719. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  6720. Expr *Operand) {
  6721. QualType ResType = Operand->getType();
  6722. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  6723. ResType = ResAtomicType->getValueType();
  6724. if (!ResType->isAnyPointerType()) return true;
  6725. QualType PointeeTy = ResType->getPointeeType();
  6726. if (PointeeTy->isVoidType()) {
  6727. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  6728. return !S.getLangOpts().CPlusPlus;
  6729. }
  6730. if (PointeeTy->isFunctionType()) {
  6731. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  6732. return !S.getLangOpts().CPlusPlus;
  6733. }
  6734. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  6735. return true;
  6736. }
  6737. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  6738. /// operands.
  6739. ///
  6740. /// This routine will diagnose any invalid arithmetic on pointer operands much
  6741. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  6742. /// for emitting a single diagnostic even for operations where both LHS and RHS
  6743. /// are (potentially problematic) pointers.
  6744. ///
  6745. /// \returns True when the operand is valid to use (even if as an extension).
  6746. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  6747. Expr *LHSExpr, Expr *RHSExpr) {
  6748. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  6749. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  6750. if (!isLHSPointer && !isRHSPointer) return true;
  6751. QualType LHSPointeeTy, RHSPointeeTy;
  6752. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  6753. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  6754. // if both are pointers check if operation is valid wrt address spaces
  6755. if (isLHSPointer && isRHSPointer) {
  6756. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  6757. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  6758. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  6759. S.Diag(Loc,
  6760. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6761. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  6762. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  6763. return false;
  6764. }
  6765. }
  6766. // Check for arithmetic on pointers to incomplete types.
  6767. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  6768. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  6769. if (isLHSVoidPtr || isRHSVoidPtr) {
  6770. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  6771. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  6772. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  6773. return !S.getLangOpts().CPlusPlus;
  6774. }
  6775. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  6776. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  6777. if (isLHSFuncPtr || isRHSFuncPtr) {
  6778. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  6779. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  6780. RHSExpr);
  6781. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  6782. return !S.getLangOpts().CPlusPlus;
  6783. }
  6784. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  6785. return false;
  6786. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  6787. return false;
  6788. return true;
  6789. }
  6790. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  6791. /// literal.
  6792. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  6793. Expr *LHSExpr, Expr *RHSExpr) {
  6794. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  6795. Expr* IndexExpr = RHSExpr;
  6796. if (!StrExpr) {
  6797. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  6798. IndexExpr = LHSExpr;
  6799. }
  6800. bool IsStringPlusInt = StrExpr &&
  6801. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  6802. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  6803. return;
  6804. llvm::APSInt index;
  6805. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  6806. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  6807. if (index.isNonNegative() &&
  6808. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  6809. index.isUnsigned()))
  6810. return;
  6811. }
  6812. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6813. Self.Diag(OpLoc, diag::warn_string_plus_int)
  6814. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  6815. // Only print a fixit for "str" + int, not for int + "str".
  6816. if (IndexExpr == RHSExpr) {
  6817. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6818. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6819. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6820. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6821. << FixItHint::CreateInsertion(EndLoc, "]");
  6822. } else
  6823. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6824. }
  6825. /// \brief Emit a warning when adding a char literal to a string.
  6826. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  6827. Expr *LHSExpr, Expr *RHSExpr) {
  6828. const Expr *StringRefExpr = LHSExpr;
  6829. const CharacterLiteral *CharExpr =
  6830. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  6831. if (!CharExpr) {
  6832. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  6833. StringRefExpr = RHSExpr;
  6834. }
  6835. if (!CharExpr || !StringRefExpr)
  6836. return;
  6837. const QualType StringType = StringRefExpr->getType();
  6838. // Return if not a PointerType.
  6839. if (!StringType->isAnyPointerType())
  6840. return;
  6841. // Return if not a CharacterType.
  6842. if (!StringType->getPointeeType()->isAnyCharacterType())
  6843. return;
  6844. ASTContext &Ctx = Self.getASTContext();
  6845. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  6846. const QualType CharType = CharExpr->getType();
  6847. if (!CharType->isAnyCharacterType() &&
  6848. CharType->isIntegerType() &&
  6849. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  6850. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6851. << DiagRange << Ctx.CharTy;
  6852. } else {
  6853. Self.Diag(OpLoc, diag::warn_string_plus_char)
  6854. << DiagRange << CharExpr->getType();
  6855. }
  6856. // Only print a fixit for str + char, not for char + str.
  6857. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  6858. SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
  6859. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  6860. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  6861. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  6862. << FixItHint::CreateInsertion(EndLoc, "]");
  6863. } else {
  6864. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  6865. }
  6866. }
  6867. /// \brief Emit error when two pointers are incompatible.
  6868. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  6869. Expr *LHSExpr, Expr *RHSExpr) {
  6870. assert(LHSExpr->getType()->isAnyPointerType());
  6871. assert(RHSExpr->getType()->isAnyPointerType());
  6872. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  6873. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  6874. << RHSExpr->getSourceRange();
  6875. }
  6876. QualType Sema::CheckAdditionOperands( // C99 6.5.6
  6877. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
  6878. QualType* CompLHSTy) {
  6879. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6880. if (LHS.get()->getType()->isVectorType() ||
  6881. RHS.get()->getType()->isVectorType()) {
  6882. QualType compType = CheckVectorOperands(
  6883. LHS, RHS, Loc, CompLHSTy,
  6884. /*AllowBothBool*/getLangOpts().AltiVec,
  6885. /*AllowBoolConversions*/getLangOpts().ZVector);
  6886. if (CompLHSTy) *CompLHSTy = compType;
  6887. return compType;
  6888. }
  6889. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6890. if (LHS.isInvalid() || RHS.isInvalid())
  6891. return QualType();
  6892. // Diagnose "string literal" '+' int and string '+' "char literal".
  6893. if (Opc == BO_Add) {
  6894. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  6895. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  6896. }
  6897. // handle the common case first (both operands are arithmetic).
  6898. if (!compType.isNull() && compType->isArithmeticType()) {
  6899. if (CompLHSTy) *CompLHSTy = compType;
  6900. return compType;
  6901. }
  6902. // Type-checking. Ultimately the pointer's going to be in PExp;
  6903. // note that we bias towards the LHS being the pointer.
  6904. Expr *PExp = LHS.get(), *IExp = RHS.get();
  6905. bool isObjCPointer;
  6906. if (PExp->getType()->isPointerType()) {
  6907. isObjCPointer = false;
  6908. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6909. isObjCPointer = true;
  6910. } else {
  6911. std::swap(PExp, IExp);
  6912. if (PExp->getType()->isPointerType()) {
  6913. isObjCPointer = false;
  6914. } else if (PExp->getType()->isObjCObjectPointerType()) {
  6915. isObjCPointer = true;
  6916. } else {
  6917. return InvalidOperands(Loc, LHS, RHS);
  6918. }
  6919. }
  6920. assert(PExp->getType()->isAnyPointerType());
  6921. if (!IExp->getType()->isIntegerType())
  6922. return InvalidOperands(Loc, LHS, RHS);
  6923. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  6924. return QualType();
  6925. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  6926. return QualType();
  6927. // Check array bounds for pointer arithemtic
  6928. CheckArrayAccess(PExp, IExp);
  6929. if (CompLHSTy) {
  6930. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  6931. if (LHSTy.isNull()) {
  6932. LHSTy = LHS.get()->getType();
  6933. if (LHSTy->isPromotableIntegerType())
  6934. LHSTy = Context.getPromotedIntegerType(LHSTy);
  6935. }
  6936. *CompLHSTy = LHSTy;
  6937. }
  6938. return PExp->getType();
  6939. }
  6940. // C99 6.5.6
  6941. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  6942. SourceLocation Loc,
  6943. QualType* CompLHSTy) {
  6944. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  6945. if (LHS.get()->getType()->isVectorType() ||
  6946. RHS.get()->getType()->isVectorType()) {
  6947. QualType compType = CheckVectorOperands(
  6948. LHS, RHS, Loc, CompLHSTy,
  6949. /*AllowBothBool*/getLangOpts().AltiVec,
  6950. /*AllowBoolConversions*/getLangOpts().ZVector);
  6951. if (CompLHSTy) *CompLHSTy = compType;
  6952. return compType;
  6953. }
  6954. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  6955. if (LHS.isInvalid() || RHS.isInvalid())
  6956. return QualType();
  6957. // Enforce type constraints: C99 6.5.6p3.
  6958. // Handle the common case first (both operands are arithmetic).
  6959. if (!compType.isNull() && compType->isArithmeticType()) {
  6960. if (CompLHSTy) *CompLHSTy = compType;
  6961. return compType;
  6962. }
  6963. // Either ptr - int or ptr - ptr.
  6964. if (LHS.get()->getType()->isAnyPointerType()) {
  6965. QualType lpointee = LHS.get()->getType()->getPointeeType();
  6966. // Diagnose bad cases where we step over interface counts.
  6967. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  6968. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  6969. return QualType();
  6970. // The result type of a pointer-int computation is the pointer type.
  6971. if (RHS.get()->getType()->isIntegerType()) {
  6972. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  6973. return QualType();
  6974. // Check array bounds for pointer arithemtic
  6975. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  6976. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  6977. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  6978. return LHS.get()->getType();
  6979. }
  6980. // Handle pointer-pointer subtractions.
  6981. if (const PointerType *RHSPTy
  6982. = RHS.get()->getType()->getAs<PointerType>()) {
  6983. QualType rpointee = RHSPTy->getPointeeType();
  6984. if (getLangOpts().CPlusPlus) {
  6985. // Pointee types must be the same: C++ [expr.add]
  6986. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  6987. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6988. }
  6989. } else {
  6990. // Pointee types must be compatible C99 6.5.6p3
  6991. if (!Context.typesAreCompatible(
  6992. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  6993. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  6994. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  6995. return QualType();
  6996. }
  6997. }
  6998. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  6999. LHS.get(), RHS.get()))
  7000. return QualType();
  7001. // The pointee type may have zero size. As an extension, a structure or
  7002. // union may have zero size or an array may have zero length. In this
  7003. // case subtraction does not make sense.
  7004. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7005. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7006. if (ElementSize.isZero()) {
  7007. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7008. << rpointee.getUnqualifiedType()
  7009. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7010. }
  7011. }
  7012. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7013. return Context.getPointerDiffType();
  7014. }
  7015. }
  7016. return InvalidOperands(Loc, LHS, RHS);
  7017. }
  7018. static bool isScopedEnumerationType(QualType T) {
  7019. if (const EnumType *ET = T->getAs<EnumType>())
  7020. return ET->getDecl()->isScoped();
  7021. return false;
  7022. }
  7023. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  7024. SourceLocation Loc, unsigned Opc,
  7025. QualType LHSType) {
  7026. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  7027. // so skip remaining warnings as we don't want to modify values within Sema.
  7028. if (S.getLangOpts().OpenCL)
  7029. return;
  7030. llvm::APSInt Right;
  7031. // Check right/shifter operand
  7032. if (RHS.get()->isValueDependent() ||
  7033. !RHS.get()->EvaluateAsInt(Right, S.Context))
  7034. return;
  7035. if (Right.isNegative()) {
  7036. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7037. S.PDiag(diag::warn_shift_negative)
  7038. << RHS.get()->getSourceRange());
  7039. return;
  7040. }
  7041. llvm::APInt LeftBits(Right.getBitWidth(),
  7042. S.Context.getTypeSize(LHS.get()->getType()));
  7043. if (Right.uge(LeftBits)) {
  7044. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7045. S.PDiag(diag::warn_shift_gt_typewidth)
  7046. << RHS.get()->getSourceRange());
  7047. return;
  7048. }
  7049. if (Opc != BO_Shl)
  7050. return;
  7051. // When left shifting an ICE which is signed, we can check for overflow which
  7052. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  7053. // integers have defined behavior modulo one more than the maximum value
  7054. // representable in the result type, so never warn for those.
  7055. llvm::APSInt Left;
  7056. if (LHS.get()->isValueDependent() ||
  7057. LHSType->hasUnsignedIntegerRepresentation() ||
  7058. !LHS.get()->EvaluateAsInt(Left, S.Context))
  7059. return;
  7060. // If LHS does not have a signed type and non-negative value
  7061. // then, the behavior is undefined. Warn about it.
  7062. if (Left.isNegative()) {
  7063. S.DiagRuntimeBehavior(Loc, LHS.get(),
  7064. S.PDiag(diag::warn_shift_lhs_negative)
  7065. << LHS.get()->getSourceRange());
  7066. return;
  7067. }
  7068. llvm::APInt ResultBits =
  7069. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  7070. if (LeftBits.uge(ResultBits))
  7071. return;
  7072. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  7073. Result = Result.shl(Right);
  7074. // Print the bit representation of the signed integer as an unsigned
  7075. // hexadecimal number.
  7076. SmallString<40> HexResult;
  7077. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  7078. // If we are only missing a sign bit, this is less likely to result in actual
  7079. // bugs -- if the result is cast back to an unsigned type, it will have the
  7080. // expected value. Thus we place this behind a different warning that can be
  7081. // turned off separately if needed.
  7082. if (LeftBits == ResultBits - 1) {
  7083. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  7084. << HexResult << LHSType
  7085. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7086. return;
  7087. }
  7088. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  7089. << HexResult.str() << Result.getMinSignedBits() << LHSType
  7090. << Left.getBitWidth() << LHS.get()->getSourceRange()
  7091. << RHS.get()->getSourceRange();
  7092. }
  7093. /// \brief Return the resulting type when an OpenCL vector is shifted
  7094. /// by a scalar or vector shift amount.
  7095. static QualType checkOpenCLVectorShift(Sema &S,
  7096. ExprResult &LHS, ExprResult &RHS,
  7097. SourceLocation Loc, bool IsCompAssign) {
  7098. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  7099. if (!LHS.get()->getType()->isVectorType()) {
  7100. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  7101. << RHS.get()->getType() << LHS.get()->getType()
  7102. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7103. return QualType();
  7104. }
  7105. if (!IsCompAssign) {
  7106. LHS = S.UsualUnaryConversions(LHS.get());
  7107. if (LHS.isInvalid()) return QualType();
  7108. }
  7109. RHS = S.UsualUnaryConversions(RHS.get());
  7110. if (RHS.isInvalid()) return QualType();
  7111. QualType LHSType = LHS.get()->getType();
  7112. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  7113. QualType LHSEleType = LHSVecTy->getElementType();
  7114. // Note that RHS might not be a vector.
  7115. QualType RHSType = RHS.get()->getType();
  7116. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  7117. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  7118. // OpenCL v1.1 s6.3.j says that the operands need to be integers.
  7119. if (!LHSEleType->isIntegerType()) {
  7120. S.Diag(Loc, diag::err_typecheck_expect_int)
  7121. << LHS.get()->getType() << LHS.get()->getSourceRange();
  7122. return QualType();
  7123. }
  7124. if (!RHSEleType->isIntegerType()) {
  7125. S.Diag(Loc, diag::err_typecheck_expect_int)
  7126. << RHS.get()->getType() << RHS.get()->getSourceRange();
  7127. return QualType();
  7128. }
  7129. if (RHSVecTy) {
  7130. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  7131. // are applied component-wise. So if RHS is a vector, then ensure
  7132. // that the number of elements is the same as LHS...
  7133. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  7134. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  7135. << LHS.get()->getType() << RHS.get()->getType()
  7136. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7137. return QualType();
  7138. }
  7139. } else {
  7140. // ...else expand RHS to match the number of elements in LHS.
  7141. QualType VecTy =
  7142. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  7143. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  7144. }
  7145. return LHSType;
  7146. }
  7147. // C99 6.5.7
  7148. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  7149. SourceLocation Loc, unsigned Opc,
  7150. bool IsCompAssign) {
  7151. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7152. // Vector shifts promote their scalar inputs to vector type.
  7153. if (LHS.get()->getType()->isVectorType() ||
  7154. RHS.get()->getType()->isVectorType()) {
  7155. if (LangOpts.OpenCL)
  7156. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7157. if (LangOpts.ZVector) {
  7158. // The shift operators for the z vector extensions work basically
  7159. // like OpenCL shifts, except that neither the LHS nor the RHS is
  7160. // allowed to be a "vector bool".
  7161. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  7162. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7163. return InvalidOperands(Loc, LHS, RHS);
  7164. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  7165. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7166. return InvalidOperands(Loc, LHS, RHS);
  7167. return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  7168. }
  7169. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7170. /*AllowBothBool*/true,
  7171. /*AllowBoolConversions*/false);
  7172. }
  7173. // Shifts don't perform usual arithmetic conversions, they just do integer
  7174. // promotions on each operand. C99 6.5.7p3
  7175. // For the LHS, do usual unary conversions, but then reset them away
  7176. // if this is a compound assignment.
  7177. ExprResult OldLHS = LHS;
  7178. LHS = UsualUnaryConversions(LHS.get());
  7179. if (LHS.isInvalid())
  7180. return QualType();
  7181. QualType LHSType = LHS.get()->getType();
  7182. if (IsCompAssign) LHS = OldLHS;
  7183. // The RHS is simpler.
  7184. RHS = UsualUnaryConversions(RHS.get());
  7185. if (RHS.isInvalid())
  7186. return QualType();
  7187. QualType RHSType = RHS.get()->getType();
  7188. // C99 6.5.7p2: Each of the operands shall have integer type.
  7189. if (!LHSType->hasIntegerRepresentation() ||
  7190. !RHSType->hasIntegerRepresentation())
  7191. return InvalidOperands(Loc, LHS, RHS);
  7192. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  7193. // hasIntegerRepresentation() above instead of this.
  7194. if (isScopedEnumerationType(LHSType) ||
  7195. isScopedEnumerationType(RHSType)) {
  7196. return InvalidOperands(Loc, LHS, RHS);
  7197. }
  7198. // Sanity-check shift operands
  7199. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  7200. // "The type of the result is that of the promoted left operand."
  7201. return LHSType;
  7202. }
  7203. static bool IsWithinTemplateSpecialization(Decl *D) {
  7204. if (DeclContext *DC = D->getDeclContext()) {
  7205. if (isa<ClassTemplateSpecializationDecl>(DC))
  7206. return true;
  7207. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  7208. return FD->isFunctionTemplateSpecialization();
  7209. }
  7210. return false;
  7211. }
  7212. /// If two different enums are compared, raise a warning.
  7213. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  7214. Expr *RHS) {
  7215. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  7216. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  7217. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  7218. if (!LHSEnumType)
  7219. return;
  7220. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  7221. if (!RHSEnumType)
  7222. return;
  7223. // Ignore anonymous enums.
  7224. if (!LHSEnumType->getDecl()->getIdentifier())
  7225. return;
  7226. if (!RHSEnumType->getDecl()->getIdentifier())
  7227. return;
  7228. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  7229. return;
  7230. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  7231. << LHSStrippedType << RHSStrippedType
  7232. << LHS->getSourceRange() << RHS->getSourceRange();
  7233. }
  7234. /// \brief Diagnose bad pointer comparisons.
  7235. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  7236. ExprResult &LHS, ExprResult &RHS,
  7237. bool IsError) {
  7238. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  7239. : diag::ext_typecheck_comparison_of_distinct_pointers)
  7240. << LHS.get()->getType() << RHS.get()->getType()
  7241. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7242. }
  7243. /// \brief Returns false if the pointers are converted to a composite type,
  7244. /// true otherwise.
  7245. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  7246. ExprResult &LHS, ExprResult &RHS) {
  7247. // C++ [expr.rel]p2:
  7248. // [...] Pointer conversions (4.10) and qualification
  7249. // conversions (4.4) are performed on pointer operands (or on
  7250. // a pointer operand and a null pointer constant) to bring
  7251. // them to their composite pointer type. [...]
  7252. //
  7253. // C++ [expr.eq]p1 uses the same notion for (in)equality
  7254. // comparisons of pointers.
  7255. // C++ [expr.eq]p2:
  7256. // In addition, pointers to members can be compared, or a pointer to
  7257. // member and a null pointer constant. Pointer to member conversions
  7258. // (4.11) and qualification conversions (4.4) are performed to bring
  7259. // them to a common type. If one operand is a null pointer constant,
  7260. // the common type is the type of the other operand. Otherwise, the
  7261. // common type is a pointer to member type similar (4.4) to the type
  7262. // of one of the operands, with a cv-qualification signature (4.4)
  7263. // that is the union of the cv-qualification signatures of the operand
  7264. // types.
  7265. QualType LHSType = LHS.get()->getType();
  7266. QualType RHSType = RHS.get()->getType();
  7267. assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
  7268. (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
  7269. bool NonStandardCompositeType = false;
  7270. bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
  7271. QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
  7272. if (T.isNull()) {
  7273. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  7274. return true;
  7275. }
  7276. if (NonStandardCompositeType)
  7277. S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
  7278. << LHSType << RHSType << T << LHS.get()->getSourceRange()
  7279. << RHS.get()->getSourceRange();
  7280. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  7281. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  7282. return false;
  7283. }
  7284. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  7285. ExprResult &LHS,
  7286. ExprResult &RHS,
  7287. bool IsError) {
  7288. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  7289. : diag::ext_typecheck_comparison_of_fptr_to_void)
  7290. << LHS.get()->getType() << RHS.get()->getType()
  7291. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7292. }
  7293. static bool isObjCObjectLiteral(ExprResult &E) {
  7294. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  7295. case Stmt::ObjCArrayLiteralClass:
  7296. case Stmt::ObjCDictionaryLiteralClass:
  7297. case Stmt::ObjCStringLiteralClass:
  7298. case Stmt::ObjCBoxedExprClass:
  7299. return true;
  7300. default:
  7301. // Note that ObjCBoolLiteral is NOT an object literal!
  7302. return false;
  7303. }
  7304. }
  7305. #if 1 // HLSL Change Starts
  7306. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7307. return LK_None;
  7308. }
  7309. #else
  7310. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  7311. const ObjCObjectPointerType *Type =
  7312. LHS->getType()->getAs<ObjCObjectPointerType>();
  7313. // If this is not actually an Objective-C object, bail out.
  7314. if (!Type)
  7315. return false;
  7316. // Get the LHS object's interface type.
  7317. QualType InterfaceType = Type->getPointeeType();
  7318. // If the RHS isn't an Objective-C object, bail out.
  7319. if (!RHS->getType()->isObjCObjectPointerType())
  7320. return false;
  7321. // Try to find the -isEqual: method.
  7322. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  7323. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  7324. InterfaceType,
  7325. /*instance=*/true);
  7326. if (!Method) {
  7327. if (Type->isObjCIdType()) {
  7328. // For 'id', just check the global pool.
  7329. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  7330. /*receiverId=*/true);
  7331. } else {
  7332. // Check protocols.
  7333. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  7334. /*instance=*/true);
  7335. }
  7336. }
  7337. if (!Method)
  7338. return false;
  7339. QualType T = Method->parameters()[0]->getType();
  7340. if (!T->isObjCObjectPointerType())
  7341. return false;
  7342. QualType R = Method->getReturnType();
  7343. if (!R->isScalarType())
  7344. return false;
  7345. return true;
  7346. }
  7347. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  7348. FromE = FromE->IgnoreParenImpCasts();
  7349. switch (FromE->getStmtClass()) {
  7350. default:
  7351. break;
  7352. case Stmt::ObjCStringLiteralClass:
  7353. // "string literal"
  7354. return LK_String;
  7355. case Stmt::ObjCArrayLiteralClass:
  7356. // "array literal"
  7357. return LK_Array;
  7358. case Stmt::ObjCDictionaryLiteralClass:
  7359. // "dictionary literal"
  7360. return LK_Dictionary;
  7361. case Stmt::BlockExprClass:
  7362. return LK_Block;
  7363. case Stmt::ObjCBoxedExprClass: {
  7364. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  7365. switch (Inner->getStmtClass()) {
  7366. case Stmt::IntegerLiteralClass:
  7367. case Stmt::FloatingLiteralClass:
  7368. case Stmt::CharacterLiteralClass:
  7369. case Stmt::ObjCBoolLiteralExprClass:
  7370. case Stmt::CXXBoolLiteralExprClass:
  7371. // "numeric literal"
  7372. return LK_Numeric;
  7373. case Stmt::ImplicitCastExprClass: {
  7374. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  7375. // Boolean literals can be represented by implicit casts.
  7376. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  7377. return LK_Numeric;
  7378. break;
  7379. }
  7380. default:
  7381. break;
  7382. }
  7383. return LK_Boxed;
  7384. }
  7385. }
  7386. return LK_None;
  7387. }
  7388. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  7389. ExprResult &LHS, ExprResult &RHS,
  7390. BinaryOperator::Opcode Opc){
  7391. Expr *Literal;
  7392. Expr *Other;
  7393. if (isObjCObjectLiteral(LHS)) {
  7394. Literal = LHS.get();
  7395. Other = RHS.get();
  7396. } else {
  7397. Literal = RHS.get();
  7398. Other = LHS.get();
  7399. }
  7400. // Don't warn on comparisons against nil.
  7401. Other = Other->IgnoreParenCasts();
  7402. if (Other->isNullPointerConstant(S.getASTContext(),
  7403. Expr::NPC_ValueDependentIsNotNull))
  7404. return;
  7405. // This should be kept in sync with warn_objc_literal_comparison.
  7406. // LK_String should always be after the other literals, since it has its own
  7407. // warning flag.
  7408. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  7409. assert(LiteralKind != Sema::LK_Block);
  7410. if (LiteralKind == Sema::LK_None) {
  7411. llvm_unreachable("Unknown Objective-C object literal kind");
  7412. }
  7413. if (LiteralKind == Sema::LK_String)
  7414. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  7415. << Literal->getSourceRange();
  7416. else
  7417. S.Diag(Loc, diag::warn_objc_literal_comparison)
  7418. << LiteralKind << Literal->getSourceRange();
  7419. if (BinaryOperator::isEqualityOp(Opc) &&
  7420. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  7421. SourceLocation Start = LHS.get()->getLocStart();
  7422. SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  7423. CharSourceRange OpRange =
  7424. CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
  7425. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  7426. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  7427. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  7428. << FixItHint::CreateInsertion(End, "]");
  7429. }
  7430. }
  7431. #endif // HLSL Change Ends
  7432. static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
  7433. ExprResult &RHS,
  7434. SourceLocation Loc,
  7435. unsigned OpaqueOpc) {
  7436. // This checking requires bools.
  7437. if (!S.getLangOpts().Bool) return;
  7438. // Check that left hand side is !something.
  7439. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  7440. if (!UO || UO->getOpcode() != UO_LNot) return;
  7441. // Only check if the right hand side is non-bool arithmetic type.
  7442. if (RHS.get()->getType()->isBooleanType()) return;
  7443. // Make sure that the something in !something is not bool.
  7444. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  7445. if (SubExpr->getType()->isBooleanType()) return;
  7446. // Emit warning.
  7447. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
  7448. << Loc;
  7449. // First note suggest !(x < y)
  7450. SourceLocation FirstOpen = SubExpr->getLocStart();
  7451. SourceLocation FirstClose = RHS.get()->getLocEnd();
  7452. FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
  7453. if (FirstClose.isInvalid())
  7454. FirstOpen = SourceLocation();
  7455. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  7456. << FixItHint::CreateInsertion(FirstOpen, "(")
  7457. << FixItHint::CreateInsertion(FirstClose, ")");
  7458. // Second note suggests (!x) < y
  7459. SourceLocation SecondOpen = LHS.get()->getLocStart();
  7460. SourceLocation SecondClose = LHS.get()->getLocEnd();
  7461. SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
  7462. if (SecondClose.isInvalid())
  7463. SecondOpen = SourceLocation();
  7464. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  7465. << FixItHint::CreateInsertion(SecondOpen, "(")
  7466. << FixItHint::CreateInsertion(SecondClose, ")");
  7467. }
  7468. // Get the decl for a simple expression: a reference to a variable,
  7469. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  7470. static ValueDecl *getCompareDecl(Expr *E) {
  7471. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  7472. return DR->getDecl();
  7473. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  7474. if (Ivar->isFreeIvar())
  7475. return Ivar->getDecl();
  7476. }
  7477. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  7478. if (Mem->isImplicitAccess())
  7479. return Mem->getMemberDecl();
  7480. }
  7481. return nullptr;
  7482. }
  7483. // C99 6.5.8, C++ [expr.rel]
  7484. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7485. SourceLocation Loc, unsigned OpaqueOpc,
  7486. bool IsRelational) {
  7487. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  7488. BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
  7489. // Handle vector comparisons separately.
  7490. if (LHS.get()->getType()->isVectorType() ||
  7491. RHS.get()->getType()->isVectorType())
  7492. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  7493. QualType LHSType = LHS.get()->getType();
  7494. QualType RHSType = RHS.get()->getType();
  7495. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  7496. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  7497. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  7498. diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
  7499. if (!LHSType->hasFloatingRepresentation() &&
  7500. !(LHSType->isBlockPointerType() && IsRelational) &&
  7501. !LHS.get()->getLocStart().isMacroID() &&
  7502. !RHS.get()->getLocStart().isMacroID() &&
  7503. ActiveTemplateInstantiations.empty()) {
  7504. // For non-floating point types, check for self-comparisons of the form
  7505. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7506. // often indicate logic errors in the program.
  7507. //
  7508. // NOTE: Don't warn about comparison expressions resulting from macro
  7509. // expansion. Also don't warn about comparisons which are only self
  7510. // comparisons within a template specialization. The warnings should catch
  7511. // obvious cases in the definition of the template anyways. The idea is to
  7512. // warn when the typed comparison operator will always evaluate to the same
  7513. // result.
  7514. ValueDecl *DL = getCompareDecl(LHSStripped);
  7515. ValueDecl *DR = getCompareDecl(RHSStripped);
  7516. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  7517. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7518. << 0 // self-
  7519. << (Opc == BO_EQ
  7520. || Opc == BO_LE
  7521. || Opc == BO_GE));
  7522. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  7523. !DL->getType()->isReferenceType() &&
  7524. !DR->getType()->isReferenceType()) {
  7525. // what is it always going to eval to?
  7526. char always_evals_to;
  7527. switch(Opc) {
  7528. case BO_EQ: // e.g. array1 == array2
  7529. always_evals_to = 0; // false
  7530. break;
  7531. case BO_NE: // e.g. array1 != array2
  7532. always_evals_to = 1; // true
  7533. break;
  7534. default:
  7535. // best we can say is 'a constant'
  7536. always_evals_to = 2; // e.g. array1 <= array2
  7537. break;
  7538. }
  7539. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  7540. << 1 // array
  7541. << always_evals_to);
  7542. }
  7543. if (isa<CastExpr>(LHSStripped))
  7544. LHSStripped = LHSStripped->IgnoreParenCasts();
  7545. if (isa<CastExpr>(RHSStripped))
  7546. RHSStripped = RHSStripped->IgnoreParenCasts();
  7547. // Warn about comparisons against a string constant (unless the other
  7548. // operand is null), the user probably wants strcmp.
  7549. Expr *literalString = nullptr;
  7550. Expr *literalStringStripped = nullptr;
  7551. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  7552. !RHSStripped->isNullPointerConstant(Context,
  7553. Expr::NPC_ValueDependentIsNull)) {
  7554. literalString = LHS.get();
  7555. literalStringStripped = LHSStripped;
  7556. } else if ((isa<StringLiteral>(RHSStripped) ||
  7557. isa<ObjCEncodeExpr>(RHSStripped)) &&
  7558. !LHSStripped->isNullPointerConstant(Context,
  7559. Expr::NPC_ValueDependentIsNull)) {
  7560. literalString = RHS.get();
  7561. literalStringStripped = RHSStripped;
  7562. }
  7563. if (literalString) {
  7564. DiagRuntimeBehavior(Loc, nullptr,
  7565. PDiag(diag::warn_stringcompare)
  7566. << isa<ObjCEncodeExpr>(literalStringStripped)
  7567. << literalString->getSourceRange());
  7568. }
  7569. }
  7570. // C99 6.5.8p3 / C99 6.5.9p4
  7571. UsualArithmeticConversions(LHS, RHS);
  7572. if (LHS.isInvalid() || RHS.isInvalid())
  7573. return QualType();
  7574. LHSType = LHS.get()->getType();
  7575. RHSType = RHS.get()->getType();
  7576. // The result of comparisons is 'bool' in C++, 'int' in C.
  7577. QualType ResultTy = Context.getLogicalOperationType();
  7578. if (IsRelational) {
  7579. if (LHSType->isRealType() && RHSType->isRealType())
  7580. return ResultTy;
  7581. } else {
  7582. // Check for comparisons of floating point operands using != and ==.
  7583. if (LHSType->hasFloatingRepresentation())
  7584. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7585. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  7586. return ResultTy;
  7587. }
  7588. const Expr::NullPointerConstantKind LHSNullKind =
  7589. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7590. const Expr::NullPointerConstantKind RHSNullKind =
  7591. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  7592. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  7593. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  7594. if (!IsRelational && LHSIsNull != RHSIsNull) {
  7595. bool IsEquality = Opc == BO_EQ;
  7596. if (RHSIsNull)
  7597. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  7598. RHS.get()->getSourceRange());
  7599. else
  7600. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  7601. LHS.get()->getSourceRange());
  7602. }
  7603. // All of the following pointer-related warnings are GCC extensions, except
  7604. // when handling null pointer constants.
  7605. if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
  7606. QualType LCanPointeeTy =
  7607. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7608. QualType RCanPointeeTy =
  7609. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  7610. if (getLangOpts().CPlusPlus) {
  7611. if (LCanPointeeTy == RCanPointeeTy)
  7612. return ResultTy;
  7613. if (!IsRelational &&
  7614. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7615. // Valid unless comparison between non-null pointer and function pointer
  7616. // This is a gcc extension compatibility comparison.
  7617. // In a SFINAE context, we treat this as a hard error to maintain
  7618. // conformance with the C++ standard.
  7619. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7620. && !LHSIsNull && !RHSIsNull) {
  7621. diagnoseFunctionPointerToVoidComparison(
  7622. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  7623. if (isSFINAEContext())
  7624. return QualType();
  7625. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7626. return ResultTy;
  7627. }
  7628. }
  7629. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7630. return QualType();
  7631. else
  7632. return ResultTy;
  7633. }
  7634. // C99 6.5.9p2 and C99 6.5.8p2
  7635. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  7636. RCanPointeeTy.getUnqualifiedType())) {
  7637. // Valid unless a relational comparison of function pointers
  7638. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  7639. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  7640. << LHSType << RHSType << LHS.get()->getSourceRange()
  7641. << RHS.get()->getSourceRange();
  7642. }
  7643. } else if (!IsRelational &&
  7644. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  7645. // Valid unless comparison between non-null pointer and function pointer
  7646. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  7647. && !LHSIsNull && !RHSIsNull)
  7648. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  7649. /*isError*/false);
  7650. } else {
  7651. // Invalid
  7652. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  7653. }
  7654. if (LCanPointeeTy != RCanPointeeTy) {
  7655. const PointerType *lhsPtr = LHSType->getAs<PointerType>();
  7656. if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  7657. Diag(Loc,
  7658. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7659. << LHSType << RHSType << 0 /* comparison */
  7660. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7661. }
  7662. unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
  7663. unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
  7664. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  7665. : CK_BitCast;
  7666. if (LHSIsNull && !RHSIsNull)
  7667. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  7668. else
  7669. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  7670. }
  7671. return ResultTy;
  7672. }
  7673. if (getLangOpts().CPlusPlus) {
  7674. // Comparison of nullptr_t with itself.
  7675. if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
  7676. return ResultTy;
  7677. // Comparison of pointers with null pointer constants and equality
  7678. // comparisons of member pointers to null pointer constants.
  7679. if (RHSIsNull &&
  7680. ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
  7681. (!IsRelational &&
  7682. (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
  7683. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7684. LHSType->isMemberPointerType()
  7685. ? CK_NullToMemberPointer
  7686. : CK_NullToPointer);
  7687. return ResultTy;
  7688. }
  7689. if (LHSIsNull &&
  7690. ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
  7691. (!IsRelational &&
  7692. (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
  7693. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7694. RHSType->isMemberPointerType()
  7695. ? CK_NullToMemberPointer
  7696. : CK_NullToPointer);
  7697. return ResultTy;
  7698. }
  7699. // Comparison of member pointers.
  7700. if (!IsRelational &&
  7701. LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
  7702. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  7703. return QualType();
  7704. else
  7705. return ResultTy;
  7706. }
  7707. // Handle scoped enumeration types specifically, since they don't promote
  7708. // to integers.
  7709. if (LHS.get()->getType()->isEnumeralType() &&
  7710. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  7711. RHS.get()->getType()))
  7712. return ResultTy;
  7713. }
  7714. // Handle block pointer types.
  7715. if (!IsRelational && LHSType->isBlockPointerType() &&
  7716. RHSType->isBlockPointerType()) {
  7717. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  7718. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  7719. if (!LHSIsNull && !RHSIsNull &&
  7720. !Context.typesAreCompatible(lpointee, rpointee)) {
  7721. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7722. << LHSType << RHSType << LHS.get()->getSourceRange()
  7723. << RHS.get()->getSourceRange();
  7724. }
  7725. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7726. return ResultTy;
  7727. }
  7728. // Allow block pointers to be compared with null pointer constants.
  7729. if (!IsRelational
  7730. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  7731. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  7732. if (!LHSIsNull && !RHSIsNull) {
  7733. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  7734. ->getPointeeType()->isVoidType())
  7735. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  7736. ->getPointeeType()->isVoidType())))
  7737. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  7738. << LHSType << RHSType << LHS.get()->getSourceRange()
  7739. << RHS.get()->getSourceRange();
  7740. }
  7741. if (LHSIsNull && !RHSIsNull)
  7742. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7743. RHSType->isPointerType() ? CK_BitCast
  7744. : CK_AnyPointerToBlockPointerCast);
  7745. else
  7746. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7747. LHSType->isPointerType() ? CK_BitCast
  7748. : CK_AnyPointerToBlockPointerCast);
  7749. return ResultTy;
  7750. }
  7751. if (LHSType->isObjCObjectPointerType() ||
  7752. RHSType->isObjCObjectPointerType()) {
  7753. const PointerType *LPT = LHSType->getAs<PointerType>();
  7754. const PointerType *RPT = RHSType->getAs<PointerType>();
  7755. if (LPT || RPT) {
  7756. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  7757. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  7758. if (!LPtrToVoid && !RPtrToVoid &&
  7759. !Context.typesAreCompatible(LHSType, RHSType)) {
  7760. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7761. /*isError*/false);
  7762. }
  7763. if (LHSIsNull && !RHSIsNull) {
  7764. Expr *E = LHS.get();
  7765. #if 0 // HLSL Change - no ObjC support
  7766. if (getLangOpts().ObjCAutoRefCount)
  7767. CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
  7768. #endif // HLSL Change
  7769. LHS = ImpCastExprToType(E, RHSType,
  7770. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7771. }
  7772. else {
  7773. Expr *E = RHS.get();
  7774. #if 0 // HLSL Change - no ObjC support
  7775. if (getLangOpts().ObjCAutoRefCount)
  7776. CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
  7777. Opc);
  7778. #endif // HLSL Change
  7779. RHS = ImpCastExprToType(E, LHSType,
  7780. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  7781. }
  7782. return ResultTy;
  7783. }
  7784. #if 0 // HLSL Change - no ObjC support
  7785. if (LHSType->isObjCObjectPointerType() &&
  7786. RHSType->isObjCObjectPointerType()) {
  7787. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  7788. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  7789. /*isError*/false);
  7790. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  7791. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  7792. if (LHSIsNull && !RHSIsNull)
  7793. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7794. else
  7795. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7796. return ResultTy;
  7797. }
  7798. #endif // HLSL Change
  7799. }
  7800. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  7801. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  7802. unsigned DiagID = 0;
  7803. bool isError = false;
  7804. if (LangOpts.DebuggerSupport) {
  7805. // Under a debugger, allow the comparison of pointers to integers,
  7806. // since users tend to want to compare addresses.
  7807. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  7808. (RHSIsNull && RHSType->isIntegerType())) {
  7809. if (IsRelational && !getLangOpts().CPlusPlus)
  7810. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  7811. } else if (IsRelational && !getLangOpts().CPlusPlus)
  7812. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  7813. else if (getLangOpts().CPlusPlus) {
  7814. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  7815. isError = true;
  7816. } else
  7817. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  7818. if (DiagID) {
  7819. Diag(Loc, DiagID)
  7820. << LHSType << RHSType << LHS.get()->getSourceRange()
  7821. << RHS.get()->getSourceRange();
  7822. if (isError)
  7823. return QualType();
  7824. }
  7825. if (LHSType->isIntegerType())
  7826. LHS = ImpCastExprToType(LHS.get(), RHSType,
  7827. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7828. else
  7829. RHS = ImpCastExprToType(RHS.get(), LHSType,
  7830. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  7831. return ResultTy;
  7832. }
  7833. // Handle block pointers.
  7834. if (!IsRelational && RHSIsNull
  7835. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  7836. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7837. return ResultTy;
  7838. }
  7839. if (!IsRelational && LHSIsNull
  7840. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  7841. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  7842. return ResultTy;
  7843. }
  7844. return InvalidOperands(Loc, LHS, RHS);
  7845. }
  7846. // Return a signed type that is of identical size and number of elements.
  7847. // For floating point vectors, return an integer type of identical size
  7848. // and number of elements.
  7849. QualType Sema::GetSignedVectorType(QualType V) {
  7850. const VectorType *VTy = V->getAs<VectorType>();
  7851. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  7852. if (TypeSize == Context.getTypeSize(Context.CharTy))
  7853. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  7854. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  7855. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  7856. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  7857. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  7858. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  7859. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  7860. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  7861. "Unhandled vector element size in vector compare");
  7862. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  7863. }
  7864. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  7865. /// operates on extended vector types. Instead of producing an IntTy result,
  7866. /// like a scalar comparison, a vector comparison produces a vector of integer
  7867. /// types.
  7868. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  7869. SourceLocation Loc,
  7870. bool IsRelational) {
  7871. // Check to make sure we're operating on vectors of the same type and width,
  7872. // Allowing one side to be a scalar of element type.
  7873. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  7874. /*AllowBothBool*/true,
  7875. /*AllowBoolConversions*/getLangOpts().ZVector);
  7876. if (vType.isNull())
  7877. return vType;
  7878. QualType LHSType = LHS.get()->getType();
  7879. // If AltiVec, the comparison results in a numeric type, i.e.
  7880. // bool for C++, int for C
  7881. if (getLangOpts().AltiVec &&
  7882. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  7883. return Context.getLogicalOperationType();
  7884. // For non-floating point types, check for self-comparisons of the form
  7885. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  7886. // often indicate logic errors in the program.
  7887. if (!LHSType->hasFloatingRepresentation() &&
  7888. ActiveTemplateInstantiations.empty()) {
  7889. if (DeclRefExpr* DRL
  7890. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  7891. if (DeclRefExpr* DRR
  7892. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  7893. if (DRL->getDecl() == DRR->getDecl())
  7894. DiagRuntimeBehavior(Loc, nullptr,
  7895. PDiag(diag::warn_comparison_always)
  7896. << 0 // self-
  7897. << 2 // "a constant"
  7898. );
  7899. }
  7900. // Check for comparisons of floating point operands using != and ==.
  7901. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  7902. assert (RHS.get()->getType()->hasFloatingRepresentation());
  7903. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  7904. }
  7905. // Return a signed type for the vector.
  7906. return GetSignedVectorType(LHSType);
  7907. }
  7908. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  7909. SourceLocation Loc) {
  7910. // Ensure that either both operands are of the same vector type, or
  7911. // one operand is of a vector type and the other is of its element type.
  7912. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  7913. /*AllowBothBool*/true,
  7914. /*AllowBoolConversions*/false);
  7915. if (vType.isNull())
  7916. return InvalidOperands(Loc, LHS, RHS);
  7917. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  7918. vType->hasFloatingRepresentation())
  7919. return InvalidOperands(Loc, LHS, RHS);
  7920. return GetSignedVectorType(LHS.get()->getType());
  7921. }
  7922. inline QualType Sema::CheckBitwiseOperands(
  7923. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7924. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7925. if (LHS.get()->getType()->isVectorType() ||
  7926. RHS.get()->getType()->isVectorType()) {
  7927. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7928. RHS.get()->getType()->hasIntegerRepresentation())
  7929. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7930. /*AllowBothBool*/true,
  7931. /*AllowBoolConversions*/getLangOpts().ZVector);
  7932. return InvalidOperands(Loc, LHS, RHS);
  7933. }
  7934. ExprResult LHSResult = LHS, RHSResult = RHS;
  7935. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  7936. IsCompAssign);
  7937. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  7938. return QualType();
  7939. LHS = LHSResult.get();
  7940. RHS = RHSResult.get();
  7941. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  7942. return compType;
  7943. return InvalidOperands(Loc, LHS, RHS);
  7944. }
  7945. inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
  7946. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  7947. // Check vector operands differently.
  7948. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  7949. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  7950. // Diagnose cases where the user write a logical and/or but probably meant a
  7951. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  7952. // is a constant.
  7953. if (LHS.get()->getType()->isIntegerType() &&
  7954. !LHS.get()->getType()->isBooleanType() &&
  7955. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  7956. // Don't warn in macros or template instantiations.
  7957. !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
  7958. // If the RHS can be constant folded, and if it constant folds to something
  7959. // that isn't 0 or 1 (which indicate a potential logical operation that
  7960. // happened to fold to true/false) then warn.
  7961. // Parens on the RHS are ignored.
  7962. llvm::APSInt Result;
  7963. if (RHS.get()->EvaluateAsInt(Result, Context))
  7964. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  7965. !RHS.get()->getExprLoc().isMacroID()) ||
  7966. (Result != 0 && Result != 1)) {
  7967. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  7968. << RHS.get()->getSourceRange()
  7969. << (Opc == BO_LAnd ? "&&" : "||");
  7970. // Suggest replacing the logical operator with the bitwise version
  7971. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  7972. << (Opc == BO_LAnd ? "&" : "|")
  7973. << FixItHint::CreateReplacement(SourceRange(
  7974. Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
  7975. getLangOpts())),
  7976. Opc == BO_LAnd ? "&" : "|");
  7977. if (Opc == BO_LAnd)
  7978. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  7979. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  7980. << FixItHint::CreateRemoval(
  7981. SourceRange(
  7982. Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
  7983. 0, getSourceManager(),
  7984. getLangOpts()),
  7985. RHS.get()->getLocEnd()));
  7986. }
  7987. }
  7988. if (!Context.getLangOpts().CPlusPlus) {
  7989. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  7990. // not operate on the built-in scalar and vector float types.
  7991. if (Context.getLangOpts().OpenCL &&
  7992. Context.getLangOpts().OpenCLVersion < 120) {
  7993. if (LHS.get()->getType()->isFloatingType() ||
  7994. RHS.get()->getType()->isFloatingType())
  7995. return InvalidOperands(Loc, LHS, RHS);
  7996. }
  7997. LHS = UsualUnaryConversions(LHS.get());
  7998. if (LHS.isInvalid())
  7999. return QualType();
  8000. RHS = UsualUnaryConversions(RHS.get());
  8001. if (RHS.isInvalid())
  8002. return QualType();
  8003. if (!LHS.get()->getType()->isScalarType() ||
  8004. !RHS.get()->getType()->isScalarType())
  8005. return InvalidOperands(Loc, LHS, RHS);
  8006. return Context.IntTy;
  8007. }
  8008. // The following is safe because we only use this method for
  8009. // non-overloadable operands.
  8010. // C++ [expr.log.and]p1
  8011. // C++ [expr.log.or]p1
  8012. // The operands are both contextually converted to type bool.
  8013. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  8014. if (LHSRes.isInvalid())
  8015. return InvalidOperands(Loc, LHS, RHS);
  8016. LHS = LHSRes;
  8017. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  8018. if (RHSRes.isInvalid())
  8019. return InvalidOperands(Loc, LHS, RHS);
  8020. RHS = RHSRes;
  8021. // C++ [expr.log.and]p2
  8022. // C++ [expr.log.or]p2
  8023. // The result is a bool.
  8024. return Context.BoolTy;
  8025. }
  8026. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  8027. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  8028. if (!ME) return false;
  8029. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  8030. ObjCMessageExpr *Base =
  8031. dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
  8032. if (!Base) return false;
  8033. return Base->getMethodDecl() != nullptr;
  8034. }
  8035. /// Is the given expression (which must be 'const') a reference to a
  8036. /// variable which was originally non-const, but which has become
  8037. /// 'const' due to being captured within a block?
  8038. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  8039. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  8040. assert(E->isLValue() && E->getType().isConstQualified());
  8041. E = E->IgnoreParens();
  8042. // Must be a reference to a declaration from an enclosing scope.
  8043. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  8044. if (!DRE) return NCCK_None;
  8045. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  8046. // The declaration must be a variable which is not declared 'const'.
  8047. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  8048. if (!var) return NCCK_None;
  8049. if (var->getType().isConstQualified()) return NCCK_None;
  8050. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  8051. // Decide whether the first capture was for a block or a lambda.
  8052. DeclContext *DC = S.CurContext, *Prev = nullptr;
  8053. while (DC != var->getDeclContext()) {
  8054. Prev = DC;
  8055. DC = DC->getParent();
  8056. }
  8057. // Unless we have an init-capture, we've gone one step too far.
  8058. if (!var->isInitCapture())
  8059. DC = Prev;
  8060. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  8061. }
  8062. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  8063. Ty = Ty.getNonReferenceType();
  8064. if (IsDereference && Ty->isPointerType())
  8065. Ty = Ty->getPointeeType();
  8066. return !Ty.isConstQualified();
  8067. }
  8068. /// Emit the "read-only variable not assignable" error and print notes to give
  8069. /// more information about why the variable is not assignable, such as pointing
  8070. /// to the declaration of a const variable, showing that a method is const, or
  8071. /// that the function is returning a const reference.
  8072. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  8073. SourceLocation Loc) {
  8074. // Update err_typecheck_assign_const and note_typecheck_assign_const
  8075. // when this enum is changed.
  8076. enum {
  8077. ConstFunction,
  8078. ConstVariable,
  8079. ConstMember,
  8080. ConstMethod,
  8081. ConstUnknown, // Keep as last element
  8082. };
  8083. SourceRange ExprRange = E->getSourceRange();
  8084. // Only emit one error on the first const found. All other consts will emit
  8085. // a note to the error.
  8086. bool DiagnosticEmitted = false;
  8087. // Track if the current expression is the result of a derefence, and if the
  8088. // next checked expression is the result of a derefence.
  8089. bool IsDereference = false;
  8090. bool NextIsDereference = false;
  8091. // Loop to process MemberExpr chains.
  8092. while (true) {
  8093. IsDereference = NextIsDereference;
  8094. NextIsDereference = false;
  8095. E = E->IgnoreParenImpCasts();
  8096. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  8097. NextIsDereference = ME->isArrow();
  8098. const ValueDecl *VD = ME->getMemberDecl();
  8099. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  8100. // Mutable fields can be modified even if the class is const.
  8101. if (Field->isMutable()) {
  8102. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  8103. break;
  8104. }
  8105. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  8106. if (!DiagnosticEmitted) {
  8107. S.Diag(Loc, diag::err_typecheck_assign_const)
  8108. << ExprRange << ConstMember << false /*static*/ << Field
  8109. << Field->getType();
  8110. DiagnosticEmitted = true;
  8111. }
  8112. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8113. << ConstMember << false /*static*/ << Field << Field->getType()
  8114. << Field->getSourceRange();
  8115. }
  8116. E = ME->getBase();
  8117. continue;
  8118. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  8119. if (VDecl->getType().isConstQualified()) {
  8120. if (!DiagnosticEmitted) {
  8121. S.Diag(Loc, diag::err_typecheck_assign_const)
  8122. << ExprRange << ConstMember << true /*static*/ << VDecl
  8123. << VDecl->getType();
  8124. DiagnosticEmitted = true;
  8125. }
  8126. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8127. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  8128. << VDecl->getSourceRange();
  8129. }
  8130. // Static fields do not inherit constness from parents.
  8131. break;
  8132. }
  8133. break;
  8134. } // End MemberExpr
  8135. break;
  8136. }
  8137. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  8138. // Function calls
  8139. const FunctionDecl *FD = CE->getDirectCallee();
  8140. if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  8141. if (!DiagnosticEmitted) {
  8142. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8143. << ConstFunction << FD;
  8144. DiagnosticEmitted = true;
  8145. }
  8146. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  8147. diag::note_typecheck_assign_const)
  8148. << ConstFunction << FD << FD->getReturnType()
  8149. << FD->getReturnTypeSourceRange();
  8150. }
  8151. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8152. // Point to variable declaration.
  8153. if (const ValueDecl *VD = DRE->getDecl()) {
  8154. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  8155. if (!DiagnosticEmitted) {
  8156. S.Diag(Loc, diag::err_typecheck_assign_const)
  8157. << ExprRange << ConstVariable << VD << VD->getType();
  8158. DiagnosticEmitted = true;
  8159. }
  8160. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  8161. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  8162. }
  8163. }
  8164. } else if (isa<CXXThisExpr>(E)) {
  8165. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  8166. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  8167. if (MD->isConst()) {
  8168. if (!DiagnosticEmitted) {
  8169. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  8170. << ConstMethod << MD;
  8171. DiagnosticEmitted = true;
  8172. }
  8173. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  8174. << ConstMethod << MD << MD->getSourceRange();
  8175. }
  8176. }
  8177. }
  8178. }
  8179. if (DiagnosticEmitted)
  8180. return;
  8181. // Can't determine a more specific message, so display the generic error.
  8182. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  8183. }
  8184. static bool HLSLCheckForModifiableLValue(
  8185. Expr *E,
  8186. SourceLocation Loc,
  8187. Sema &S
  8188. ) {
  8189. assert(isa<CXXOperatorCallExpr>(E));
  8190. const CXXOperatorCallExpr *expr = cast<CXXOperatorCallExpr>(E);
  8191. const Expr *LHS = expr->getArg(0);
  8192. QualType qt = LHS->getType();
  8193. // Check modifying const matrix with double subscript operator calls
  8194. if (isa<CXXOperatorCallExpr>(expr->getArg(0)))
  8195. return HLSLCheckForModifiableLValue(const_cast<Expr *>(expr->getArg(0)), Loc, S);
  8196. if (qt.isConstQualified() && (hlsl::IsMatrixType(&S, qt) || hlsl::IsVectorType(&S, qt))) {
  8197. DiagnoseConstAssignment(S, LHS, Loc);
  8198. return true;
  8199. }
  8200. if (!LHS->isLValue()) {
  8201. S.Diag(Loc, diag::err_typecheck_expression_not_modifiable_lvalue);
  8202. return true;
  8203. }
  8204. return false;
  8205. }
  8206. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  8207. /// emit an error and return true. If so, return false.
  8208. bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { // HLSL Change: export this function
  8209. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  8210. // HLSL Change Starts - check const for array subscript operator for HLSL vector/matrix
  8211. if (S.Context.getLangOpts().HLSL && E->getStmtClass() == Stmt::CXXOperatorCallExprClass) {
  8212. // check if it's a vector or matrix
  8213. return HLSLCheckForModifiableLValue(E, Loc, S);
  8214. }
  8215. // HLSL Change Ends
  8216. SourceLocation OrigLoc = Loc;
  8217. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  8218. &Loc);
  8219. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  8220. IsLV = Expr::MLV_InvalidMessageExpression;
  8221. if (IsLV == Expr::MLV_Valid)
  8222. return false;
  8223. unsigned DiagID = 0;
  8224. bool NeedType = false;
  8225. switch (IsLV) { // C99 6.5.16p2
  8226. case Expr::MLV_ConstQualified:
  8227. // Use a specialized diagnostic when we're assigning to an object
  8228. // from an enclosing function or block.
  8229. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  8230. if (NCCK == NCCK_Block)
  8231. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  8232. else
  8233. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  8234. break;
  8235. }
  8236. // In ARC, use some specialized diagnostics for occasions where we
  8237. // infer 'const'. These are always pseudo-strong variables.
  8238. if (S.getLangOpts().ObjCAutoRefCount) {
  8239. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  8240. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  8241. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  8242. // Use the normal diagnostic if it's pseudo-__strong but the
  8243. // user actually wrote 'const'.
  8244. if (var->isARCPseudoStrong() &&
  8245. (!var->getTypeSourceInfo() ||
  8246. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  8247. // There are two pseudo-strong cases:
  8248. // - self
  8249. ObjCMethodDecl *method = S.getCurMethodDecl();
  8250. if (method && var == method->getSelfDecl())
  8251. DiagID = method->isClassMethod()
  8252. ? diag::err_typecheck_arc_assign_self_class_method
  8253. : diag::err_typecheck_arc_assign_self;
  8254. // - fast enumeration variables
  8255. else
  8256. DiagID = diag::err_typecheck_arr_assign_enumeration;
  8257. SourceRange Assign;
  8258. if (Loc != OrigLoc)
  8259. Assign = SourceRange(OrigLoc, OrigLoc);
  8260. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8261. // We need to preserve the AST regardless, so migration tool
  8262. // can do its job.
  8263. return false;
  8264. }
  8265. }
  8266. }
  8267. // If none of the special cases above are triggered, then this is a
  8268. // simple const assignment.
  8269. if (DiagID == 0) {
  8270. DiagnoseConstAssignment(S, E, Loc);
  8271. return true;
  8272. }
  8273. break;
  8274. case Expr::MLV_ConstAddrSpace:
  8275. DiagnoseConstAssignment(S, E, Loc);
  8276. return true;
  8277. case Expr::MLV_ArrayType:
  8278. case Expr::MLV_ArrayTemporary:
  8279. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  8280. NeedType = true;
  8281. break;
  8282. case Expr::MLV_NotObjectType:
  8283. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  8284. NeedType = true;
  8285. break;
  8286. case Expr::MLV_LValueCast:
  8287. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  8288. break;
  8289. case Expr::MLV_Valid:
  8290. llvm_unreachable("did not take early return for MLV_Valid");
  8291. case Expr::MLV_InvalidExpression:
  8292. case Expr::MLV_MemberFunction:
  8293. case Expr::MLV_ClassTemporary:
  8294. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  8295. break;
  8296. case Expr::MLV_IncompleteType:
  8297. case Expr::MLV_IncompleteVoidType:
  8298. return S.RequireCompleteType(Loc, E->getType(),
  8299. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  8300. case Expr::MLV_DuplicateVectorComponents:
  8301. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  8302. break;
  8303. // HLSL Change Starts
  8304. case Expr::MLV_DuplicateMatrixComponents:
  8305. DiagID = diag::err_hlsl_typecheck_duplicate_matrix_components_not_mlvalue;
  8306. break;
  8307. // HLSL Change Ends
  8308. case Expr::MLV_NoSetterProperty:
  8309. llvm_unreachable("readonly properties should be processed differently");
  8310. case Expr::MLV_InvalidMessageExpression:
  8311. DiagID = diag::error_readonly_message_assignment;
  8312. break;
  8313. case Expr::MLV_SubObjCPropertySetting:
  8314. DiagID = diag::error_no_subobject_property_setting;
  8315. break;
  8316. }
  8317. SourceRange Assign;
  8318. if (Loc != OrigLoc)
  8319. Assign = SourceRange(OrigLoc, OrigLoc);
  8320. if (NeedType)
  8321. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  8322. else
  8323. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  8324. return true;
  8325. }
  8326. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  8327. SourceLocation Loc,
  8328. Sema &Sema) {
  8329. // C / C++ fields
  8330. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  8331. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  8332. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  8333. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  8334. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  8335. }
  8336. // Objective-C instance variables
  8337. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  8338. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  8339. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  8340. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  8341. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  8342. if (RL && RR && RL->getDecl() == RR->getDecl())
  8343. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  8344. }
  8345. }
  8346. // C99 6.5.16.1
  8347. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  8348. SourceLocation Loc,
  8349. QualType CompoundType) {
  8350. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  8351. // Verify that LHS is a modifiable lvalue, and emit error if not.
  8352. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  8353. return QualType();
  8354. QualType LHSType = LHSExpr->getType();
  8355. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  8356. CompoundType;
  8357. AssignConvertType ConvTy;
  8358. if (CompoundType.isNull()) {
  8359. Expr *RHSCheck = RHS.get();
  8360. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  8361. QualType LHSTy(LHSType);
  8362. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  8363. if (RHS.isInvalid())
  8364. return QualType();
  8365. // Special case of NSObject attributes on c-style pointer types.
  8366. if (ConvTy == IncompatiblePointer &&
  8367. ((Context.isObjCNSObjectType(LHSType) &&
  8368. RHSType->isObjCObjectPointerType()) ||
  8369. (Context.isObjCNSObjectType(RHSType) &&
  8370. LHSType->isObjCObjectPointerType())))
  8371. ConvTy = Compatible;
  8372. if (ConvTy == Compatible &&
  8373. LHSType->isObjCObjectType())
  8374. Diag(Loc, diag::err_objc_object_assignment)
  8375. << LHSType;
  8376. // If the RHS is a unary plus or minus, check to see if they = and + are
  8377. // right next to each other. If so, the user may have typo'd "x =+ 4"
  8378. // instead of "x += 4".
  8379. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  8380. RHSCheck = ICE->getSubExpr();
  8381. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  8382. if ((UO->getOpcode() == UO_Plus ||
  8383. UO->getOpcode() == UO_Minus) &&
  8384. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  8385. // Only if the two operators are exactly adjacent.
  8386. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  8387. // And there is a space or other character before the subexpr of the
  8388. // unary +/-. We don't want to warn on "x=-1".
  8389. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  8390. UO->getSubExpr()->getLocStart().isFileID()) {
  8391. Diag(Loc, diag::warn_not_compound_assign)
  8392. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  8393. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  8394. }
  8395. }
  8396. #if 0 // HLSL Change Starts
  8397. if (ConvTy == Compatible) {
  8398. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  8399. // Warn about retain cycles where a block captures the LHS, but
  8400. // not if the LHS is a simple variable into which the block is
  8401. // being stored...unless that variable can be captured by reference!
  8402. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  8403. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  8404. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  8405. checkRetainCycles(LHSExpr, RHS.get());
  8406. // It is safe to assign a weak reference into a strong variable.
  8407. // Although this code can still have problems:
  8408. // id x = self.weakProp;
  8409. // id y = self.weakProp;
  8410. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8411. // paths through the function. This should be revisited if
  8412. // -Wrepeated-use-of-weak is made flow-sensitive.
  8413. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8414. RHS.get()->getLocStart()))
  8415. getCurFunction()->markSafeWeakUse(RHS.get());
  8416. } else if (getLangOpts().ObjCAutoRefCount) {
  8417. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  8418. }
  8419. }
  8420. #endif // HLSL Change Ends
  8421. } else {
  8422. // Compound assignment "x += y"
  8423. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  8424. }
  8425. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  8426. RHS.get(), AA_Assigning))
  8427. return QualType();
  8428. CheckForNullPointerDereference(*this, LHSExpr);
  8429. // C99 6.5.16p3: The type of an assignment expression is the type of the
  8430. // left operand unless the left operand has qualified type, in which case
  8431. // it is the unqualified version of the type of the left operand.
  8432. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  8433. // is converted to the type of the assignment expression (above).
  8434. // C++ 5.17p1: the type of the assignment expression is that of its left
  8435. // operand.
  8436. return (getLangOpts().CPlusPlus
  8437. ? LHSType : LHSType.getUnqualifiedType());
  8438. }
  8439. // C99 6.5.17
  8440. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8441. SourceLocation Loc) {
  8442. LHS = S.CheckPlaceholderExpr(LHS.get());
  8443. RHS = S.CheckPlaceholderExpr(RHS.get());
  8444. if (LHS.isInvalid() || RHS.isInvalid())
  8445. return QualType();
  8446. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  8447. // operands, but not unary promotions.
  8448. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  8449. // So we treat the LHS as a ignored value, and in C++ we allow the
  8450. // containing site to determine what should be done with the RHS.
  8451. LHS = S.IgnoredValueConversions(LHS.get());
  8452. if (LHS.isInvalid())
  8453. return QualType();
  8454. S.DiagnoseUnusedExprResult(LHS.get());
  8455. if (!S.getLangOpts().CPlusPlus) {
  8456. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  8457. if (RHS.isInvalid())
  8458. return QualType();
  8459. if (!RHS.get()->getType()->isVoidType())
  8460. S.RequireCompleteType(Loc, RHS.get()->getType(),
  8461. diag::err_incomplete_type);
  8462. }
  8463. return RHS.get()->getType();
  8464. }
  8465. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  8466. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  8467. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  8468. ExprValueKind &VK,
  8469. ExprObjectKind &OK,
  8470. SourceLocation OpLoc,
  8471. bool IsInc, bool IsPrefix) {
  8472. if (Op->isTypeDependent())
  8473. return S.Context.DependentTy;
  8474. QualType ResType = Op->getType();
  8475. // Atomic types can be used for increment / decrement where the non-atomic
  8476. // versions can, so ignore the _Atomic() specifier for the purpose of
  8477. // checking.
  8478. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8479. ResType = ResAtomicType->getValueType();
  8480. assert(!ResType.isNull() && "no type for increment/decrement expression");
  8481. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  8482. // Decrement of bool is not allowed.
  8483. if (!IsInc) {
  8484. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  8485. return QualType();
  8486. }
  8487. // Increment of bool sets it to true, but is deprecated.
  8488. S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
  8489. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  8490. // Error on enum increments and decrements in C++ mode
  8491. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  8492. return QualType();
  8493. } else if (ResType->isRealType()) {
  8494. // OK!
  8495. } else if (ResType->isPointerType()) {
  8496. // C99 6.5.2.4p2, 6.5.6p2
  8497. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  8498. return QualType();
  8499. } else if (ResType->isObjCObjectPointerType()) {
  8500. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  8501. // Otherwise, we just need a complete type.
  8502. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  8503. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  8504. return QualType();
  8505. } else if (ResType->isAnyComplexType()) {
  8506. // C99 does not support ++/-- on complex types, we allow as an extension.
  8507. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  8508. << ResType << Op->getSourceRange();
  8509. } else if (ResType->isPlaceholderType()) {
  8510. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8511. if (PR.isInvalid()) return QualType();
  8512. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  8513. IsInc, IsPrefix);
  8514. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  8515. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  8516. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  8517. (ResType->getAs<VectorType>()->getVectorKind() !=
  8518. VectorType::AltiVecBool)) {
  8519. // The z vector extensions allow ++ and -- for non-bool vectors.
  8520. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  8521. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  8522. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  8523. } else {
  8524. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  8525. << ResType << int(IsInc) << Op->getSourceRange();
  8526. return QualType();
  8527. }
  8528. // At this point, we know we have a real, complex or pointer type.
  8529. // Now make sure the operand is a modifiable lvalue.
  8530. if (CheckForModifiableLvalue(Op, OpLoc, S))
  8531. return QualType();
  8532. // In C++, a prefix increment is the same type as the operand. Otherwise
  8533. // (in C or with postfix), the increment is the unqualified type of the
  8534. // operand.
  8535. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  8536. VK = VK_LValue;
  8537. OK = Op->getObjectKind();
  8538. return ResType;
  8539. } else {
  8540. VK = VK_RValue;
  8541. return ResType.getUnqualifiedType();
  8542. }
  8543. }
  8544. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  8545. /// This routine allows us to typecheck complex/recursive expressions
  8546. /// where the declaration is needed for type checking. We only need to
  8547. /// handle cases when the expression references a function designator
  8548. /// or is an lvalue. Here are some examples:
  8549. /// - &(x) => x
  8550. /// - &*****f => f for f a function designator.
  8551. /// - &s.xx => s
  8552. /// - &s.zz[1].yy -> s, if zz is an array
  8553. /// - *(x + 1) -> x, if x is an array
  8554. /// - &"123"[2] -> 0
  8555. /// - & __real__ x -> x
  8556. static ValueDecl *getPrimaryDecl(Expr *E) {
  8557. switch (E->getStmtClass()) {
  8558. case Stmt::DeclRefExprClass:
  8559. return cast<DeclRefExpr>(E)->getDecl();
  8560. case Stmt::MemberExprClass:
  8561. // If this is an arrow operator, the address is an offset from
  8562. // the base's value, so the object the base refers to is
  8563. // irrelevant.
  8564. if (cast<MemberExpr>(E)->isArrow())
  8565. return nullptr;
  8566. // Otherwise, the expression refers to a part of the base
  8567. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  8568. case Stmt::ArraySubscriptExprClass: {
  8569. // FIXME: This code shouldn't be necessary! We should catch the implicit
  8570. // promotion of register arrays earlier.
  8571. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  8572. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  8573. if (ICE->getSubExpr()->getType()->isArrayType())
  8574. return getPrimaryDecl(ICE->getSubExpr());
  8575. }
  8576. return nullptr;
  8577. }
  8578. case Stmt::UnaryOperatorClass: {
  8579. UnaryOperator *UO = cast<UnaryOperator>(E);
  8580. switch(UO->getOpcode()) {
  8581. case UO_Real:
  8582. case UO_Imag:
  8583. case UO_Extension:
  8584. return getPrimaryDecl(UO->getSubExpr());
  8585. default:
  8586. return nullptr;
  8587. }
  8588. }
  8589. case Stmt::ParenExprClass:
  8590. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  8591. case Stmt::ImplicitCastExprClass:
  8592. // If the result of an implicit cast is an l-value, we care about
  8593. // the sub-expression; otherwise, the result here doesn't matter.
  8594. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  8595. default:
  8596. return nullptr;
  8597. }
  8598. }
  8599. namespace {
  8600. enum {
  8601. AO_Bit_Field = 0,
  8602. AO_Vector_Element = 1,
  8603. AO_Property_Expansion = 2,
  8604. AO_Register_Variable = 3,
  8605. AO_No_Error = 4
  8606. };
  8607. }
  8608. /// \brief Diagnose invalid operand for address of operations.
  8609. ///
  8610. /// \param Type The type of operand which cannot have its address taken.
  8611. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  8612. Expr *E, unsigned Type) {
  8613. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  8614. }
  8615. /// CheckAddressOfOperand - The operand of & must be either a function
  8616. /// designator or an lvalue designating an object. If it is an lvalue, the
  8617. /// object cannot be declared with storage class register or be a bit field.
  8618. /// Note: The usual conversions are *not* applied to the operand of the &
  8619. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  8620. /// In C++, the operand might be an overloaded function name, in which case
  8621. /// we allow the '&' but retain the overloaded-function type.
  8622. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  8623. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  8624. if (PTy->getKind() == BuiltinType::Overload) {
  8625. Expr *E = OrigOp.get()->IgnoreParens();
  8626. if (!isa<OverloadExpr>(E)) {
  8627. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  8628. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  8629. << OrigOp.get()->getSourceRange();
  8630. return QualType();
  8631. }
  8632. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  8633. if (isa<UnresolvedMemberExpr>(Ovl))
  8634. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  8635. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8636. << OrigOp.get()->getSourceRange();
  8637. return QualType();
  8638. }
  8639. return Context.OverloadTy;
  8640. }
  8641. if (PTy->getKind() == BuiltinType::UnknownAny)
  8642. return Context.UnknownAnyTy;
  8643. if (PTy->getKind() == BuiltinType::BoundMember) {
  8644. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8645. << OrigOp.get()->getSourceRange();
  8646. return QualType();
  8647. }
  8648. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  8649. if (OrigOp.isInvalid()) return QualType();
  8650. }
  8651. if (OrigOp.get()->isTypeDependent())
  8652. return Context.DependentTy;
  8653. assert(!OrigOp.get()->getType()->isPlaceholderType());
  8654. // Make sure to ignore parentheses in subsequent checks
  8655. Expr *op = OrigOp.get()->IgnoreParens();
  8656. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  8657. if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
  8658. Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
  8659. return QualType();
  8660. }
  8661. if (getLangOpts().C99) {
  8662. // Implement C99-only parts of addressof rules.
  8663. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  8664. if (uOp->getOpcode() == UO_Deref)
  8665. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  8666. // (assuming the deref expression is valid).
  8667. return uOp->getSubExpr()->getType();
  8668. }
  8669. // Technically, there should be a check for array subscript
  8670. // expressions here, but the result of one is always an lvalue anyway.
  8671. }
  8672. ValueDecl *dcl = getPrimaryDecl(op);
  8673. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  8674. unsigned AddressOfError = AO_No_Error;
  8675. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  8676. bool sfinae = (bool)isSFINAEContext();
  8677. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  8678. : diag::ext_typecheck_addrof_temporary)
  8679. << op->getType() << op->getSourceRange();
  8680. if (sfinae)
  8681. return QualType();
  8682. // Materialize the temporary as an lvalue so that we can take its address.
  8683. OrigOp = op = new (Context)
  8684. MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  8685. } else if (isa<ObjCSelectorExpr>(op)) {
  8686. return Context.getPointerType(op->getType());
  8687. } else if (lval == Expr::LV_MemberFunction) {
  8688. // If it's an instance method, make a member pointer.
  8689. // The expression must have exactly the form &A::foo.
  8690. // If the underlying expression isn't a decl ref, give up.
  8691. if (!isa<DeclRefExpr>(op)) {
  8692. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  8693. << OrigOp.get()->getSourceRange();
  8694. return QualType();
  8695. }
  8696. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  8697. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  8698. // The id-expression was parenthesized.
  8699. if (OrigOp.get() != DRE) {
  8700. Diag(OpLoc, diag::err_parens_pointer_member_function)
  8701. << OrigOp.get()->getSourceRange();
  8702. // The method was named without a qualifier.
  8703. } else if (!DRE->getQualifier()) {
  8704. if (MD->getParent()->getName().empty())
  8705. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8706. << op->getSourceRange();
  8707. else {
  8708. SmallString<32> Str;
  8709. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  8710. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  8711. << op->getSourceRange()
  8712. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  8713. }
  8714. }
  8715. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  8716. if (isa<CXXDestructorDecl>(MD))
  8717. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  8718. QualType MPTy = Context.getMemberPointerType(
  8719. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  8720. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8721. RequireCompleteType(OpLoc, MPTy, 0);
  8722. return MPTy;
  8723. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  8724. // C99 6.5.3.2p1
  8725. // The operand must be either an l-value or a function designator
  8726. if (!op->getType()->isFunctionType()) {
  8727. // Use a special diagnostic for loads from property references.
  8728. if (isa<PseudoObjectExpr>(op)) {
  8729. AddressOfError = AO_Property_Expansion;
  8730. } else {
  8731. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  8732. << op->getType() << op->getSourceRange();
  8733. return QualType();
  8734. }
  8735. }
  8736. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  8737. // The operand cannot be a bit-field
  8738. AddressOfError = AO_Bit_Field;
  8739. } else if (op->getObjectKind() == OK_VectorComponent) {
  8740. // The operand cannot be an element of a vector
  8741. AddressOfError = AO_Vector_Element;
  8742. } else if (dcl) { // C99 6.5.3.2p1
  8743. // We have an lvalue with a decl. Make sure the decl is not declared
  8744. // with the register storage-class specifier.
  8745. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  8746. // in C++ it is not error to take address of a register
  8747. // variable (c++03 7.1.1P3)
  8748. if (vd->getStorageClass() == SC_Register &&
  8749. !getLangOpts().CPlusPlus) {
  8750. AddressOfError = AO_Register_Variable;
  8751. }
  8752. } else if (isa<MSPropertyDecl>(dcl)) {
  8753. AddressOfError = AO_Property_Expansion;
  8754. } else if (isa<FunctionTemplateDecl>(dcl)) {
  8755. return Context.OverloadTy;
  8756. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  8757. // Okay: we can take the address of a field.
  8758. // Could be a pointer to member, though, if there is an explicit
  8759. // scope qualifier for the class.
  8760. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  8761. DeclContext *Ctx = dcl->getDeclContext();
  8762. if (Ctx && Ctx->isRecord()) {
  8763. if (dcl->getType()->isReferenceType()) {
  8764. Diag(OpLoc,
  8765. diag::err_cannot_form_pointer_to_member_of_reference_type)
  8766. << dcl->getDeclName() << dcl->getType();
  8767. return QualType();
  8768. }
  8769. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  8770. Ctx = Ctx->getParent();
  8771. QualType MPTy = Context.getMemberPointerType(
  8772. op->getType(),
  8773. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  8774. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  8775. RequireCompleteType(OpLoc, MPTy, 0);
  8776. return MPTy;
  8777. }
  8778. }
  8779. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
  8780. llvm_unreachable("Unknown/unexpected decl type");
  8781. }
  8782. if (AddressOfError != AO_No_Error) {
  8783. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  8784. return QualType();
  8785. }
  8786. if (lval == Expr::LV_IncompleteVoidType) {
  8787. // Taking the address of a void variable is technically illegal, but we
  8788. // allow it in cases which are otherwise valid.
  8789. // Example: "extern void x; void* y = &x;".
  8790. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  8791. }
  8792. // If the operand has type "type", the result has type "pointer to type".
  8793. if (op->getType()->isObjCObjectType())
  8794. return Context.getObjCObjectPointerType(op->getType());
  8795. return Context.getPointerType(op->getType());
  8796. }
  8797. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  8798. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  8799. if (!DRE)
  8800. return;
  8801. const Decl *D = DRE->getDecl();
  8802. if (!D)
  8803. return;
  8804. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  8805. if (!Param)
  8806. return;
  8807. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  8808. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  8809. return;
  8810. if (FunctionScopeInfo *FD = S.getCurFunction())
  8811. if (!FD->ModifiedNonNullParams.count(Param))
  8812. FD->ModifiedNonNullParams.insert(Param);
  8813. }
  8814. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  8815. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  8816. SourceLocation OpLoc) {
  8817. if (Op->isTypeDependent())
  8818. return S.Context.DependentTy;
  8819. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  8820. if (ConvResult.isInvalid())
  8821. return QualType();
  8822. Op = ConvResult.get();
  8823. QualType OpTy = Op->getType();
  8824. QualType Result;
  8825. if (isa<CXXReinterpretCastExpr>(Op)) {
  8826. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  8827. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  8828. Op->getSourceRange());
  8829. }
  8830. if (const PointerType *PT = OpTy->getAs<PointerType>())
  8831. Result = PT->getPointeeType();
  8832. else if (const ObjCObjectPointerType *OPT =
  8833. OpTy->getAs<ObjCObjectPointerType>())
  8834. Result = OPT->getPointeeType();
  8835. else {
  8836. ExprResult PR = S.CheckPlaceholderExpr(Op);
  8837. if (PR.isInvalid()) return QualType();
  8838. if (PR.get() != Op)
  8839. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  8840. }
  8841. if (Result.isNull()) {
  8842. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  8843. << OpTy << Op->getSourceRange();
  8844. return QualType();
  8845. }
  8846. // Note that per both C89 and C99, indirection is always legal, even if Result
  8847. // is an incomplete type or void. It would be possible to warn about
  8848. // dereferencing a void pointer, but it's completely well-defined, and such a
  8849. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  8850. // for pointers to 'void' but is fine for any other pointer type:
  8851. //
  8852. // C++ [expr.unary.op]p1:
  8853. // [...] the expression to which [the unary * operator] is applied shall
  8854. // be a pointer to an object type, or a pointer to a function type
  8855. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  8856. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  8857. << OpTy << Op->getSourceRange();
  8858. // Dereferences are usually l-values...
  8859. VK = VK_LValue;
  8860. // ...except that certain expressions are never l-values in C.
  8861. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  8862. VK = VK_RValue;
  8863. return Result;
  8864. }
  8865. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  8866. BinaryOperatorKind Opc;
  8867. switch (Kind) {
  8868. default: llvm_unreachable("Unknown binop!");
  8869. case tok::periodstar: Opc = BO_PtrMemD; break;
  8870. case tok::arrowstar: Opc = BO_PtrMemI; break;
  8871. case tok::star: Opc = BO_Mul; break;
  8872. case tok::slash: Opc = BO_Div; break;
  8873. case tok::percent: Opc = BO_Rem; break;
  8874. case tok::plus: Opc = BO_Add; break;
  8875. case tok::minus: Opc = BO_Sub; break;
  8876. case tok::lessless: Opc = BO_Shl; break;
  8877. case tok::greatergreater: Opc = BO_Shr; break;
  8878. case tok::lessequal: Opc = BO_LE; break;
  8879. case tok::less: Opc = BO_LT; break;
  8880. case tok::greaterequal: Opc = BO_GE; break;
  8881. case tok::greater: Opc = BO_GT; break;
  8882. case tok::exclaimequal: Opc = BO_NE; break;
  8883. case tok::equalequal: Opc = BO_EQ; break;
  8884. case tok::amp: Opc = BO_And; break;
  8885. case tok::caret: Opc = BO_Xor; break;
  8886. case tok::pipe: Opc = BO_Or; break;
  8887. case tok::ampamp: Opc = BO_LAnd; break;
  8888. case tok::pipepipe: Opc = BO_LOr; break;
  8889. case tok::equal: Opc = BO_Assign; break;
  8890. case tok::starequal: Opc = BO_MulAssign; break;
  8891. case tok::slashequal: Opc = BO_DivAssign; break;
  8892. case tok::percentequal: Opc = BO_RemAssign; break;
  8893. case tok::plusequal: Opc = BO_AddAssign; break;
  8894. case tok::minusequal: Opc = BO_SubAssign; break;
  8895. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  8896. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  8897. case tok::ampequal: Opc = BO_AndAssign; break;
  8898. case tok::caretequal: Opc = BO_XorAssign; break;
  8899. case tok::pipeequal: Opc = BO_OrAssign; break;
  8900. case tok::comma: Opc = BO_Comma; break;
  8901. }
  8902. return Opc;
  8903. }
  8904. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  8905. tok::TokenKind Kind) {
  8906. UnaryOperatorKind Opc;
  8907. switch (Kind) {
  8908. default: llvm_unreachable("Unknown unary op!");
  8909. case tok::plusplus: Opc = UO_PreInc; break;
  8910. case tok::minusminus: Opc = UO_PreDec; break;
  8911. case tok::amp: Opc = UO_AddrOf; break;
  8912. case tok::star: Opc = UO_Deref; break;
  8913. case tok::plus: Opc = UO_Plus; break;
  8914. case tok::minus: Opc = UO_Minus; break;
  8915. case tok::tilde: Opc = UO_Not; break;
  8916. case tok::exclaim: Opc = UO_LNot; break;
  8917. case tok::kw___real: Opc = UO_Real; break;
  8918. case tok::kw___imag: Opc = UO_Imag; break;
  8919. case tok::kw___extension__: Opc = UO_Extension; break;
  8920. }
  8921. return Opc;
  8922. }
  8923. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  8924. /// This warning is only emitted for builtin assignment operations. It is also
  8925. /// suppressed in the event of macro expansions.
  8926. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  8927. SourceLocation OpLoc) {
  8928. if (!S.ActiveTemplateInstantiations.empty())
  8929. return;
  8930. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  8931. return;
  8932. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8933. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8934. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8935. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8936. if (!LHSDeclRef || !RHSDeclRef ||
  8937. LHSDeclRef->getLocation().isMacroID() ||
  8938. RHSDeclRef->getLocation().isMacroID())
  8939. return;
  8940. const ValueDecl *LHSDecl =
  8941. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  8942. const ValueDecl *RHSDecl =
  8943. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  8944. if (LHSDecl != RHSDecl)
  8945. return;
  8946. if (LHSDecl->getType().isVolatileQualified())
  8947. return;
  8948. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  8949. if (RefTy->getPointeeType().isVolatileQualified())
  8950. return;
  8951. S.Diag(OpLoc, diag::warn_self_assignment)
  8952. << LHSDeclRef->getType()
  8953. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8954. }
  8955. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  8956. /// is usually indicative of introspection within the Objective-C pointer.
  8957. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  8958. SourceLocation OpLoc) {
  8959. if (!S.getLangOpts().ObjC1)
  8960. return;
  8961. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  8962. const Expr *LHS = L.get();
  8963. const Expr *RHS = R.get();
  8964. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8965. ObjCPointerExpr = LHS;
  8966. OtherExpr = RHS;
  8967. }
  8968. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  8969. ObjCPointerExpr = RHS;
  8970. OtherExpr = LHS;
  8971. }
  8972. // This warning is deliberately made very specific to reduce false
  8973. // positives with logic that uses '&' for hashing. This logic mainly
  8974. // looks for code trying to introspect into tagged pointers, which
  8975. // code should generally never do.
  8976. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  8977. unsigned Diag = diag::warn_objc_pointer_masking;
  8978. // Determine if we are introspecting the result of performSelectorXXX.
  8979. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  8980. // Special case messages to -performSelector and friends, which
  8981. // can return non-pointer values boxed in a pointer value.
  8982. // Some clients may wish to silence warnings in this subcase.
  8983. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  8984. Selector S = ME->getSelector();
  8985. StringRef SelArg0 = S.getNameForSlot(0);
  8986. if (SelArg0.startswith("performSelector"))
  8987. Diag = diag::warn_objc_pointer_masking_performSelector;
  8988. }
  8989. S.Diag(OpLoc, Diag)
  8990. << ObjCPointerExpr->getSourceRange();
  8991. }
  8992. }
  8993. static NamedDecl *getDeclFromExpr(Expr *E) {
  8994. if (!E)
  8995. return nullptr;
  8996. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  8997. return DRE->getDecl();
  8998. if (auto *ME = dyn_cast<MemberExpr>(E))
  8999. return ME->getMemberDecl();
  9000. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  9001. return IRE->getDecl();
  9002. return nullptr;
  9003. }
  9004. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  9005. /// operator @p Opc at location @c TokLoc. This routine only supports
  9006. /// built-in operations; ActOnBinOp handles overloaded operators.
  9007. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  9008. BinaryOperatorKind Opc,
  9009. Expr *LHSExpr, Expr *RHSExpr) {
  9010. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  9011. // The syntax only allows initializer lists on the RHS of assignment,
  9012. // so we don't need to worry about accepting invalid code for
  9013. // non-assignment operators.
  9014. // C++11 5.17p9:
  9015. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  9016. // of x = {} is x = T().
  9017. InitializationKind Kind =
  9018. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  9019. InitializedEntity Entity =
  9020. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  9021. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  9022. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  9023. if (Init.isInvalid())
  9024. return Init;
  9025. RHSExpr = Init.get();
  9026. }
  9027. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  9028. QualType ResultTy; // Result type of the binary operator.
  9029. // The following two variables are used for compound assignment operators
  9030. QualType CompLHSTy; // Type of LHS after promotions for computation
  9031. QualType CompResultTy; // Type of computation result
  9032. ExprValueKind VK = VK_RValue;
  9033. ExprObjectKind OK = OK_Ordinary;
  9034. // HLSL Change Starts
  9035. // Handle HLSL binary operands differently
  9036. if (getLangOpts().HLSL) {
  9037. hlsl::CheckBinOpForHLSL(*this, OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  9038. if (!ResultTy.isNull() && Opc == BO_Comma) {
  9039. // In C/C++, the RHS value kind should propagate. In HLSL, it should yield an r-value.
  9040. // VK = RHS.get()->getValueKind();
  9041. OK = RHS.get()->getObjectKind();
  9042. }
  9043. goto CasesHandled;
  9044. }
  9045. // HLSL Change Ends
  9046. if (!getLangOpts().CPlusPlus) {
  9047. // C cannot handle TypoExpr nodes on either side of a binop because it
  9048. // doesn't handle dependent types properly, so make sure any TypoExprs have
  9049. // been dealt with before checking the operands.
  9050. LHS = CorrectDelayedTyposInExpr(LHSExpr);
  9051. RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
  9052. if (Opc != BO_Assign)
  9053. return ExprResult(E);
  9054. // Avoid correcting the RHS to the same Expr as the LHS.
  9055. Decl *D = getDeclFromExpr(E);
  9056. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  9057. });
  9058. if (!LHS.isUsable() || !RHS.isUsable())
  9059. return ExprError();
  9060. }
  9061. switch (Opc) {
  9062. case BO_Assign:
  9063. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  9064. if (getLangOpts().CPlusPlus &&
  9065. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  9066. VK = LHS.get()->getValueKind();
  9067. OK = LHS.get()->getObjectKind();
  9068. }
  9069. if (!ResultTy.isNull()) {
  9070. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9071. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  9072. }
  9073. RecordModifiableNonNullParam(*this, LHS.get());
  9074. break;
  9075. case BO_PtrMemD:
  9076. case BO_PtrMemI:
  9077. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  9078. Opc == BO_PtrMemI);
  9079. break;
  9080. case BO_Mul:
  9081. case BO_Div:
  9082. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  9083. Opc == BO_Div);
  9084. break;
  9085. case BO_Rem:
  9086. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  9087. break;
  9088. case BO_Add:
  9089. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  9090. break;
  9091. case BO_Sub:
  9092. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  9093. break;
  9094. case BO_Shl:
  9095. case BO_Shr:
  9096. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  9097. break;
  9098. case BO_LE:
  9099. case BO_LT:
  9100. case BO_GE:
  9101. case BO_GT:
  9102. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  9103. break;
  9104. case BO_EQ:
  9105. case BO_NE:
  9106. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  9107. break;
  9108. case BO_And:
  9109. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  9110. case BO_Xor:
  9111. case BO_Or:
  9112. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
  9113. break;
  9114. case BO_LAnd:
  9115. case BO_LOr:
  9116. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  9117. break;
  9118. case BO_MulAssign:
  9119. case BO_DivAssign:
  9120. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  9121. Opc == BO_DivAssign);
  9122. CompLHSTy = CompResultTy;
  9123. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9124. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9125. break;
  9126. case BO_RemAssign:
  9127. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  9128. CompLHSTy = CompResultTy;
  9129. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9130. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9131. break;
  9132. case BO_AddAssign:
  9133. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  9134. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9135. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9136. break;
  9137. case BO_SubAssign:
  9138. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  9139. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9140. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9141. break;
  9142. case BO_ShlAssign:
  9143. case BO_ShrAssign:
  9144. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  9145. CompLHSTy = CompResultTy;
  9146. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9147. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9148. break;
  9149. case BO_AndAssign:
  9150. case BO_OrAssign: // fallthrough
  9151. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  9152. case BO_XorAssign:
  9153. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
  9154. CompLHSTy = CompResultTy;
  9155. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  9156. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  9157. break;
  9158. case BO_Comma:
  9159. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  9160. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  9161. VK = RHS.get()->getValueKind();
  9162. OK = RHS.get()->getObjectKind();
  9163. }
  9164. break;
  9165. }
  9166. CasesHandled: // HLSL Change: minimize code changes by avoiding a branch above
  9167. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  9168. return ExprError();
  9169. // Check for array bounds violations for both sides of the BinaryOperator
  9170. CheckArrayAccess(LHS.get());
  9171. CheckArrayAccess(RHS.get());
  9172. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  9173. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  9174. &Context.Idents.get("object_setClass"),
  9175. SourceLocation(), LookupOrdinaryName);
  9176. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  9177. SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
  9178. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  9179. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  9180. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  9181. FixItHint::CreateInsertion(RHSLocEnd, ")");
  9182. }
  9183. else
  9184. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  9185. }
  9186. else if (const ObjCIvarRefExpr *OIRE =
  9187. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  9188. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  9189. if (CompResultTy.isNull())
  9190. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  9191. OK, OpLoc, FPFeatures.fp_contract);
  9192. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  9193. OK_ObjCProperty) {
  9194. VK = VK_LValue;
  9195. OK = LHS.get()->getObjectKind();
  9196. }
  9197. return new (Context) CompoundAssignOperator(
  9198. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  9199. OpLoc, FPFeatures.fp_contract);
  9200. }
  9201. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  9202. /// operators are mixed in a way that suggests that the programmer forgot that
  9203. /// comparison operators have higher precedence. The most typical example of
  9204. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  9205. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  9206. SourceLocation OpLoc, Expr *LHSExpr,
  9207. Expr *RHSExpr) {
  9208. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  9209. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  9210. // Check that one of the sides is a comparison operator.
  9211. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  9212. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  9213. if (!isLeftComp && !isRightComp)
  9214. return;
  9215. // Bitwise operations are sometimes used as eager logical ops.
  9216. // Don't diagnose this.
  9217. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  9218. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  9219. if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
  9220. return;
  9221. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  9222. OpLoc)
  9223. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  9224. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  9225. SourceRange ParensRange = isLeftComp ?
  9226. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  9227. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  9228. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  9229. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  9230. SuggestParentheses(Self, OpLoc,
  9231. Self.PDiag(diag::note_precedence_silence) << OpStr,
  9232. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  9233. SuggestParentheses(Self, OpLoc,
  9234. Self.PDiag(diag::note_precedence_bitwise_first)
  9235. << BinaryOperator::getOpcodeStr(Opc),
  9236. ParensRange);
  9237. }
  9238. /// \brief It accepts a '&' expr that is inside a '|' one.
  9239. /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
  9240. /// in parentheses.
  9241. static void
  9242. EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
  9243. BinaryOperator *Bop) {
  9244. assert(Bop->getOpcode() == BO_And);
  9245. Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
  9246. << Bop->getSourceRange() << OpLoc;
  9247. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9248. Self.PDiag(diag::note_precedence_silence)
  9249. << Bop->getOpcodeStr(),
  9250. Bop->getSourceRange());
  9251. }
  9252. /// \brief It accepts a '&&' expr that is inside a '||' one.
  9253. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  9254. /// in parentheses.
  9255. static void
  9256. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  9257. BinaryOperator *Bop) {
  9258. assert(Bop->getOpcode() == BO_LAnd);
  9259. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  9260. << Bop->getSourceRange() << OpLoc;
  9261. SuggestParentheses(Self, Bop->getOperatorLoc(),
  9262. Self.PDiag(diag::note_precedence_silence)
  9263. << Bop->getOpcodeStr(),
  9264. Bop->getSourceRange());
  9265. }
  9266. /// \brief Returns true if the given expression can be evaluated as a constant
  9267. /// 'true'.
  9268. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  9269. bool Res;
  9270. return !E->isValueDependent() &&
  9271. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  9272. }
  9273. /// \brief Returns true if the given expression can be evaluated as a constant
  9274. /// 'false'.
  9275. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  9276. bool Res;
  9277. return !E->isValueDependent() &&
  9278. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  9279. }
  9280. /// \brief Look for '&&' in the left hand of a '||' expr.
  9281. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  9282. Expr *LHSExpr, Expr *RHSExpr) {
  9283. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  9284. if (Bop->getOpcode() == BO_LAnd) {
  9285. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  9286. if (EvaluatesAsFalse(S, RHSExpr))
  9287. return;
  9288. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  9289. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  9290. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9291. } else if (Bop->getOpcode() == BO_LOr) {
  9292. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  9293. // If it's "a || b && 1 || c" we didn't warn earlier for
  9294. // "a || b && 1", but warn now.
  9295. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  9296. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  9297. }
  9298. }
  9299. }
  9300. }
  9301. /// \brief Look for '&&' in the right hand of a '||' expr.
  9302. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  9303. Expr *LHSExpr, Expr *RHSExpr) {
  9304. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  9305. if (Bop->getOpcode() == BO_LAnd) {
  9306. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  9307. if (EvaluatesAsFalse(S, LHSExpr))
  9308. return;
  9309. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  9310. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  9311. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  9312. }
  9313. }
  9314. }
  9315. /// \brief Look for '&' in the left or right hand of a '|' expr.
  9316. static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
  9317. Expr *OrArg) {
  9318. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
  9319. if (Bop->getOpcode() == BO_And)
  9320. return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
  9321. }
  9322. }
  9323. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  9324. Expr *SubExpr, StringRef Shift) {
  9325. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  9326. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  9327. StringRef Op = Bop->getOpcodeStr();
  9328. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  9329. << Bop->getSourceRange() << OpLoc << Shift << Op;
  9330. SuggestParentheses(S, Bop->getOperatorLoc(),
  9331. S.PDiag(diag::note_precedence_silence) << Op,
  9332. Bop->getSourceRange());
  9333. }
  9334. }
  9335. }
  9336. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  9337. Expr *LHSExpr, Expr *RHSExpr) {
  9338. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  9339. if (!OCE)
  9340. return;
  9341. FunctionDecl *FD = OCE->getDirectCallee();
  9342. if (!FD || !FD->isOverloadedOperator())
  9343. return;
  9344. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  9345. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  9346. return;
  9347. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  9348. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  9349. << (Kind == OO_LessLess);
  9350. SuggestParentheses(S, OCE->getOperatorLoc(),
  9351. S.PDiag(diag::note_precedence_silence)
  9352. << (Kind == OO_LessLess ? "<<" : ">>"),
  9353. OCE->getSourceRange());
  9354. SuggestParentheses(S, OpLoc,
  9355. S.PDiag(diag::note_evaluate_comparison_first),
  9356. SourceRange(OCE->getArg(1)->getLocStart(),
  9357. RHSExpr->getLocEnd()));
  9358. }
  9359. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  9360. /// precedence.
  9361. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  9362. SourceLocation OpLoc, Expr *LHSExpr,
  9363. Expr *RHSExpr){
  9364. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  9365. if (BinaryOperator::isBitwiseOp(Opc))
  9366. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  9367. // Diagnose "arg1 & arg2 | arg3"
  9368. if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9369. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
  9370. DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
  9371. }
  9372. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  9373. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  9374. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  9375. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  9376. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  9377. }
  9378. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  9379. || Opc == BO_Shr) {
  9380. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  9381. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  9382. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  9383. }
  9384. // Warn on overloaded shift operators and comparisons, such as:
  9385. // cout << 5 == 4;
  9386. if (BinaryOperator::isComparisonOp(Opc))
  9387. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  9388. }
  9389. // Binary Operators. 'Tok' is the token for the operator.
  9390. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  9391. tok::TokenKind Kind,
  9392. Expr *LHSExpr, Expr *RHSExpr) {
  9393. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  9394. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  9395. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  9396. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  9397. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  9398. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  9399. }
  9400. /// Build an overloaded binary operator expression in the given scope.
  9401. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  9402. BinaryOperatorKind Opc,
  9403. Expr *LHS, Expr *RHS) {
  9404. // Find all of the overloaded operators visible from this
  9405. // point. We perform both an operator-name lookup from the local
  9406. // scope and an argument-dependent lookup based on the types of
  9407. // the arguments.
  9408. UnresolvedSet<16> Functions;
  9409. OverloadedOperatorKind OverOp
  9410. = BinaryOperator::getOverloadedOperator(Opc);
  9411. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  9412. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  9413. RHS->getType(), Functions);
  9414. // Build the (potentially-overloaded, potentially-dependent)
  9415. // binary operation.
  9416. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  9417. }
  9418. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  9419. BinaryOperatorKind Opc,
  9420. Expr *LHSExpr, Expr *RHSExpr) {
  9421. // We want to end up calling one of checkPseudoObjectAssignment
  9422. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  9423. // both expressions are overloadable or either is type-dependent),
  9424. // or CreateBuiltinBinOp (in any other case). We also want to get
  9425. // any placeholder types out of the way.
  9426. // Handle pseudo-objects in the LHS.
  9427. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  9428. // Assignments with a pseudo-object l-value need special analysis.
  9429. if (pty->getKind() == BuiltinType::PseudoObject &&
  9430. BinaryOperator::isAssignmentOp(Opc))
  9431. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  9432. // Don't resolve overloads if the other type is overloadable.
  9433. if (pty->getKind() == BuiltinType::Overload) {
  9434. // We can't actually test that if we still have a placeholder,
  9435. // though. Fortunately, none of the exceptions we see in that
  9436. // code below are valid when the LHS is an overload set. Note
  9437. // that an overload set can be dependently-typed, but it never
  9438. // instantiates to having an overloadable type.
  9439. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9440. if (resolvedRHS.isInvalid()) return ExprError();
  9441. RHSExpr = resolvedRHS.get();
  9442. if (RHSExpr->isTypeDependent() ||
  9443. RHSExpr->getType()->isOverloadableType())
  9444. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9445. }
  9446. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  9447. if (LHS.isInvalid()) return ExprError();
  9448. LHSExpr = LHS.get();
  9449. }
  9450. // Handle pseudo-objects in the RHS.
  9451. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  9452. // An overload in the RHS can potentially be resolved by the type
  9453. // being assigned to.
  9454. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  9455. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9456. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9457. if (LHSExpr->getType()->isOverloadableType())
  9458. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9459. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9460. }
  9461. // Don't resolve overloads if the other type is overloadable.
  9462. if (pty->getKind() == BuiltinType::Overload &&
  9463. LHSExpr->getType()->isOverloadableType())
  9464. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9465. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  9466. if (!resolvedRHS.isUsable()) return ExprError();
  9467. RHSExpr = resolvedRHS.get();
  9468. }
  9469. // HLSL Change: bypass binary operator overload work, which isn't supported in any case;
  9470. // otherwise more extensive changes need to be done to add HLSL-specific behavior to
  9471. // be considered when building overload candidate sets
  9472. if (getLangOpts().CPlusPlus && !getLangOpts().HLSL) {
  9473. // If either expression is type-dependent, always build an
  9474. // overloaded op.
  9475. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  9476. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9477. // Otherwise, build an overloaded op if either expression has an
  9478. // overloadable type.
  9479. if (LHSExpr->getType()->isOverloadableType() ||
  9480. RHSExpr->getType()->isOverloadableType())
  9481. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  9482. }
  9483. // Build a built-in binary operation.
  9484. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  9485. }
  9486. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  9487. UnaryOperatorKind Opc,
  9488. Expr *InputExpr) {
  9489. ExprResult Input = InputExpr;
  9490. ExprValueKind VK = VK_RValue;
  9491. ExprObjectKind OK = OK_Ordinary;
  9492. QualType resultType;
  9493. // HLSL Change Starts
  9494. if (getLangOpts().HLSL) {
  9495. resultType = hlsl::CheckUnaryOpForHLSL(*this, OpLoc, Opc, Input, VK, OK);
  9496. goto CasesHandled;
  9497. }
  9498. // HLSL Change Ends
  9499. switch (Opc) {
  9500. case UO_PreInc:
  9501. case UO_PreDec:
  9502. case UO_PostInc:
  9503. case UO_PostDec:
  9504. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  9505. OpLoc,
  9506. Opc == UO_PreInc ||
  9507. Opc == UO_PostInc,
  9508. Opc == UO_PreInc ||
  9509. Opc == UO_PreDec);
  9510. break;
  9511. case UO_AddrOf:
  9512. resultType = CheckAddressOfOperand(Input, OpLoc);
  9513. RecordModifiableNonNullParam(*this, InputExpr);
  9514. break;
  9515. case UO_Deref: {
  9516. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9517. if (Input.isInvalid()) return ExprError();
  9518. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  9519. break;
  9520. }
  9521. case UO_Plus:
  9522. case UO_Minus:
  9523. Input = UsualUnaryConversions(Input.get());
  9524. if (Input.isInvalid()) return ExprError();
  9525. resultType = Input.get()->getType();
  9526. if (resultType->isDependentType())
  9527. break;
  9528. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  9529. break;
  9530. else if (resultType->isVectorType() &&
  9531. // The z vector extensions don't allow + or - with bool vectors.
  9532. (!Context.getLangOpts().ZVector ||
  9533. resultType->getAs<VectorType>()->getVectorKind() !=
  9534. VectorType::AltiVecBool))
  9535. break;
  9536. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  9537. Opc == UO_Plus &&
  9538. resultType->isPointerType())
  9539. break;
  9540. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9541. << resultType << Input.get()->getSourceRange());
  9542. case UO_Not: // bitwise complement
  9543. Input = UsualUnaryConversions(Input.get());
  9544. if (Input.isInvalid())
  9545. return ExprError();
  9546. resultType = Input.get()->getType();
  9547. if (resultType->isDependentType())
  9548. break;
  9549. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  9550. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  9551. // C99 does not support '~' for complex conjugation.
  9552. Diag(OpLoc, diag::ext_integer_complement_complex)
  9553. << resultType << Input.get()->getSourceRange();
  9554. else if (resultType->hasIntegerRepresentation())
  9555. break;
  9556. else if (resultType->isExtVectorType()) {
  9557. if (Context.getLangOpts().OpenCL) {
  9558. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  9559. // on vector float types.
  9560. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9561. if (!T->isIntegerType())
  9562. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9563. << resultType << Input.get()->getSourceRange());
  9564. }
  9565. break;
  9566. } else {
  9567. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9568. << resultType << Input.get()->getSourceRange());
  9569. }
  9570. break;
  9571. case UO_LNot: // logical negation
  9572. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  9573. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  9574. if (Input.isInvalid()) return ExprError();
  9575. resultType = Input.get()->getType();
  9576. // Though we still have to promote half FP to float...
  9577. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  9578. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  9579. resultType = Context.FloatTy;
  9580. }
  9581. if (resultType->isDependentType())
  9582. break;
  9583. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  9584. // C99 6.5.3.3p1: ok, fallthrough;
  9585. if (Context.getLangOpts().CPlusPlus) {
  9586. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  9587. // operand contextually converted to bool.
  9588. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  9589. ScalarTypeToBooleanCastKind(resultType));
  9590. } else if (Context.getLangOpts().OpenCL &&
  9591. Context.getLangOpts().OpenCLVersion < 120) {
  9592. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9593. // operate on scalar float types.
  9594. if (!resultType->isIntegerType())
  9595. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9596. << resultType << Input.get()->getSourceRange());
  9597. }
  9598. } else if (resultType->isExtVectorType()) {
  9599. if (Context.getLangOpts().OpenCL &&
  9600. Context.getLangOpts().OpenCLVersion < 120) {
  9601. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  9602. // operate on vector float types.
  9603. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  9604. if (!T->isIntegerType())
  9605. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9606. << resultType << Input.get()->getSourceRange());
  9607. }
  9608. // Vector logical not returns the signed variant of the operand type.
  9609. resultType = GetSignedVectorType(resultType);
  9610. break;
  9611. } else {
  9612. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  9613. << resultType << Input.get()->getSourceRange());
  9614. }
  9615. // LNot always has type int. C99 6.5.3.3p5.
  9616. // In C++, it's bool. C++ 5.3.1p8
  9617. resultType = Context.getLogicalOperationType();
  9618. break;
  9619. case UO_Real:
  9620. case UO_Imag:
  9621. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  9622. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  9623. // complex l-values to ordinary l-values and all other values to r-values.
  9624. if (Input.isInvalid()) return ExprError();
  9625. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  9626. if (Input.get()->getValueKind() != VK_RValue &&
  9627. Input.get()->getObjectKind() == OK_Ordinary)
  9628. VK = Input.get()->getValueKind();
  9629. } else if (!getLangOpts().CPlusPlus) {
  9630. // In C, a volatile scalar is read by __imag. In C++, it is not.
  9631. Input = DefaultLvalueConversion(Input.get());
  9632. }
  9633. break;
  9634. case UO_Extension:
  9635. resultType = Input.get()->getType();
  9636. VK = Input.get()->getValueKind();
  9637. OK = Input.get()->getObjectKind();
  9638. break;
  9639. }
  9640. CasesHandled: // HLSL Change: add label to skip C/C++ unary operator processing
  9641. if (resultType.isNull() || Input.isInvalid())
  9642. return ExprError();
  9643. // Check for array bounds violations in the operand of the UnaryOperator,
  9644. // except for the '*' and '&' operators that have to be handled specially
  9645. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  9646. // that are explicitly defined as valid by the standard).
  9647. if (Opc != UO_AddrOf && Opc != UO_Deref)
  9648. CheckArrayAccess(Input.get());
  9649. return new (Context)
  9650. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  9651. }
  9652. /// \brief Determine whether the given expression is a qualified member
  9653. /// access expression, of a form that could be turned into a pointer to member
  9654. /// with the address-of operator.
  9655. static bool isQualifiedMemberAccess(Expr *E) {
  9656. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9657. if (!DRE->getQualifier())
  9658. return false;
  9659. ValueDecl *VD = DRE->getDecl();
  9660. if (!VD->isCXXClassMember())
  9661. return false;
  9662. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  9663. return true;
  9664. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  9665. return Method->isInstance();
  9666. return false;
  9667. }
  9668. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  9669. if (!ULE->getQualifier())
  9670. return false;
  9671. for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
  9672. DEnd = ULE->decls_end();
  9673. D != DEnd; ++D) {
  9674. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
  9675. if (Method->isInstance())
  9676. return true;
  9677. } else {
  9678. // Overload set does not contain methods.
  9679. break;
  9680. }
  9681. }
  9682. return false;
  9683. }
  9684. return false;
  9685. }
  9686. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  9687. UnaryOperatorKind Opc, Expr *Input) {
  9688. // HLSL Change Starts - placeholders and overloaded operators not supported
  9689. if (getLangOpts().HLSL)
  9690. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9691. // HLSL Change Ends
  9692. // First things first: handle placeholders so that the
  9693. // overloaded-operator check considers the right type.
  9694. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  9695. // Increment and decrement of pseudo-object references.
  9696. if (pty->getKind() == BuiltinType::PseudoObject &&
  9697. UnaryOperator::isIncrementDecrementOp(Opc))
  9698. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  9699. // extension is always a builtin operator.
  9700. if (Opc == UO_Extension)
  9701. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9702. // & gets special logic for several kinds of placeholder.
  9703. // The builtin code knows what to do.
  9704. if (Opc == UO_AddrOf &&
  9705. (pty->getKind() == BuiltinType::Overload ||
  9706. pty->getKind() == BuiltinType::UnknownAny ||
  9707. pty->getKind() == BuiltinType::BoundMember))
  9708. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9709. // Anything else needs to be handled now.
  9710. ExprResult Result = CheckPlaceholderExpr(Input);
  9711. if (Result.isInvalid()) return ExprError();
  9712. Input = Result.get();
  9713. }
  9714. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  9715. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  9716. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  9717. // Find all of the overloaded operators visible from this
  9718. // point. We perform both an operator-name lookup from the local
  9719. // scope and an argument-dependent lookup based on the types of
  9720. // the arguments.
  9721. UnresolvedSet<16> Functions;
  9722. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  9723. if (S && OverOp != OO_None)
  9724. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  9725. Functions);
  9726. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  9727. }
  9728. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  9729. }
  9730. // Unary Operators. 'Tok' is the token for the operator.
  9731. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  9732. tok::TokenKind Op, Expr *Input) {
  9733. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  9734. }
  9735. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  9736. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  9737. LabelDecl *TheDecl) {
  9738. TheDecl->markUsed(Context);
  9739. // Create the AST node. The address of a label always has type 'void*'.
  9740. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  9741. Context.getPointerType(Context.VoidTy));
  9742. }
  9743. /// Given the last statement in a statement-expression, check whether
  9744. /// the result is a producing expression (like a call to an
  9745. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  9746. /// release out of the full-expression. Otherwise, return null.
  9747. /// Cannot fail.
  9748. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  9749. // Should always be wrapped with one of these.
  9750. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  9751. if (!cleanups) return nullptr;
  9752. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  9753. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  9754. return nullptr;
  9755. // Splice out the cast. This shouldn't modify any interesting
  9756. // features of the statement.
  9757. Expr *producer = cast->getSubExpr();
  9758. assert(producer->getType() == cast->getType());
  9759. assert(producer->getValueKind() == cast->getValueKind());
  9760. cleanups->setSubExpr(producer);
  9761. return cleanups;
  9762. }
  9763. void Sema::ActOnStartStmtExpr() {
  9764. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  9765. }
  9766. void Sema::ActOnStmtExprError() {
  9767. // Note that function is also called by TreeTransform when leaving a
  9768. // StmtExpr scope without rebuilding anything.
  9769. DiscardCleanupsInEvaluationContext();
  9770. PopExpressionEvaluationContext();
  9771. }
  9772. ExprResult
  9773. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  9774. SourceLocation RPLoc) { // "({..})"
  9775. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  9776. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  9777. if (hasAnyUnrecoverableErrorsInThisFunction())
  9778. DiscardCleanupsInEvaluationContext();
  9779. assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
  9780. PopExpressionEvaluationContext();
  9781. // FIXME: there are a variety of strange constraints to enforce here, for
  9782. // example, it is not possible to goto into a stmt expression apparently.
  9783. // More semantic analysis is needed.
  9784. // If there are sub-stmts in the compound stmt, take the type of the last one
  9785. // as the type of the stmtexpr.
  9786. QualType Ty = Context.VoidTy;
  9787. bool StmtExprMayBindToTemp = false;
  9788. if (!Compound->body_empty()) {
  9789. Stmt *LastStmt = Compound->body_back();
  9790. LabelStmt *LastLabelStmt = nullptr;
  9791. // If LastStmt is a label, skip down through into the body.
  9792. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  9793. LastLabelStmt = Label;
  9794. LastStmt = Label->getSubStmt();
  9795. }
  9796. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  9797. // Do function/array conversion on the last expression, but not
  9798. // lvalue-to-rvalue. However, initialize an unqualified type.
  9799. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  9800. if (LastExpr.isInvalid())
  9801. return ExprError();
  9802. Ty = LastExpr.get()->getType().getUnqualifiedType();
  9803. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  9804. // In ARC, if the final expression ends in a consume, splice
  9805. // the consume out and bind it later. In the alternate case
  9806. // (when dealing with a retainable type), the result
  9807. // initialization will create a produce. In both cases the
  9808. // result will be +1, and we'll need to balance that out with
  9809. // a bind.
  9810. if (Expr *rebuiltLastStmt
  9811. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  9812. LastExpr = rebuiltLastStmt;
  9813. } else {
  9814. LastExpr = PerformCopyInitialization(
  9815. InitializedEntity::InitializeResult(LPLoc,
  9816. Ty,
  9817. false),
  9818. SourceLocation(),
  9819. LastExpr);
  9820. }
  9821. if (LastExpr.isInvalid())
  9822. return ExprError();
  9823. if (LastExpr.get() != nullptr) {
  9824. if (!LastLabelStmt)
  9825. Compound->setLastStmt(LastExpr.get());
  9826. else
  9827. LastLabelStmt->setSubStmt(LastExpr.get());
  9828. StmtExprMayBindToTemp = true;
  9829. }
  9830. }
  9831. }
  9832. }
  9833. // FIXME: Check that expression type is complete/non-abstract; statement
  9834. // expressions are not lvalues.
  9835. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  9836. if (StmtExprMayBindToTemp)
  9837. return MaybeBindToTemporary(ResStmtExpr);
  9838. return ResStmtExpr;
  9839. }
  9840. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  9841. TypeSourceInfo *TInfo,
  9842. OffsetOfComponent *CompPtr,
  9843. unsigned NumComponents,
  9844. SourceLocation RParenLoc) {
  9845. QualType ArgTy = TInfo->getType();
  9846. bool Dependent = ArgTy->isDependentType();
  9847. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  9848. // We must have at least one component that refers to the type, and the first
  9849. // one is known to be a field designator. Verify that the ArgTy represents
  9850. // a struct/union/class.
  9851. if (!Dependent && !ArgTy->isRecordType())
  9852. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  9853. << ArgTy << TypeRange);
  9854. // Type must be complete per C99 7.17p3 because a declaring a variable
  9855. // with an incomplete type would be ill-formed.
  9856. if (!Dependent
  9857. && RequireCompleteType(BuiltinLoc, ArgTy,
  9858. diag::err_offsetof_incomplete_type, TypeRange))
  9859. return ExprError();
  9860. // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
  9861. // GCC extension, diagnose them.
  9862. // FIXME: This diagnostic isn't actually visible because the location is in
  9863. // a system header!
  9864. if (NumComponents != 1)
  9865. Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
  9866. << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
  9867. bool DidWarnAboutNonPOD = false;
  9868. QualType CurrentType = ArgTy;
  9869. typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
  9870. SmallVector<OffsetOfNode, 4> Comps;
  9871. SmallVector<Expr*, 4> Exprs;
  9872. for (unsigned i = 0; i != NumComponents; ++i) {
  9873. const OffsetOfComponent &OC = CompPtr[i];
  9874. if (OC.isBrackets) {
  9875. // Offset of an array sub-field. TODO: Should we allow vector elements?
  9876. if (!CurrentType->isDependentType()) {
  9877. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  9878. if(!AT)
  9879. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  9880. << CurrentType);
  9881. CurrentType = AT->getElementType();
  9882. } else
  9883. CurrentType = Context.DependentTy;
  9884. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  9885. if (IdxRval.isInvalid())
  9886. return ExprError();
  9887. Expr *Idx = IdxRval.get();
  9888. // The expression must be an integral expression.
  9889. // FIXME: An integral constant expression?
  9890. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  9891. !Idx->getType()->isIntegerType())
  9892. return ExprError(Diag(Idx->getLocStart(),
  9893. diag::err_typecheck_subscript_not_integer)
  9894. << Idx->getSourceRange());
  9895. // Record this array index.
  9896. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  9897. Exprs.push_back(Idx);
  9898. continue;
  9899. }
  9900. // Offset of a field.
  9901. if (CurrentType->isDependentType()) {
  9902. // We have the offset of a field, but we can't look into the dependent
  9903. // type. Just record the identifier of the field.
  9904. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  9905. CurrentType = Context.DependentTy;
  9906. continue;
  9907. }
  9908. // We need to have a complete type to look into.
  9909. if (RequireCompleteType(OC.LocStart, CurrentType,
  9910. diag::err_offsetof_incomplete_type))
  9911. return ExprError();
  9912. // Look for the designated field.
  9913. const RecordType *RC = CurrentType->getAs<RecordType>();
  9914. if (!RC)
  9915. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  9916. << CurrentType);
  9917. RecordDecl *RD = RC->getDecl();
  9918. // C++ [lib.support.types]p5:
  9919. // The macro offsetof accepts a restricted set of type arguments in this
  9920. // International Standard. type shall be a POD structure or a POD union
  9921. // (clause 9).
  9922. // C++11 [support.types]p4:
  9923. // If type is not a standard-layout class (Clause 9), the results are
  9924. // undefined.
  9925. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9926. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  9927. unsigned DiagID =
  9928. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  9929. : diag::ext_offsetof_non_pod_type;
  9930. if (!IsSafe && !DidWarnAboutNonPOD &&
  9931. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  9932. PDiag(DiagID)
  9933. << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
  9934. << CurrentType))
  9935. DidWarnAboutNonPOD = true;
  9936. }
  9937. // Look for the field.
  9938. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  9939. LookupQualifiedName(R, RD);
  9940. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  9941. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  9942. if (!MemberDecl) {
  9943. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  9944. MemberDecl = IndirectMemberDecl->getAnonField();
  9945. }
  9946. if (!MemberDecl)
  9947. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  9948. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  9949. OC.LocEnd));
  9950. // C99 7.17p3:
  9951. // (If the specified member is a bit-field, the behavior is undefined.)
  9952. //
  9953. // We diagnose this as an error.
  9954. if (MemberDecl->isBitField()) {
  9955. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  9956. << MemberDecl->getDeclName()
  9957. << SourceRange(BuiltinLoc, RParenLoc);
  9958. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  9959. return ExprError();
  9960. }
  9961. RecordDecl *Parent = MemberDecl->getParent();
  9962. if (IndirectMemberDecl)
  9963. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  9964. // If the member was found in a base class, introduce OffsetOfNodes for
  9965. // the base class indirections.
  9966. CXXBasePaths Paths;
  9967. if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
  9968. if (Paths.getDetectedVirtual()) {
  9969. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  9970. << MemberDecl->getDeclName()
  9971. << SourceRange(BuiltinLoc, RParenLoc);
  9972. return ExprError();
  9973. }
  9974. CXXBasePath &Path = Paths.front();
  9975. for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
  9976. B != BEnd; ++B)
  9977. Comps.push_back(OffsetOfNode(B->Base));
  9978. }
  9979. if (IndirectMemberDecl) {
  9980. for (auto *FI : IndirectMemberDecl->chain()) {
  9981. assert(isa<FieldDecl>(FI));
  9982. Comps.push_back(OffsetOfNode(OC.LocStart,
  9983. cast<FieldDecl>(FI), OC.LocEnd));
  9984. }
  9985. } else
  9986. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  9987. CurrentType = MemberDecl->getType().getNonReferenceType();
  9988. }
  9989. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  9990. Comps, Exprs, RParenLoc);
  9991. }
  9992. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  9993. SourceLocation BuiltinLoc,
  9994. SourceLocation TypeLoc,
  9995. ParsedType ParsedArgTy,
  9996. OffsetOfComponent *CompPtr,
  9997. unsigned NumComponents,
  9998. SourceLocation RParenLoc) {
  9999. TypeSourceInfo *ArgTInfo;
  10000. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  10001. if (ArgTy.isNull())
  10002. return ExprError();
  10003. if (!ArgTInfo)
  10004. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  10005. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
  10006. RParenLoc);
  10007. }
  10008. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  10009. Expr *CondExpr,
  10010. Expr *LHSExpr, Expr *RHSExpr,
  10011. SourceLocation RPLoc) {
  10012. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  10013. ExprValueKind VK = VK_RValue;
  10014. ExprObjectKind OK = OK_Ordinary;
  10015. QualType resType;
  10016. bool ValueDependent = false;
  10017. bool CondIsTrue = false;
  10018. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  10019. resType = Context.DependentTy;
  10020. ValueDependent = true;
  10021. } else {
  10022. // The conditional expression is required to be a constant expression.
  10023. llvm::APSInt condEval(32);
  10024. ExprResult CondICE
  10025. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  10026. diag::err_typecheck_choose_expr_requires_constant, false);
  10027. if (CondICE.isInvalid())
  10028. return ExprError();
  10029. CondExpr = CondICE.get();
  10030. CondIsTrue = condEval.getZExtValue();
  10031. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  10032. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  10033. resType = ActiveExpr->getType();
  10034. ValueDependent = ActiveExpr->isValueDependent();
  10035. VK = ActiveExpr->getValueKind();
  10036. OK = ActiveExpr->getObjectKind();
  10037. }
  10038. return new (Context)
  10039. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  10040. CondIsTrue, resType->isDependentType(), ValueDependent);
  10041. }
  10042. //===----------------------------------------------------------------------===//
  10043. // Clang Extensions.
  10044. //===----------------------------------------------------------------------===//
  10045. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  10046. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  10047. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  10048. if (LangOpts.CPlusPlus) {
  10049. Decl *ManglingContextDecl;
  10050. if (MangleNumberingContext *MCtx =
  10051. getCurrentMangleNumberContext(Block->getDeclContext(),
  10052. ManglingContextDecl)) {
  10053. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  10054. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  10055. }
  10056. }
  10057. PushBlockScope(CurScope, Block);
  10058. CurContext->addDecl(Block);
  10059. if (CurScope)
  10060. PushDeclContext(CurScope, Block);
  10061. else
  10062. CurContext = Block;
  10063. getCurBlock()->HasImplicitReturnType = true;
  10064. // Enter a new evaluation context to insulate the block from any
  10065. // cleanups from the enclosing full-expression.
  10066. PushExpressionEvaluationContext(PotentiallyEvaluated);
  10067. }
  10068. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  10069. Scope *CurScope) {
  10070. assert(ParamInfo.getIdentifier() == nullptr &&
  10071. "block-id should have no identifier!");
  10072. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  10073. BlockScopeInfo *CurBlock = getCurBlock();
  10074. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  10075. QualType T = Sig->getType();
  10076. // FIXME: We should allow unexpanded parameter packs here, but that would,
  10077. // in turn, make the block expression contain unexpanded parameter packs.
  10078. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  10079. // Drop the parameters.
  10080. FunctionProtoType::ExtProtoInfo EPI;
  10081. EPI.HasTrailingReturn = false;
  10082. EPI.TypeQuals |= DeclSpec::TQ_const;
  10083. T = Context.getFunctionType(Context.DependentTy, None, EPI, None); // HLSL Change - add param mods
  10084. Sig = Context.getTrivialTypeSourceInfo(T);
  10085. }
  10086. // GetTypeForDeclarator always produces a function type for a block
  10087. // literal signature. Furthermore, it is always a FunctionProtoType
  10088. // unless the function was written with a typedef.
  10089. assert(T->isFunctionType() &&
  10090. "GetTypeForDeclarator made a non-function block signature");
  10091. // Look for an explicit signature in that function type.
  10092. FunctionProtoTypeLoc ExplicitSignature;
  10093. TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
  10094. if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
  10095. // Check whether that explicit signature was synthesized by
  10096. // GetTypeForDeclarator. If so, don't save that as part of the
  10097. // written signature.
  10098. if (ExplicitSignature.getLocalRangeBegin() ==
  10099. ExplicitSignature.getLocalRangeEnd()) {
  10100. // This would be much cheaper if we stored TypeLocs instead of
  10101. // TypeSourceInfos.
  10102. TypeLoc Result = ExplicitSignature.getReturnLoc();
  10103. unsigned Size = Result.getFullDataSize();
  10104. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  10105. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  10106. ExplicitSignature = FunctionProtoTypeLoc();
  10107. }
  10108. }
  10109. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  10110. CurBlock->FunctionType = T;
  10111. const FunctionType *Fn = T->getAs<FunctionType>();
  10112. QualType RetTy = Fn->getReturnType();
  10113. bool isVariadic =
  10114. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  10115. CurBlock->TheDecl->setIsVariadic(isVariadic);
  10116. // Context.DependentTy is used as a placeholder for a missing block
  10117. // return type. TODO: what should we do with declarators like:
  10118. // ^ * { ... }
  10119. // If the answer is "apply template argument deduction"....
  10120. if (RetTy != Context.DependentTy) {
  10121. CurBlock->ReturnType = RetTy;
  10122. CurBlock->TheDecl->setBlockMissingReturnType(false);
  10123. CurBlock->HasImplicitReturnType = false;
  10124. }
  10125. // Push block parameters from the declarator if we had them.
  10126. SmallVector<ParmVarDecl*, 8> Params;
  10127. if (ExplicitSignature) {
  10128. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  10129. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  10130. if (Param->getIdentifier() == nullptr &&
  10131. !Param->isImplicit() &&
  10132. !Param->isInvalidDecl() &&
  10133. !getLangOpts().CPlusPlus)
  10134. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  10135. Params.push_back(Param);
  10136. }
  10137. // Fake up parameter variables if we have a typedef, like
  10138. // ^ fntype { ... }
  10139. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  10140. for (const auto &I : Fn->param_types()) {
  10141. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  10142. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  10143. Params.push_back(Param);
  10144. }
  10145. }
  10146. // Set the parameters on the block decl.
  10147. if (!Params.empty()) {
  10148. CurBlock->TheDecl->setParams(Params);
  10149. CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
  10150. CurBlock->TheDecl->param_end(),
  10151. /*CheckParameterNames=*/false);
  10152. }
  10153. // Finally we can process decl attributes.
  10154. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  10155. // Put the parameter variables in scope.
  10156. for (auto AI : CurBlock->TheDecl->params()) {
  10157. AI->setOwningFunction(CurBlock->TheDecl);
  10158. // If this has an identifier, add it to the scope stack.
  10159. if (AI->getIdentifier()) {
  10160. CheckShadow(CurBlock->TheScope, AI);
  10161. PushOnScopeChains(AI, CurBlock->TheScope);
  10162. }
  10163. }
  10164. }
  10165. /// ActOnBlockError - If there is an error parsing a block, this callback
  10166. /// is invoked to pop the information about the block from the action impl.
  10167. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  10168. // Leave the expression-evaluation context.
  10169. DiscardCleanupsInEvaluationContext();
  10170. PopExpressionEvaluationContext();
  10171. // Pop off CurBlock, handle nested blocks.
  10172. PopDeclContext();
  10173. PopFunctionScopeInfo();
  10174. }
  10175. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  10176. /// literal was successfully completed. ^(int x){...}
  10177. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  10178. Stmt *Body, Scope *CurScope) {
  10179. // HLSL Changes Start
  10180. llvm_unreachable("block statements unsupported and unreachable in HLSL");
  10181. #if 0
  10182. // HLSL Changes End
  10183. // If blocks are disabled, emit an error.
  10184. if (!LangOpts.Blocks)
  10185. Diag(CaretLoc, diag::err_blocks_disable);
  10186. // Leave the expression-evaluation context.
  10187. if (hasAnyUnrecoverableErrorsInThisFunction())
  10188. DiscardCleanupsInEvaluationContext();
  10189. assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
  10190. PopExpressionEvaluationContext();
  10191. if (getLangOpts().HLSL) {
  10192. return ExprError();
  10193. }
  10194. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  10195. if (BSI->HasImplicitReturnType)
  10196. deduceClosureReturnType(*BSI);
  10197. PopDeclContext();
  10198. QualType RetTy = Context.VoidTy;
  10199. if (!BSI->ReturnType.isNull())
  10200. RetTy = BSI->ReturnType;
  10201. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  10202. QualType BlockTy;
  10203. // Set the captured variables on the block.
  10204. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  10205. SmallVector<BlockDecl::Capture, 4> Captures;
  10206. for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
  10207. CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
  10208. if (Cap.isThisCapture())
  10209. continue;
  10210. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  10211. Cap.isNested(), Cap.getInitExpr());
  10212. Captures.push_back(NewCap);
  10213. }
  10214. BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
  10215. BSI->CXXThisCaptureIndex != 0);
  10216. // If the user wrote a function type in some form, try to use that.
  10217. if (!BSI->FunctionType.isNull()) {
  10218. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  10219. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  10220. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  10221. // Turn protoless block types into nullary block types.
  10222. if (isa<FunctionNoProtoType>(FTy)) {
  10223. FunctionProtoType::ExtProtoInfo EPI;
  10224. EPI.ExtInfo = Ext;
  10225. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10226. // Otherwise, if we don't need to change anything about the function type,
  10227. // preserve its sugar structure.
  10228. } else if (FTy->getReturnType() == RetTy &&
  10229. (!NoReturn || FTy->getNoReturnAttr())) {
  10230. BlockTy = BSI->FunctionType;
  10231. // Otherwise, make the minimal modifications to the function type.
  10232. } else {
  10233. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  10234. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10235. EPI.TypeQuals = 0; // FIXME: silently?
  10236. EPI.ExtInfo = Ext;
  10237. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  10238. }
  10239. // If we don't have a function type, just build one from nothing.
  10240. } else {
  10241. FunctionProtoType::ExtProtoInfo EPI;
  10242. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  10243. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  10244. }
  10245. DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
  10246. BSI->TheDecl->param_end());
  10247. BlockTy = Context.getBlockPointerType(BlockTy);
  10248. // If needed, diagnose invalid gotos and switches in the block.
  10249. if (getCurFunction()->NeedsScopeChecking() &&
  10250. !PP.isCodeCompletionEnabled())
  10251. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  10252. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  10253. // Try to apply the named return value optimization. We have to check again
  10254. // if we can do this, though, because blocks keep return statements around
  10255. // to deduce an implicit return type.
  10256. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  10257. !BSI->TheDecl->isDependentContext())
  10258. computeNRVO(Body, BSI);
  10259. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  10260. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10261. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  10262. // If the block isn't obviously global, i.e. it captures anything at
  10263. // all, then we need to do a few things in the surrounding context:
  10264. if (Result->getBlockDecl()->hasCaptures()) {
  10265. // First, this expression has a new cleanup object.
  10266. ExprCleanupObjects.push_back(Result->getBlockDecl());
  10267. ExprNeedsCleanups = true;
  10268. // It also gets a branch-protected scope if any of the captured
  10269. // variables needs destruction.
  10270. for (const auto &CI : Result->getBlockDecl()->captures()) {
  10271. const VarDecl *var = CI.getVariable();
  10272. if (var->getType().isDestructedType() != QualType::DK_none) {
  10273. getCurFunction()->setHasBranchProtectedScope();
  10274. break;
  10275. }
  10276. }
  10277. }
  10278. return Result;
  10279. #endif // HLSL Change
  10280. }
  10281. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
  10282. Expr *E, ParsedType Ty,
  10283. SourceLocation RPLoc) {
  10284. TypeSourceInfo *TInfo;
  10285. GetTypeFromParser(Ty, &TInfo);
  10286. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  10287. }
  10288. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  10289. Expr *E, TypeSourceInfo *TInfo,
  10290. SourceLocation RPLoc) {
  10291. Expr *OrigExpr = E;
  10292. // Get the va_list type
  10293. QualType VaListType = Context.getBuiltinVaListType();
  10294. if (VaListType->isArrayType()) {
  10295. // Deal with implicit array decay; for example, on x86-64,
  10296. // va_list is an array, but it's supposed to decay to
  10297. // a pointer for va_arg.
  10298. VaListType = Context.getArrayDecayedType(VaListType);
  10299. // Make sure the input expression also decays appropriately.
  10300. ExprResult Result = UsualUnaryConversions(E);
  10301. if (Result.isInvalid())
  10302. return ExprError();
  10303. E = Result.get();
  10304. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  10305. // If va_list is a record type and we are compiling in C++ mode,
  10306. // check the argument using reference binding.
  10307. InitializedEntity Entity
  10308. = InitializedEntity::InitializeParameter(Context,
  10309. Context.getLValueReferenceType(VaListType), false);
  10310. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  10311. if (Init.isInvalid())
  10312. return ExprError();
  10313. E = Init.getAs<Expr>();
  10314. } else {
  10315. // Otherwise, the va_list argument must be an l-value because
  10316. // it is modified by va_arg.
  10317. if (!E->isTypeDependent() &&
  10318. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  10319. return ExprError();
  10320. }
  10321. if (!E->isTypeDependent() &&
  10322. !Context.hasSameType(VaListType, E->getType())) {
  10323. return ExprError(Diag(E->getLocStart(),
  10324. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  10325. << OrigExpr->getType() << E->getSourceRange());
  10326. }
  10327. if (!TInfo->getType()->isDependentType()) {
  10328. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  10329. diag::err_second_parameter_to_va_arg_incomplete,
  10330. TInfo->getTypeLoc()))
  10331. return ExprError();
  10332. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  10333. TInfo->getType(),
  10334. diag::err_second_parameter_to_va_arg_abstract,
  10335. TInfo->getTypeLoc()))
  10336. return ExprError();
  10337. if (!TInfo->getType().isPODType(Context)) {
  10338. Diag(TInfo->getTypeLoc().getBeginLoc(),
  10339. TInfo->getType()->isObjCLifetimeType()
  10340. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  10341. : diag::warn_second_parameter_to_va_arg_not_pod)
  10342. << TInfo->getType()
  10343. << TInfo->getTypeLoc().getSourceRange();
  10344. }
  10345. // Check for va_arg where arguments of the given type will be promoted
  10346. // (i.e. this va_arg is guaranteed to have undefined behavior).
  10347. QualType PromoteType;
  10348. if (TInfo->getType()->isPromotableIntegerType()) {
  10349. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  10350. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  10351. PromoteType = QualType();
  10352. }
  10353. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  10354. PromoteType = Context.DoubleTy;
  10355. if (!PromoteType.isNull())
  10356. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  10357. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  10358. << TInfo->getType()
  10359. << PromoteType
  10360. << TInfo->getTypeLoc().getSourceRange());
  10361. }
  10362. QualType T = TInfo->getType().getNonLValueExprType(Context);
  10363. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
  10364. }
  10365. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  10366. // The type of __null will be int or long, depending on the size of
  10367. // pointers on the target.
  10368. QualType Ty;
  10369. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  10370. if (pw == Context.getTargetInfo().getIntWidth())
  10371. Ty = Context.IntTy;
  10372. else if (pw == Context.getTargetInfo().getLongWidth())
  10373. Ty = Context.LongTy;
  10374. else if (pw == Context.getTargetInfo().getLongLongWidth())
  10375. Ty = Context.LongLongTy;
  10376. else {
  10377. llvm_unreachable("I don't know size of pointer!");
  10378. }
  10379. return new (Context) GNUNullExpr(Ty, TokenLoc);
  10380. }
  10381. bool
  10382. Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
  10383. if (!getLangOpts().ObjC1)
  10384. return false;
  10385. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  10386. if (!PT)
  10387. return false;
  10388. if (!PT->isObjCIdType()) {
  10389. // Check if the destination is the 'NSString' interface.
  10390. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  10391. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  10392. return false;
  10393. }
  10394. // Ignore any parens, implicit casts (should only be
  10395. // array-to-pointer decays), and not-so-opaque values. The last is
  10396. // important for making this trigger for property assignments.
  10397. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  10398. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  10399. if (OV->getSourceExpr())
  10400. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  10401. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  10402. if (!SL || !SL->isAscii())
  10403. return false;
  10404. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  10405. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  10406. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  10407. return true;
  10408. }
  10409. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  10410. SourceLocation Loc,
  10411. QualType DstType, QualType SrcType,
  10412. Expr *SrcExpr, AssignmentAction Action,
  10413. bool *Complained) {
  10414. if (Complained)
  10415. *Complained = false;
  10416. // Decode the result (notice that AST's are still created for extensions).
  10417. bool CheckInferredResultType = false;
  10418. bool isInvalid = false;
  10419. unsigned DiagKind = 0;
  10420. FixItHint Hint;
  10421. ConversionFixItGenerator ConvHints;
  10422. bool MayHaveConvFixit = false;
  10423. bool MayHaveFunctionDiff = false;
  10424. const ObjCInterfaceDecl *IFace = nullptr;
  10425. const ObjCProtocolDecl *PDecl = nullptr;
  10426. // HLSL Change Starts
  10427. if (LangOpts.HLSL) {
  10428. hlsl::DiagnoseAssignmentResultForHLSL(this, ConvTy, Loc, DstType, SrcType, SrcExpr, Action, Complained);
  10429. }
  10430. // HLSL Change Ends
  10431. switch (ConvTy) {
  10432. case Compatible:
  10433. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  10434. return false;
  10435. case PointerToInt:
  10436. DiagKind = diag::ext_typecheck_convert_pointer_int;
  10437. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10438. MayHaveConvFixit = true;
  10439. break;
  10440. case IntToPointer:
  10441. DiagKind = diag::ext_typecheck_convert_int_pointer;
  10442. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10443. MayHaveConvFixit = true;
  10444. break;
  10445. case IncompatiblePointer:
  10446. DiagKind =
  10447. (Action == AA_Passing_CFAudited ?
  10448. diag::err_arc_typecheck_convert_incompatible_pointer :
  10449. diag::ext_typecheck_convert_incompatible_pointer);
  10450. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  10451. SrcType->isObjCObjectPointerType();
  10452. if (Hint.isNull() && !CheckInferredResultType) {
  10453. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10454. }
  10455. else if (CheckInferredResultType) {
  10456. SrcType = SrcType.getUnqualifiedType();
  10457. DstType = DstType.getUnqualifiedType();
  10458. }
  10459. MayHaveConvFixit = true;
  10460. break;
  10461. case IncompatiblePointerSign:
  10462. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  10463. break;
  10464. case FunctionVoidPointer:
  10465. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  10466. break;
  10467. case IncompatiblePointerDiscardsQualifiers: {
  10468. // Perform array-to-pointer decay if necessary.
  10469. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  10470. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  10471. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  10472. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  10473. DiagKind = diag::err_typecheck_incompatible_address_space;
  10474. break;
  10475. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  10476. DiagKind = diag::err_typecheck_incompatible_ownership;
  10477. break;
  10478. }
  10479. llvm_unreachable("unknown error case for discarding qualifiers!");
  10480. // fallthrough
  10481. }
  10482. case CompatiblePointerDiscardsQualifiers:
  10483. // If the qualifiers lost were because we were applying the
  10484. // (deprecated) C++ conversion from a string literal to a char*
  10485. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  10486. // Ideally, this check would be performed in
  10487. // checkPointerTypesForAssignment. However, that would require a
  10488. // bit of refactoring (so that the second argument is an
  10489. // expression, rather than a type), which should be done as part
  10490. // of a larger effort to fix checkPointerTypesForAssignment for
  10491. // C++ semantics.
  10492. if (getLangOpts().CPlusPlus &&
  10493. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  10494. return false;
  10495. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  10496. break;
  10497. case IncompatibleNestedPointerQualifiers:
  10498. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  10499. break;
  10500. case IntToBlockPointer:
  10501. DiagKind = diag::err_int_to_block_pointer;
  10502. break;
  10503. case IncompatibleBlockPointer:
  10504. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  10505. break;
  10506. case IncompatibleObjCQualifiedId: {
  10507. if (SrcType->isObjCQualifiedIdType()) {
  10508. const ObjCObjectPointerType *srcOPT =
  10509. SrcType->getAs<ObjCObjectPointerType>();
  10510. for (auto *srcProto : srcOPT->quals()) {
  10511. PDecl = srcProto;
  10512. break;
  10513. }
  10514. if (const ObjCInterfaceType *IFaceT =
  10515. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10516. IFace = IFaceT->getDecl();
  10517. }
  10518. else if (DstType->isObjCQualifiedIdType()) {
  10519. const ObjCObjectPointerType *dstOPT =
  10520. DstType->getAs<ObjCObjectPointerType>();
  10521. for (auto *dstProto : dstOPT->quals()) {
  10522. PDecl = dstProto;
  10523. break;
  10524. }
  10525. if (const ObjCInterfaceType *IFaceT =
  10526. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  10527. IFace = IFaceT->getDecl();
  10528. }
  10529. DiagKind = diag::warn_incompatible_qualified_id;
  10530. break;
  10531. }
  10532. case IncompatibleVectors:
  10533. DiagKind = diag::warn_incompatible_vectors;
  10534. break;
  10535. case IncompatibleObjCWeakRef:
  10536. DiagKind = diag::err_arc_weak_unavailable_assign;
  10537. break;
  10538. case Incompatible:
  10539. DiagKind = diag::err_typecheck_convert_incompatible;
  10540. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  10541. MayHaveConvFixit = true;
  10542. isInvalid = true;
  10543. MayHaveFunctionDiff = true;
  10544. break;
  10545. }
  10546. QualType FirstType, SecondType;
  10547. switch (Action) {
  10548. case AA_Assigning:
  10549. case AA_Initializing:
  10550. // The destination type comes first.
  10551. FirstType = DstType;
  10552. SecondType = SrcType;
  10553. break;
  10554. case AA_Returning:
  10555. case AA_Passing:
  10556. case AA_Passing_CFAudited:
  10557. case AA_Converting:
  10558. case AA_Sending:
  10559. case AA_Casting:
  10560. // The source type comes first.
  10561. FirstType = SrcType;
  10562. SecondType = DstType;
  10563. break;
  10564. }
  10565. PartialDiagnostic FDiag = PDiag(DiagKind);
  10566. if (Action == AA_Passing_CFAudited)
  10567. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  10568. else
  10569. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  10570. // If we can fix the conversion, suggest the FixIts.
  10571. assert(ConvHints.isNull() || Hint.isNull());
  10572. if (!ConvHints.isNull()) {
  10573. for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
  10574. HE = ConvHints.Hints.end(); HI != HE; ++HI)
  10575. FDiag << *HI;
  10576. } else {
  10577. FDiag << Hint;
  10578. }
  10579. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  10580. if (MayHaveFunctionDiff)
  10581. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  10582. Diag(Loc, FDiag);
  10583. if (DiagKind == diag::warn_incompatible_qualified_id &&
  10584. PDecl && IFace && !IFace->hasDefinition())
  10585. Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
  10586. << IFace->getName() << PDecl->getName();
  10587. if (SecondType == Context.OverloadTy)
  10588. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  10589. FirstType);
  10590. if (CheckInferredResultType)
  10591. EmitRelatedResultTypeNote(SrcExpr);
  10592. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  10593. EmitRelatedResultTypeNoteForReturn(DstType);
  10594. if (Complained)
  10595. *Complained = true;
  10596. return isInvalid;
  10597. }
  10598. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10599. llvm::APSInt *Result) {
  10600. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  10601. public:
  10602. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10603. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  10604. }
  10605. } Diagnoser;
  10606. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  10607. }
  10608. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  10609. llvm::APSInt *Result,
  10610. unsigned DiagID,
  10611. bool AllowFold) {
  10612. class IDDiagnoser : public VerifyICEDiagnoser {
  10613. unsigned DiagID;
  10614. public:
  10615. IDDiagnoser(unsigned DiagID)
  10616. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  10617. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  10618. S.Diag(Loc, DiagID) << SR;
  10619. }
  10620. } Diagnoser(DiagID);
  10621. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  10622. }
  10623. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  10624. SourceRange SR) {
  10625. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  10626. }
  10627. ExprResult
  10628. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  10629. VerifyICEDiagnoser &Diagnoser,
  10630. bool AllowFold) {
  10631. SourceLocation DiagLoc = E->getLocStart();
  10632. if (getLangOpts().CPlusPlus11) {
  10633. // C++11 [expr.const]p5:
  10634. // If an expression of literal class type is used in a context where an
  10635. // integral constant expression is required, then that class type shall
  10636. // have a single non-explicit conversion function to an integral or
  10637. // unscoped enumeration type
  10638. ExprResult Converted;
  10639. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  10640. public:
  10641. CXX11ConvertDiagnoser(bool Silent)
  10642. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  10643. Silent, true) {}
  10644. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10645. QualType T) override {
  10646. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  10647. }
  10648. SemaDiagnosticBuilder diagnoseIncomplete(
  10649. Sema &S, SourceLocation Loc, QualType T) override {
  10650. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  10651. }
  10652. SemaDiagnosticBuilder diagnoseExplicitConv(
  10653. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10654. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  10655. }
  10656. SemaDiagnosticBuilder noteExplicitConv(
  10657. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10658. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10659. << ConvTy->isEnumeralType() << ConvTy;
  10660. }
  10661. SemaDiagnosticBuilder diagnoseAmbiguous(
  10662. Sema &S, SourceLocation Loc, QualType T) override {
  10663. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  10664. }
  10665. SemaDiagnosticBuilder noteAmbiguous(
  10666. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  10667. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  10668. << ConvTy->isEnumeralType() << ConvTy;
  10669. }
  10670. SemaDiagnosticBuilder diagnoseConversion(
  10671. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  10672. llvm_unreachable("conversion functions are permitted");
  10673. }
  10674. } ConvertDiagnoser(Diagnoser.Suppress);
  10675. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  10676. ConvertDiagnoser);
  10677. if (Converted.isInvalid())
  10678. return Converted;
  10679. E = Converted.get();
  10680. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  10681. return ExprError();
  10682. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  10683. // An ICE must be of integral or unscoped enumeration type.
  10684. if (!Diagnoser.Suppress)
  10685. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10686. return ExprError();
  10687. }
  10688. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  10689. // in the non-ICE case.
  10690. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  10691. if (Result)
  10692. *Result = E->EvaluateKnownConstInt(Context);
  10693. return E;
  10694. }
  10695. Expr::EvalResult EvalResult;
  10696. SmallVector<PartialDiagnosticAt, 8> Notes;
  10697. EvalResult.Diag = &Notes;
  10698. // Try to evaluate the expression, and produce diagnostics explaining why it's
  10699. // not a constant expression as a side-effect.
  10700. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  10701. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  10702. // In C++11, we can rely on diagnostics being produced for any expression
  10703. // which is not a constant expression. If no diagnostics were produced, then
  10704. // this is a constant expression.
  10705. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  10706. if (Result)
  10707. *Result = EvalResult.Val.getInt();
  10708. return E;
  10709. }
  10710. // If our only note is the usual "invalid subexpression" note, just point
  10711. // the caret at its location rather than producing an essentially
  10712. // redundant note.
  10713. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10714. diag::note_invalid_subexpr_in_const_expr) {
  10715. DiagLoc = Notes[0].first;
  10716. Notes.clear();
  10717. }
  10718. if (!Folded || !AllowFold) {
  10719. if (!Diagnoser.Suppress) {
  10720. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  10721. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10722. Diag(Notes[I].first, Notes[I].second);
  10723. }
  10724. return ExprError();
  10725. }
  10726. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  10727. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10728. Diag(Notes[I].first, Notes[I].second);
  10729. if (Result)
  10730. *Result = EvalResult.Val.getInt();
  10731. return E;
  10732. }
  10733. namespace {
  10734. // Handle the case where we conclude a expression which we speculatively
  10735. // considered to be unevaluated is actually evaluated.
  10736. class TransformToPE : public TreeTransform<TransformToPE> {
  10737. typedef TreeTransform<TransformToPE> BaseTransform;
  10738. public:
  10739. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  10740. // Make sure we redo semantic analysis
  10741. bool AlwaysRebuild() { return true; }
  10742. // Make sure we handle LabelStmts correctly.
  10743. // FIXME: This does the right thing, but maybe we need a more general
  10744. // fix to TreeTransform?
  10745. StmtResult TransformLabelStmt(LabelStmt *S) {
  10746. S->getDecl()->setStmt(nullptr);
  10747. return BaseTransform::TransformLabelStmt(S);
  10748. }
  10749. // We need to special-case DeclRefExprs referring to FieldDecls which
  10750. // are not part of a member pointer formation; normal TreeTransforming
  10751. // doesn't catch this case because of the way we represent them in the AST.
  10752. // FIXME: This is a bit ugly; is it really the best way to handle this
  10753. // case?
  10754. //
  10755. // Error on DeclRefExprs referring to FieldDecls.
  10756. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  10757. if (isa<FieldDecl>(E->getDecl()) &&
  10758. !SemaRef.isUnevaluatedContext())
  10759. return SemaRef.Diag(E->getLocation(),
  10760. diag::err_invalid_non_static_member_use)
  10761. << E->getDecl() << E->getSourceRange();
  10762. return BaseTransform::TransformDeclRefExpr(E);
  10763. }
  10764. // Exception: filter out member pointer formation
  10765. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  10766. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  10767. return E;
  10768. return BaseTransform::TransformUnaryOperator(E);
  10769. }
  10770. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  10771. // Lambdas never need to be transformed.
  10772. return E;
  10773. }
  10774. };
  10775. }
  10776. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  10777. assert(isUnevaluatedContext() &&
  10778. "Should only transform unevaluated expressions");
  10779. ExprEvalContexts.back().Context =
  10780. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  10781. if (isUnevaluatedContext())
  10782. return E;
  10783. return TransformToPE(*this).TransformExpr(E);
  10784. }
  10785. void
  10786. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10787. Decl *LambdaContextDecl,
  10788. bool IsDecltype) {
  10789. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
  10790. ExprNeedsCleanups, LambdaContextDecl,
  10791. IsDecltype);
  10792. ExprNeedsCleanups = false;
  10793. if (!MaybeODRUseExprs.empty())
  10794. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  10795. }
  10796. void
  10797. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  10798. ReuseLambdaContextDecl_t,
  10799. bool IsDecltype) {
  10800. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  10801. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  10802. }
  10803. void Sema::PopExpressionEvaluationContext() {
  10804. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  10805. unsigned NumTypos = Rec.NumTypos;
  10806. if (!Rec.Lambdas.empty()) {
  10807. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10808. unsigned D;
  10809. if (Rec.isUnevaluated()) {
  10810. // C++11 [expr.prim.lambda]p2:
  10811. // A lambda-expression shall not appear in an unevaluated operand
  10812. // (Clause 5).
  10813. D = diag::err_lambda_unevaluated_operand;
  10814. } else {
  10815. // C++1y [expr.const]p2:
  10816. // A conditional-expression e is a core constant expression unless the
  10817. // evaluation of e, following the rules of the abstract machine, would
  10818. // evaluate [...] a lambda-expression.
  10819. D = diag::err_lambda_in_constant_expression;
  10820. }
  10821. for (const auto *L : Rec.Lambdas)
  10822. Diag(L->getLocStart(), D);
  10823. } else {
  10824. // Mark the capture expressions odr-used. This was deferred
  10825. // during lambda expression creation.
  10826. for (auto *Lambda : Rec.Lambdas) {
  10827. for (auto *C : Lambda->capture_inits())
  10828. MarkDeclarationsReferencedInExpr(C);
  10829. }
  10830. }
  10831. }
  10832. // When are coming out of an unevaluated context, clear out any
  10833. // temporaries that we may have created as part of the evaluation of
  10834. // the expression in that context: they aren't relevant because they
  10835. // will never be constructed.
  10836. if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
  10837. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  10838. ExprCleanupObjects.end());
  10839. ExprNeedsCleanups = Rec.ParentNeedsCleanups;
  10840. CleanupVarDeclMarking();
  10841. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  10842. // Otherwise, merge the contexts together.
  10843. } else {
  10844. ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
  10845. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  10846. Rec.SavedMaybeODRUseExprs.end());
  10847. }
  10848. // Pop the current expression evaluation context off the stack.
  10849. ExprEvalContexts.pop_back();
  10850. if (!ExprEvalContexts.empty())
  10851. ExprEvalContexts.back().NumTypos += NumTypos;
  10852. else
  10853. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  10854. "last ExpressionEvaluationContextRecord");
  10855. }
  10856. void Sema::DiscardCleanupsInEvaluationContext() {
  10857. ExprCleanupObjects.erase(
  10858. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  10859. ExprCleanupObjects.end());
  10860. ExprNeedsCleanups = false;
  10861. MaybeODRUseExprs.clear();
  10862. }
  10863. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  10864. if (!E->getType()->isVariablyModifiedType())
  10865. return E;
  10866. return TransformToPotentiallyEvaluated(E);
  10867. }
  10868. static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
  10869. // Do not mark anything as "used" within a dependent context; wait for
  10870. // an instantiation.
  10871. if (SemaRef.CurContext->isDependentContext())
  10872. return false;
  10873. switch (SemaRef.ExprEvalContexts.back().Context) {
  10874. case Sema::Unevaluated:
  10875. case Sema::UnevaluatedAbstract:
  10876. // We are in an expression that is not potentially evaluated; do nothing.
  10877. // (Depending on how you read the standard, we actually do need to do
  10878. // something here for null pointer constants, but the standard's
  10879. // definition of a null pointer constant is completely crazy.)
  10880. return false;
  10881. case Sema::ConstantEvaluated:
  10882. case Sema::PotentiallyEvaluated:
  10883. // We are in a potentially evaluated expression (or a constant-expression
  10884. // in C++03); we need to do implicit template instantiation, implicitly
  10885. // define class members, and mark most declarations as used.
  10886. return true;
  10887. case Sema::PotentiallyEvaluatedIfUsed:
  10888. // Referenced declarations will only be used if the construct in the
  10889. // containing expression is used.
  10890. return false;
  10891. }
  10892. llvm_unreachable("Invalid context");
  10893. }
  10894. /// \brief Mark a function referenced, and check whether it is odr-used
  10895. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  10896. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  10897. bool OdrUse) {
  10898. assert(Func && "No function?");
  10899. Func->setReferenced();
  10900. // C++11 [basic.def.odr]p3:
  10901. // A function whose name appears as a potentially-evaluated expression is
  10902. // odr-used if it is the unique lookup result or the selected member of a
  10903. // set of overloaded functions [...].
  10904. //
  10905. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  10906. // can just check that here. Skip the rest of this function if we've already
  10907. // marked the function as used.
  10908. if (Func->isUsed(/*CheckUsedAttr=*/false) ||
  10909. !IsPotentiallyEvaluatedContext(*this)) {
  10910. // C++11 [temp.inst]p3:
  10911. // Unless a function template specialization has been explicitly
  10912. // instantiated or explicitly specialized, the function template
  10913. // specialization is implicitly instantiated when the specialization is
  10914. // referenced in a context that requires a function definition to exist.
  10915. //
  10916. // We consider constexpr function templates to be referenced in a context
  10917. // that requires a definition to exist whenever they are referenced.
  10918. //
  10919. // FIXME: This instantiates constexpr functions too frequently. If this is
  10920. // really an unevaluated context (and we're not just in the definition of a
  10921. // function template or overload resolution or other cases which we
  10922. // incorrectly consider to be unevaluated contexts), and we're not in a
  10923. // subexpression which we actually need to evaluate (for instance, a
  10924. // template argument, array bound or an expression in a braced-init-list),
  10925. // we are not permitted to instantiate this constexpr function definition.
  10926. //
  10927. // FIXME: This also implicitly defines special members too frequently. They
  10928. // are only supposed to be implicitly defined if they are odr-used, but they
  10929. // are not odr-used from constant expressions in unevaluated contexts.
  10930. // However, they cannot be referenced if they are deleted, and they are
  10931. // deleted whenever the implicit definition of the special member would
  10932. // fail.
  10933. if (!Func->isConstexpr() || Func->getBody())
  10934. return;
  10935. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  10936. if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
  10937. return;
  10938. }
  10939. // Note that this declaration has been used.
  10940. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  10941. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  10942. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  10943. if (Constructor->isDefaultConstructor()) {
  10944. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  10945. return;
  10946. DefineImplicitDefaultConstructor(Loc, Constructor);
  10947. } else if (Constructor->isCopyConstructor()) {
  10948. DefineImplicitCopyConstructor(Loc, Constructor);
  10949. } else if (Constructor->isMoveConstructor()) {
  10950. DefineImplicitMoveConstructor(Loc, Constructor);
  10951. }
  10952. } else if (Constructor->getInheritedConstructor()) {
  10953. DefineInheritingConstructor(Loc, Constructor);
  10954. }
  10955. } else if (CXXDestructorDecl *Destructor =
  10956. dyn_cast<CXXDestructorDecl>(Func)) {
  10957. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  10958. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  10959. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  10960. return;
  10961. DefineImplicitDestructor(Loc, Destructor);
  10962. }
  10963. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  10964. MarkVTableUsed(Loc, Destructor->getParent());
  10965. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  10966. if (MethodDecl->isOverloadedOperator() &&
  10967. MethodDecl->getOverloadedOperator() == OO_Equal) {
  10968. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  10969. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  10970. if (MethodDecl->isCopyAssignmentOperator())
  10971. DefineImplicitCopyAssignment(Loc, MethodDecl);
  10972. else
  10973. DefineImplicitMoveAssignment(Loc, MethodDecl);
  10974. }
  10975. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  10976. MethodDecl->getParent()->isLambda()) {
  10977. CXXConversionDecl *Conversion =
  10978. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  10979. if (Conversion->isLambdaToBlockPointerConversion())
  10980. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  10981. else
  10982. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  10983. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  10984. MarkVTableUsed(Loc, MethodDecl->getParent());
  10985. }
  10986. // Recursive functions should be marked when used from another function.
  10987. // FIXME: Is this really right?
  10988. if (CurContext == Func) return;
  10989. // Resolve the exception specification for any function which is
  10990. // used: CodeGen will need it.
  10991. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  10992. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  10993. ResolveExceptionSpec(Loc, FPT);
  10994. if (!OdrUse) return;
  10995. // Implicit instantiation of function templates and member functions of
  10996. // class templates.
  10997. if (Func->isImplicitlyInstantiable()) {
  10998. bool AlreadyInstantiated = false;
  10999. SourceLocation PointOfInstantiation = Loc;
  11000. if (FunctionTemplateSpecializationInfo *SpecInfo
  11001. = Func->getTemplateSpecializationInfo()) {
  11002. if (SpecInfo->getPointOfInstantiation().isInvalid())
  11003. SpecInfo->setPointOfInstantiation(Loc);
  11004. else if (SpecInfo->getTemplateSpecializationKind()
  11005. == TSK_ImplicitInstantiation) {
  11006. AlreadyInstantiated = true;
  11007. PointOfInstantiation = SpecInfo->getPointOfInstantiation();
  11008. }
  11009. } else if (MemberSpecializationInfo *MSInfo
  11010. = Func->getMemberSpecializationInfo()) {
  11011. if (MSInfo->getPointOfInstantiation().isInvalid())
  11012. MSInfo->setPointOfInstantiation(Loc);
  11013. else if (MSInfo->getTemplateSpecializationKind()
  11014. == TSK_ImplicitInstantiation) {
  11015. AlreadyInstantiated = true;
  11016. PointOfInstantiation = MSInfo->getPointOfInstantiation();
  11017. }
  11018. }
  11019. if (!AlreadyInstantiated || Func->isConstexpr()) {
  11020. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  11021. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  11022. ActiveTemplateInstantiations.size())
  11023. PendingLocalImplicitInstantiations.push_back(
  11024. std::make_pair(Func, PointOfInstantiation));
  11025. else if (Func->isConstexpr())
  11026. // Do not defer instantiations of constexpr functions, to avoid the
  11027. // expression evaluator needing to call back into Sema if it sees a
  11028. // call to such a function.
  11029. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  11030. else {
  11031. PendingInstantiations.push_back(std::make_pair(Func,
  11032. PointOfInstantiation));
  11033. // Notify the consumer that a function was implicitly instantiated.
  11034. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  11035. }
  11036. }
  11037. } else {
  11038. // Walk redefinitions, as some of them may be instantiable.
  11039. for (auto i : Func->redecls()) {
  11040. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  11041. MarkFunctionReferenced(Loc, i);
  11042. }
  11043. }
  11044. // Keep track of used but undefined functions.
  11045. if (!Func->isDefined()) {
  11046. if (mightHaveNonExternalLinkage(Func))
  11047. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11048. else if (Func->getMostRecentDecl()->isInlined() &&
  11049. !LangOpts.GNUInline &&
  11050. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  11051. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  11052. }
  11053. // Normally the most current decl is marked used while processing the use and
  11054. // any subsequent decls are marked used by decl merging. This fails with
  11055. // template instantiation since marking can happen at the end of the file
  11056. // and, because of the two phase lookup, this function is called with at
  11057. // decl in the middle of a decl chain. We loop to maintain the invariant
  11058. // that once a decl is used, all decls after it are also used.
  11059. for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
  11060. F->markUsed(Context);
  11061. if (F == Func)
  11062. break;
  11063. }
  11064. }
  11065. static void
  11066. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  11067. VarDecl *var, DeclContext *DC) {
  11068. DeclContext *VarDC = var->getDeclContext();
  11069. // If the parameter still belongs to the translation unit, then
  11070. // we're actually just using one parameter in the declaration of
  11071. // the next.
  11072. if (isa<ParmVarDecl>(var) &&
  11073. isa<TranslationUnitDecl>(VarDC))
  11074. return;
  11075. // For C code, don't diagnose about capture if we're not actually in code
  11076. // right now; it's impossible to write a non-constant expression outside of
  11077. // function context, so we'll get other (more useful) diagnostics later.
  11078. //
  11079. // For C++, things get a bit more nasty... it would be nice to suppress this
  11080. // diagnostic for certain cases like using a local variable in an array bound
  11081. // for a member of a local class, but the correct predicate is not obvious.
  11082. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  11083. return;
  11084. if (isa<CXXMethodDecl>(VarDC) &&
  11085. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  11086. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
  11087. << var->getIdentifier();
  11088. } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
  11089. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
  11090. << var->getIdentifier() << fn->getDeclName();
  11091. } else if (isa<BlockDecl>(VarDC)) {
  11092. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
  11093. << var->getIdentifier();
  11094. } else {
  11095. // FIXME: Is there any other context where a local variable can be
  11096. // declared?
  11097. S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
  11098. << var->getIdentifier();
  11099. }
  11100. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  11101. << var->getIdentifier();
  11102. // FIXME: Add additional diagnostic info about class etc. which prevents
  11103. // capture.
  11104. }
  11105. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  11106. bool &SubCapturesAreNested,
  11107. QualType &CaptureType,
  11108. QualType &DeclRefType) {
  11109. // Check whether we've already captured it.
  11110. if (CSI->CaptureMap.count(Var)) {
  11111. // If we found a capture, any subcaptures are nested.
  11112. SubCapturesAreNested = true;
  11113. // Retrieve the capture type for this variable.
  11114. CaptureType = CSI->getCapture(Var).getCaptureType();
  11115. // Compute the type of an expression that refers to this variable.
  11116. DeclRefType = CaptureType.getNonReferenceType();
  11117. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  11118. if (Cap.isCopyCapture() &&
  11119. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
  11120. DeclRefType.addConst();
  11121. return true;
  11122. }
  11123. return false;
  11124. }
  11125. // Only block literals, captured statements, and lambda expressions can
  11126. // capture; other scopes don't work.
  11127. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  11128. SourceLocation Loc,
  11129. const bool Diagnose, Sema &S) {
  11130. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  11131. return getLambdaAwareParentOfDeclContext(DC);
  11132. else if (Var->hasLocalStorage()) {
  11133. if (Diagnose)
  11134. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  11135. }
  11136. return nullptr;
  11137. }
  11138. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11139. // certain types of variables (unnamed, variably modified types etc.)
  11140. // so check for eligibility.
  11141. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  11142. SourceLocation Loc,
  11143. const bool Diagnose, Sema &S) {
  11144. bool IsBlock = isa<BlockScopeInfo>(CSI);
  11145. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  11146. // Lambdas are not allowed to capture unnamed variables
  11147. // (e.g. anonymous unions).
  11148. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  11149. // assuming that's the intent.
  11150. if (IsLambda && !Var->getDeclName()) {
  11151. if (Diagnose) {
  11152. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  11153. S.Diag(Var->getLocation(), diag::note_declared_at);
  11154. }
  11155. return false;
  11156. }
  11157. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  11158. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  11159. if (Diagnose) {
  11160. S.Diag(Loc, diag::err_ref_vm_type);
  11161. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11162. << Var->getDeclName();
  11163. }
  11164. return false;
  11165. }
  11166. // Prohibit structs with flexible array members too.
  11167. // We cannot capture what is in the tail end of the struct.
  11168. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  11169. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  11170. if (Diagnose) {
  11171. if (IsBlock)
  11172. S.Diag(Loc, diag::err_ref_flexarray_type);
  11173. else
  11174. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  11175. << Var->getDeclName();
  11176. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11177. << Var->getDeclName();
  11178. }
  11179. return false;
  11180. }
  11181. }
  11182. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11183. // Lambdas and captured statements are not allowed to capture __block
  11184. // variables; they don't support the expected semantics.
  11185. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  11186. if (Diagnose) {
  11187. S.Diag(Loc, diag::err_capture_block_variable)
  11188. << Var->getDeclName() << !IsLambda;
  11189. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11190. << Var->getDeclName();
  11191. }
  11192. return false;
  11193. }
  11194. return true;
  11195. }
  11196. // Returns true if the capture by block was successful.
  11197. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  11198. SourceLocation Loc,
  11199. const bool BuildAndDiagnose,
  11200. QualType &CaptureType,
  11201. QualType &DeclRefType,
  11202. const bool Nested,
  11203. Sema &S) {
  11204. Expr *CopyExpr = nullptr;
  11205. bool ByRef = false;
  11206. // Blocks are not allowed to capture arrays.
  11207. if (CaptureType->isArrayType()) {
  11208. if (BuildAndDiagnose) {
  11209. S.Diag(Loc, diag::err_ref_array_type);
  11210. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11211. << Var->getDeclName();
  11212. }
  11213. return false;
  11214. }
  11215. // Forbid the block-capture of autoreleasing variables.
  11216. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11217. if (BuildAndDiagnose) {
  11218. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  11219. << /*block*/ 0;
  11220. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11221. << Var->getDeclName();
  11222. }
  11223. return false;
  11224. }
  11225. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  11226. if (HasBlocksAttr || CaptureType->isReferenceType()) {
  11227. // Block capture by reference does not change the capture or
  11228. // declaration reference types.
  11229. ByRef = true;
  11230. } else {
  11231. // Block capture by copy introduces 'const'.
  11232. CaptureType = CaptureType.getNonReferenceType().withConst();
  11233. DeclRefType = CaptureType;
  11234. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  11235. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  11236. // The capture logic needs the destructor, so make sure we mark it.
  11237. // Usually this is unnecessary because most local variables have
  11238. // their destructors marked at declaration time, but parameters are
  11239. // an exception because it's technically only the call site that
  11240. // actually requires the destructor.
  11241. if (isa<ParmVarDecl>(Var))
  11242. S.FinalizeVarWithDestructor(Var, Record);
  11243. // Enter a new evaluation context to insulate the copy
  11244. // full-expression.
  11245. EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
  11246. // According to the blocks spec, the capture of a variable from
  11247. // the stack requires a const copy constructor. This is not true
  11248. // of the copy/move done to move a __block variable to the heap.
  11249. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  11250. DeclRefType.withConst(),
  11251. VK_LValue, Loc);
  11252. ExprResult Result
  11253. = S.PerformCopyInitialization(
  11254. InitializedEntity::InitializeBlock(Var->getLocation(),
  11255. CaptureType, false),
  11256. Loc, DeclRef);
  11257. // Build a full-expression copy expression if initialization
  11258. // succeeded and used a non-trivial constructor. Recover from
  11259. // errors by pretending that the copy isn't necessary.
  11260. if (!Result.isInvalid() &&
  11261. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  11262. ->isTrivial()) {
  11263. Result = S.MaybeCreateExprWithCleanups(Result);
  11264. CopyExpr = Result.get();
  11265. }
  11266. }
  11267. }
  11268. }
  11269. // Actually capture the variable.
  11270. if (BuildAndDiagnose)
  11271. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  11272. SourceLocation(), CaptureType, CopyExpr);
  11273. return true;
  11274. }
  11275. /// \brief Capture the given variable in the captured region.
  11276. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  11277. VarDecl *Var,
  11278. SourceLocation Loc,
  11279. const bool BuildAndDiagnose,
  11280. QualType &CaptureType,
  11281. QualType &DeclRefType,
  11282. const bool RefersToCapturedVariable,
  11283. Sema &S) {
  11284. // By default, capture variables by reference.
  11285. bool ByRef = true;
  11286. // Using an LValue reference type is consistent with Lambdas (see below).
  11287. if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var))
  11288. DeclRefType = DeclRefType.getUnqualifiedType();
  11289. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11290. Expr *CopyExpr = nullptr;
  11291. if (BuildAndDiagnose) {
  11292. // The current implementation assumes that all variables are captured
  11293. // by references. Since there is no capture by copy, no expression
  11294. // evaluation will be needed.
  11295. RecordDecl *RD = RSI->TheRecordDecl;
  11296. FieldDecl *Field
  11297. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  11298. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  11299. nullptr, false, ICIS_NoInit);
  11300. Field->setImplicit(true);
  11301. Field->setAccess(AS_private);
  11302. RD->addDecl(Field);
  11303. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  11304. DeclRefType, VK_LValue, Loc);
  11305. Var->setReferenced(true);
  11306. Var->markUsed(S.Context);
  11307. }
  11308. // Actually capture the variable.
  11309. if (BuildAndDiagnose)
  11310. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  11311. SourceLocation(), CaptureType, CopyExpr);
  11312. return true;
  11313. }
  11314. /// \brief Create a field within the lambda class for the variable
  11315. /// being captured.
  11316. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
  11317. QualType FieldType, QualType DeclRefType,
  11318. SourceLocation Loc,
  11319. bool RefersToCapturedVariable) {
  11320. CXXRecordDecl *Lambda = LSI->Lambda;
  11321. // Build the non-static data member.
  11322. FieldDecl *Field
  11323. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  11324. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  11325. nullptr, false, ICIS_NoInit);
  11326. Field->setImplicit(true);
  11327. Field->setAccess(AS_private);
  11328. Lambda->addDecl(Field);
  11329. }
  11330. /// \brief Capture the given variable in the lambda.
  11331. static bool captureInLambda(LambdaScopeInfo *LSI,
  11332. VarDecl *Var,
  11333. SourceLocation Loc,
  11334. const bool BuildAndDiagnose,
  11335. QualType &CaptureType,
  11336. QualType &DeclRefType,
  11337. const bool RefersToCapturedVariable,
  11338. const Sema::TryCaptureKind Kind,
  11339. SourceLocation EllipsisLoc,
  11340. const bool IsTopScope,
  11341. Sema &S) {
  11342. // Determine whether we are capturing by reference or by value.
  11343. bool ByRef = false;
  11344. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  11345. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  11346. } else {
  11347. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  11348. }
  11349. // Compute the type of the field that will capture this variable.
  11350. if (ByRef) {
  11351. // C++11 [expr.prim.lambda]p15:
  11352. // An entity is captured by reference if it is implicitly or
  11353. // explicitly captured but not captured by copy. It is
  11354. // unspecified whether additional unnamed non-static data
  11355. // members are declared in the closure type for entities
  11356. // captured by reference.
  11357. //
  11358. // FIXME: It is not clear whether we want to build an lvalue reference
  11359. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  11360. // to do the former, while EDG does the latter. Core issue 1249 will
  11361. // clarify, but for now we follow GCC because it's a more permissive and
  11362. // easily defensible position.
  11363. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  11364. } else {
  11365. // C++11 [expr.prim.lambda]p14:
  11366. // For each entity captured by copy, an unnamed non-static
  11367. // data member is declared in the closure type. The
  11368. // declaration order of these members is unspecified. The type
  11369. // of such a data member is the type of the corresponding
  11370. // captured entity if the entity is not a reference to an
  11371. // object, or the referenced type otherwise. [Note: If the
  11372. // captured entity is a reference to a function, the
  11373. // corresponding data member is also a reference to a
  11374. // function. - end note ]
  11375. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  11376. if (!RefType->getPointeeType()->isFunctionType())
  11377. CaptureType = RefType->getPointeeType();
  11378. }
  11379. // Forbid the lambda copy-capture of autoreleasing variables.
  11380. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  11381. if (BuildAndDiagnose) {
  11382. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  11383. S.Diag(Var->getLocation(), diag::note_previous_decl)
  11384. << Var->getDeclName();
  11385. }
  11386. return false;
  11387. }
  11388. // Make sure that by-copy captures are of a complete and non-abstract type.
  11389. if (BuildAndDiagnose) {
  11390. if (!CaptureType->isDependentType() &&
  11391. S.RequireCompleteType(Loc, CaptureType,
  11392. diag::err_capture_of_incomplete_type,
  11393. Var->getDeclName()))
  11394. return false;
  11395. if (S.RequireNonAbstractType(Loc, CaptureType,
  11396. diag::err_capture_of_abstract_type))
  11397. return false;
  11398. }
  11399. }
  11400. // Capture this variable in the lambda.
  11401. if (BuildAndDiagnose)
  11402. addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
  11403. RefersToCapturedVariable);
  11404. // Compute the type of a reference to this captured variable.
  11405. if (ByRef)
  11406. DeclRefType = CaptureType.getNonReferenceType();
  11407. else {
  11408. // C++ [expr.prim.lambda]p5:
  11409. // The closure type for a lambda-expression has a public inline
  11410. // function call operator [...]. This function call operator is
  11411. // declared const (9.3.1) if and only if the lambda-expression’s
  11412. // parameter-declaration-clause is not followed by mutable.
  11413. DeclRefType = CaptureType.getNonReferenceType();
  11414. if (!LSI->Mutable && !CaptureType->isReferenceType())
  11415. DeclRefType.addConst();
  11416. }
  11417. // Add the capture.
  11418. if (BuildAndDiagnose)
  11419. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  11420. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  11421. return true;
  11422. }
  11423. bool Sema::tryCaptureVariable(
  11424. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  11425. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  11426. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  11427. // An init-capture is notionally from the context surrounding its
  11428. // declaration, but its parent DC is the lambda class.
  11429. DeclContext *VarDC = Var->getDeclContext();
  11430. if (Var->isInitCapture())
  11431. VarDC = VarDC->getParent();
  11432. DeclContext *DC = CurContext;
  11433. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  11434. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  11435. // We need to sync up the Declaration Context with the
  11436. // FunctionScopeIndexToStopAt
  11437. if (FunctionScopeIndexToStopAt) {
  11438. unsigned FSIndex = FunctionScopes.size() - 1;
  11439. while (FSIndex != MaxFunctionScopesIndex) {
  11440. DC = getLambdaAwareParentOfDeclContext(DC);
  11441. --FSIndex;
  11442. }
  11443. }
  11444. // If the variable is declared in the current context, there is no need to
  11445. // capture it.
  11446. if (VarDC == DC) return true;
  11447. // Capture global variables if it is required to use private copy of this
  11448. // variable.
  11449. bool IsGlobal = !Var->hasLocalStorage();
  11450. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
  11451. return true;
  11452. // Walk up the stack to determine whether we can capture the variable,
  11453. // performing the "simple" checks that don't depend on type. We stop when
  11454. // we've either hit the declared scope of the variable or find an existing
  11455. // capture of that variable. We start from the innermost capturing-entity
  11456. // (the DC) and ensure that all intervening capturing-entities
  11457. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  11458. // declcontext can either capture the variable or have already captured
  11459. // the variable.
  11460. CaptureType = Var->getType();
  11461. DeclRefType = CaptureType.getNonReferenceType();
  11462. bool Nested = false;
  11463. bool Explicit = (Kind != TryCapture_Implicit);
  11464. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  11465. unsigned OpenMPLevel = 0;
  11466. do {
  11467. // Only block literals, captured statements, and lambda expressions can
  11468. // capture; other scopes don't work.
  11469. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  11470. ExprLoc,
  11471. BuildAndDiagnose,
  11472. *this);
  11473. // We need to check for the parent *first* because, if we *have*
  11474. // private-captured a global variable, we need to recursively capture it in
  11475. // intermediate blocks, lambdas, etc.
  11476. if (!ParentDC) {
  11477. if (IsGlobal) {
  11478. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  11479. break;
  11480. }
  11481. return true;
  11482. }
  11483. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  11484. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  11485. // Check whether we've already captured it.
  11486. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  11487. DeclRefType))
  11488. break;
  11489. if (getLangOpts().OpenMP) {
  11490. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11491. // OpenMP private variables should not be captured in outer scope, so
  11492. // just break here.
  11493. if (RSI->CapRegionKind == CR_OpenMP) {
  11494. if (isOpenMPPrivateVar(Var, OpenMPLevel)) {
  11495. Nested = true;
  11496. DeclRefType = DeclRefType.getUnqualifiedType();
  11497. CaptureType = Context.getLValueReferenceType(DeclRefType);
  11498. break;
  11499. }
  11500. ++OpenMPLevel;
  11501. }
  11502. }
  11503. }
  11504. // If we are instantiating a generic lambda call operator body,
  11505. // we do not want to capture new variables. What was captured
  11506. // during either a lambdas transformation or initial parsing
  11507. // should be used.
  11508. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  11509. if (BuildAndDiagnose) {
  11510. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11511. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  11512. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11513. Diag(Var->getLocation(), diag::note_previous_decl)
  11514. << Var->getDeclName();
  11515. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  11516. } else
  11517. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  11518. }
  11519. return true;
  11520. }
  11521. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  11522. // certain types of variables (unnamed, variably modified types etc.)
  11523. // so check for eligibility.
  11524. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  11525. return true;
  11526. // Try to capture variable-length arrays types.
  11527. if (Var->getType()->isVariablyModifiedType()) {
  11528. // We're going to walk down into the type and look for VLA
  11529. // expressions.
  11530. QualType QTy = Var->getType();
  11531. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  11532. QTy = PVD->getOriginalType();
  11533. do {
  11534. const Type *Ty = QTy.getTypePtr();
  11535. switch (Ty->getTypeClass()) {
  11536. #define TYPE(Class, Base)
  11537. #define ABSTRACT_TYPE(Class, Base)
  11538. #define NON_CANONICAL_TYPE(Class, Base)
  11539. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  11540. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  11541. #include "clang/AST/TypeNodes.def"
  11542. QTy = QualType();
  11543. break;
  11544. // These types are never variably-modified.
  11545. case Type::Builtin:
  11546. case Type::Complex:
  11547. case Type::Vector:
  11548. case Type::ExtVector:
  11549. case Type::Record:
  11550. case Type::Enum:
  11551. case Type::Elaborated:
  11552. case Type::TemplateSpecialization:
  11553. case Type::ObjCObject:
  11554. case Type::ObjCInterface:
  11555. case Type::ObjCObjectPointer:
  11556. llvm_unreachable("type class is never variably-modified!");
  11557. case Type::Adjusted:
  11558. QTy = cast<AdjustedType>(Ty)->getOriginalType();
  11559. break;
  11560. case Type::Decayed:
  11561. QTy = cast<DecayedType>(Ty)->getPointeeType();
  11562. break;
  11563. case Type::Pointer:
  11564. QTy = cast<PointerType>(Ty)->getPointeeType();
  11565. break;
  11566. case Type::BlockPointer:
  11567. QTy = cast<BlockPointerType>(Ty)->getPointeeType();
  11568. break;
  11569. case Type::LValueReference:
  11570. case Type::RValueReference:
  11571. QTy = cast<ReferenceType>(Ty)->getPointeeType();
  11572. break;
  11573. case Type::MemberPointer:
  11574. QTy = cast<MemberPointerType>(Ty)->getPointeeType();
  11575. break;
  11576. case Type::ConstantArray:
  11577. case Type::IncompleteArray:
  11578. // Losing element qualification here is fine.
  11579. QTy = cast<ArrayType>(Ty)->getElementType();
  11580. break;
  11581. case Type::VariableArray: {
  11582. // Losing element qualification here is fine.
  11583. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  11584. // Unknown size indication requires no size computation.
  11585. // Otherwise, evaluate and record it.
  11586. if (auto Size = VAT->getSizeExpr()) {
  11587. if (!CSI->isVLATypeCaptured(VAT)) {
  11588. RecordDecl *CapRecord = nullptr;
  11589. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  11590. CapRecord = LSI->Lambda;
  11591. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11592. CapRecord = CRSI->TheRecordDecl;
  11593. }
  11594. if (CapRecord) {
  11595. auto ExprLoc = Size->getExprLoc();
  11596. auto SizeType = Context.getSizeType();
  11597. // Build the non-static data member.
  11598. auto Field = FieldDecl::Create(
  11599. Context, CapRecord, ExprLoc, ExprLoc,
  11600. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  11601. /*BW*/ nullptr, /*Mutable*/ false,
  11602. /*InitStyle*/ ICIS_NoInit);
  11603. Field->setImplicit(true);
  11604. Field->setAccess(AS_private);
  11605. Field->setCapturedVLAType(VAT);
  11606. CapRecord->addDecl(Field);
  11607. CSI->addVLATypeCapture(ExprLoc, SizeType);
  11608. }
  11609. }
  11610. }
  11611. QTy = VAT->getElementType();
  11612. break;
  11613. }
  11614. case Type::FunctionProto:
  11615. case Type::FunctionNoProto:
  11616. QTy = cast<FunctionType>(Ty)->getReturnType();
  11617. break;
  11618. case Type::Paren:
  11619. case Type::TypeOf:
  11620. case Type::UnaryTransform:
  11621. case Type::Attributed:
  11622. case Type::SubstTemplateTypeParm:
  11623. case Type::PackExpansion:
  11624. // Keep walking after single level desugaring.
  11625. QTy = QTy.getSingleStepDesugaredType(getASTContext());
  11626. break;
  11627. case Type::Typedef:
  11628. QTy = cast<TypedefType>(Ty)->desugar();
  11629. break;
  11630. case Type::Decltype:
  11631. QTy = cast<DecltypeType>(Ty)->desugar();
  11632. break;
  11633. case Type::Auto:
  11634. QTy = cast<AutoType>(Ty)->getDeducedType();
  11635. break;
  11636. case Type::TypeOfExpr:
  11637. QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  11638. break;
  11639. case Type::Atomic:
  11640. QTy = cast<AtomicType>(Ty)->getValueType();
  11641. break;
  11642. }
  11643. } while (!QTy.isNull() && QTy->isVariablyModifiedType());
  11644. }
  11645. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  11646. // No capture-default, and this is not an explicit capture
  11647. // so cannot capture this variable.
  11648. if (BuildAndDiagnose) {
  11649. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  11650. Diag(Var->getLocation(), diag::note_previous_decl)
  11651. << Var->getDeclName();
  11652. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  11653. diag::note_lambda_decl);
  11654. // FIXME: If we error out because an outer lambda can not implicitly
  11655. // capture a variable that an inner lambda explicitly captures, we
  11656. // should have the inner lambda do the explicit capture - because
  11657. // it makes for cleaner diagnostics later. This would purely be done
  11658. // so that the diagnostic does not misleadingly claim that a variable
  11659. // can not be captured by a lambda implicitly even though it is captured
  11660. // explicitly. Suggestion:
  11661. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  11662. // at the function head
  11663. // - cache the StartingDeclContext - this must be a lambda
  11664. // - captureInLambda in the innermost lambda the variable.
  11665. }
  11666. return true;
  11667. }
  11668. FunctionScopesIndex--;
  11669. DC = ParentDC;
  11670. Explicit = false;
  11671. } while (!VarDC->Equals(DC));
  11672. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  11673. // computing the type of the capture at each step, checking type-specific
  11674. // requirements, and adding captures if requested.
  11675. // If the variable had already been captured previously, we start capturing
  11676. // at the lambda nested within that one.
  11677. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  11678. ++I) {
  11679. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  11680. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  11681. if (!captureInBlock(BSI, Var, ExprLoc,
  11682. BuildAndDiagnose, CaptureType,
  11683. DeclRefType, Nested, *this))
  11684. return true;
  11685. Nested = true;
  11686. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  11687. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  11688. BuildAndDiagnose, CaptureType,
  11689. DeclRefType, Nested, *this))
  11690. return true;
  11691. Nested = true;
  11692. } else {
  11693. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  11694. if (!captureInLambda(LSI, Var, ExprLoc,
  11695. BuildAndDiagnose, CaptureType,
  11696. DeclRefType, Nested, Kind, EllipsisLoc,
  11697. /*IsTopScope*/I == N - 1, *this))
  11698. return true;
  11699. Nested = true;
  11700. }
  11701. }
  11702. return false;
  11703. }
  11704. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  11705. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  11706. QualType CaptureType;
  11707. QualType DeclRefType;
  11708. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  11709. /*BuildAndDiagnose=*/true, CaptureType,
  11710. DeclRefType, nullptr);
  11711. }
  11712. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  11713. QualType CaptureType;
  11714. QualType DeclRefType;
  11715. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11716. /*BuildAndDiagnose=*/false, CaptureType,
  11717. DeclRefType, nullptr);
  11718. }
  11719. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  11720. QualType CaptureType;
  11721. QualType DeclRefType;
  11722. // Determine whether we can capture this variable.
  11723. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  11724. /*BuildAndDiagnose=*/false, CaptureType,
  11725. DeclRefType, nullptr))
  11726. return QualType();
  11727. return DeclRefType;
  11728. }
  11729. // If either the type of the variable or the initializer is dependent,
  11730. // return false. Otherwise, determine whether the variable is a constant
  11731. // expression. Use this if you need to know if a variable that might or
  11732. // might not be dependent is truly a constant expression.
  11733. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  11734. ASTContext &Context) {
  11735. if (Var->getType()->isDependentType())
  11736. return false;
  11737. const VarDecl *DefVD = nullptr;
  11738. Var->getAnyInitializer(DefVD);
  11739. if (!DefVD)
  11740. return false;
  11741. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  11742. Expr *Init = cast<Expr>(Eval->Value);
  11743. if (Init->isValueDependent())
  11744. return false;
  11745. return IsVariableAConstantExpression(Var, Context);
  11746. }
  11747. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  11748. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  11749. // an object that satisfies the requirements for appearing in a
  11750. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  11751. // is immediately applied." This function handles the lvalue-to-rvalue
  11752. // conversion part.
  11753. MaybeODRUseExprs.erase(E->IgnoreParens());
  11754. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  11755. // to a variable that is a constant expression, and if so, identify it as
  11756. // a reference to a variable that does not involve an odr-use of that
  11757. // variable.
  11758. if (LambdaScopeInfo *LSI = getCurLambda()) {
  11759. Expr *SansParensExpr = E->IgnoreParens();
  11760. VarDecl *Var = nullptr;
  11761. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  11762. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  11763. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  11764. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  11765. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  11766. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  11767. }
  11768. }
  11769. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  11770. Res = CorrectDelayedTyposInExpr(Res);
  11771. if (!Res.isUsable())
  11772. return Res;
  11773. // If a constant-expression is a reference to a variable where we delay
  11774. // deciding whether it is an odr-use, just assume we will apply the
  11775. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  11776. // (a non-type template argument), we have special handling anyway.
  11777. UpdateMarkingForLValueToRValue(Res.get());
  11778. return Res;
  11779. }
  11780. void Sema::CleanupVarDeclMarking() {
  11781. for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
  11782. e = MaybeODRUseExprs.end();
  11783. i != e; ++i) {
  11784. VarDecl *Var;
  11785. SourceLocation Loc;
  11786. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
  11787. Var = cast<VarDecl>(DRE->getDecl());
  11788. Loc = DRE->getLocation();
  11789. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
  11790. Var = cast<VarDecl>(ME->getMemberDecl());
  11791. Loc = ME->getMemberLoc();
  11792. } else {
  11793. llvm_unreachable("Unexpected expression");
  11794. }
  11795. MarkVarDeclODRUsed(Var, Loc, *this,
  11796. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  11797. }
  11798. MaybeODRUseExprs.clear();
  11799. }
  11800. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  11801. VarDecl *Var, Expr *E) {
  11802. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  11803. "Invalid Expr argument to DoMarkVarDeclReferenced");
  11804. Var->setReferenced();
  11805. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  11806. bool MarkODRUsed = true;
  11807. // If the context is not potentially evaluated, this is not an odr-use and
  11808. // does not trigger instantiation.
  11809. if (!IsPotentiallyEvaluatedContext(SemaRef)) {
  11810. if (SemaRef.isUnevaluatedContext())
  11811. return;
  11812. // If we don't yet know whether this context is going to end up being an
  11813. // evaluated context, and we're referencing a variable from an enclosing
  11814. // scope, add a potential capture.
  11815. //
  11816. // FIXME: Is this necessary? These contexts are only used for default
  11817. // arguments, where local variables can't be used.
  11818. const bool RefersToEnclosingScope =
  11819. (SemaRef.CurContext != Var->getDeclContext() &&
  11820. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  11821. if (RefersToEnclosingScope) {
  11822. if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
  11823. // If a variable could potentially be odr-used, defer marking it so
  11824. // until we finish analyzing the full expression for any
  11825. // lvalue-to-rvalue
  11826. // or discarded value conversions that would obviate odr-use.
  11827. // Add it to the list of potential captures that will be analyzed
  11828. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  11829. // unless the variable is a reference that was initialized by a constant
  11830. // expression (this will never need to be captured or odr-used).
  11831. assert(E && "Capture variable should be used in an expression.");
  11832. if (!Var->getType()->isReferenceType() ||
  11833. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  11834. LSI->addPotentialCapture(E->IgnoreParens());
  11835. }
  11836. }
  11837. if (!isTemplateInstantiation(TSK))
  11838. return;
  11839. // Instantiate, but do not mark as odr-used, variable templates.
  11840. MarkODRUsed = false;
  11841. }
  11842. VarTemplateSpecializationDecl *VarSpec =
  11843. dyn_cast<VarTemplateSpecializationDecl>(Var);
  11844. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  11845. "Can't instantiate a partial template specialization.");
  11846. // Perform implicit instantiation of static data members, static data member
  11847. // templates of class templates, and variable template specializations. Delay
  11848. // instantiations of variable templates, except for those that could be used
  11849. // in a constant expression.
  11850. if (isTemplateInstantiation(TSK)) {
  11851. bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
  11852. if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
  11853. if (Var->getPointOfInstantiation().isInvalid()) {
  11854. // This is a modification of an existing AST node. Notify listeners.
  11855. if (ASTMutationListener *L = SemaRef.getASTMutationListener())
  11856. L->StaticDataMemberInstantiated(Var);
  11857. } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
  11858. // Don't bother trying to instantiate it again, unless we might need
  11859. // its initializer before we get to the end of the TU.
  11860. TryInstantiating = false;
  11861. }
  11862. if (Var->getPointOfInstantiation().isInvalid())
  11863. Var->setTemplateSpecializationKind(TSK, Loc);
  11864. if (TryInstantiating) {
  11865. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  11866. bool InstantiationDependent = false;
  11867. bool IsNonDependent =
  11868. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  11869. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  11870. : true;
  11871. // Do not instantiate specializations that are still type-dependent.
  11872. if (IsNonDependent) {
  11873. if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
  11874. // Do not defer instantiations of variables which could be used in a
  11875. // constant expression.
  11876. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  11877. } else {
  11878. SemaRef.PendingInstantiations
  11879. .push_back(std::make_pair(Var, PointOfInstantiation));
  11880. }
  11881. }
  11882. }
  11883. }
  11884. if(!MarkODRUsed) return;
  11885. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  11886. // the requirements for appearing in a constant expression (5.19) and, if
  11887. // it is an object, the lvalue-to-rvalue conversion (4.1)
  11888. // is immediately applied." We check the first part here, and
  11889. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  11890. // Note that we use the C++11 definition everywhere because nothing in
  11891. // C++03 depends on whether we get the C++03 version correct. The second
  11892. // part does not apply to references, since they are not objects.
  11893. if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
  11894. // A reference initialized by a constant expression can never be
  11895. // odr-used, so simply ignore it.
  11896. if (!Var->getType()->isReferenceType())
  11897. SemaRef.MaybeODRUseExprs.insert(E);
  11898. } else
  11899. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  11900. /*MaxFunctionScopeIndex ptr*/ nullptr);
  11901. }
  11902. /// \brief Mark a variable referenced, and check whether it is odr-used
  11903. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  11904. /// used directly for normal expressions referring to VarDecl.
  11905. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  11906. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  11907. }
  11908. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  11909. Decl *D, Expr *E, bool OdrUse) {
  11910. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  11911. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  11912. return;
  11913. }
  11914. SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
  11915. // If this is a call to a method via a cast, also mark the method in the
  11916. // derived class used in case codegen can devirtualize the call.
  11917. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11918. if (!ME)
  11919. return;
  11920. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  11921. if (!MD)
  11922. return;
  11923. // Only attempt to devirtualize if this is truly a virtual call.
  11924. bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
  11925. if (!IsVirtualCall)
  11926. return;
  11927. const Expr *Base = ME->getBase();
  11928. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  11929. if (!MostDerivedClassDecl)
  11930. return;
  11931. CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
  11932. if (!DM || DM->isPure())
  11933. return;
  11934. SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
  11935. }
  11936. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  11937. void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
  11938. // TODO: update this with DR# once a defect report is filed.
  11939. // C++11 defect. The address of a pure member should not be an ODR use, even
  11940. // if it's a qualified reference.
  11941. bool OdrUse = true;
  11942. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  11943. if (Method->isVirtual())
  11944. OdrUse = false;
  11945. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  11946. }
  11947. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  11948. void Sema::MarkMemberReferenced(MemberExpr *E) {
  11949. // C++11 [basic.def.odr]p2:
  11950. // A non-overloaded function whose name appears as a potentially-evaluated
  11951. // expression or a member of a set of candidate functions, if selected by
  11952. // overload resolution when referred to from a potentially-evaluated
  11953. // expression, is odr-used, unless it is a pure virtual function and its
  11954. // name is not explicitly qualified.
  11955. bool OdrUse = true;
  11956. if (!E->hasQualifier()) {
  11957. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  11958. if (Method->isPure())
  11959. OdrUse = false;
  11960. }
  11961. SourceLocation Loc = E->getMemberLoc().isValid() ?
  11962. E->getMemberLoc() : E->getLocStart();
  11963. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
  11964. }
  11965. /// \brief Perform marking for a reference to an arbitrary declaration. It
  11966. /// marks the declaration referenced, and performs odr-use checking for
  11967. /// functions and variables. This method should not be used when building a
  11968. /// normal expression which refers to a variable.
  11969. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
  11970. if (OdrUse) {
  11971. if (auto *VD = dyn_cast<VarDecl>(D)) {
  11972. MarkVariableReferenced(Loc, VD);
  11973. return;
  11974. }
  11975. }
  11976. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  11977. MarkFunctionReferenced(Loc, FD, OdrUse);
  11978. return;
  11979. }
  11980. D->setReferenced();
  11981. }
  11982. namespace {
  11983. // Mark all of the declarations referenced
  11984. // FIXME: Not fully implemented yet! We need to have a better understanding
  11985. // of when we're entering
  11986. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  11987. Sema &S;
  11988. SourceLocation Loc;
  11989. public:
  11990. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  11991. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  11992. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  11993. bool TraverseRecordType(RecordType *T);
  11994. };
  11995. }
  11996. bool MarkReferencedDecls::TraverseTemplateArgument(
  11997. const TemplateArgument &Arg) {
  11998. if (Arg.getKind() == TemplateArgument::Declaration) {
  11999. if (Decl *D = Arg.getAsDecl())
  12000. S.MarkAnyDeclReferenced(Loc, D, true);
  12001. }
  12002. return Inherited::TraverseTemplateArgument(Arg);
  12003. }
  12004. bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
  12005. if (ClassTemplateSpecializationDecl *Spec
  12006. = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
  12007. const TemplateArgumentList &Args = Spec->getTemplateArgs();
  12008. return TraverseTemplateArguments(Args.data(), Args.size());
  12009. }
  12010. return true;
  12011. }
  12012. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  12013. MarkReferencedDecls Marker(*this, Loc);
  12014. Marker.TraverseType(Context.getCanonicalType(T));
  12015. }
  12016. namespace {
  12017. /// \brief Helper class that marks all of the declarations referenced by
  12018. /// potentially-evaluated subexpressions as "referenced".
  12019. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  12020. Sema &S;
  12021. bool SkipLocalVariables;
  12022. public:
  12023. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  12024. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  12025. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  12026. void VisitDeclRefExpr(DeclRefExpr *E) {
  12027. // If we were asked not to visit local variables, don't.
  12028. if (SkipLocalVariables) {
  12029. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  12030. if (VD->hasLocalStorage())
  12031. return;
  12032. }
  12033. S.MarkDeclRefReferenced(E);
  12034. }
  12035. void VisitMemberExpr(MemberExpr *E) {
  12036. S.MarkMemberReferenced(E);
  12037. Inherited::VisitMemberExpr(E);
  12038. }
  12039. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  12040. S.MarkFunctionReferenced(E->getLocStart(),
  12041. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  12042. Visit(E->getSubExpr());
  12043. }
  12044. void VisitCXXNewExpr(CXXNewExpr *E) {
  12045. if (E->getOperatorNew())
  12046. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  12047. if (E->getOperatorDelete())
  12048. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12049. Inherited::VisitCXXNewExpr(E);
  12050. }
  12051. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  12052. if (E->getOperatorDelete())
  12053. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  12054. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  12055. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  12056. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  12057. S.MarkFunctionReferenced(E->getLocStart(),
  12058. S.LookupDestructor(Record));
  12059. }
  12060. Inherited::VisitCXXDeleteExpr(E);
  12061. }
  12062. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  12063. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  12064. Inherited::VisitCXXConstructExpr(E);
  12065. }
  12066. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  12067. Visit(E->getExpr());
  12068. }
  12069. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12070. Inherited::VisitImplicitCastExpr(E);
  12071. if (E->getCastKind() == CK_LValueToRValue)
  12072. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  12073. }
  12074. };
  12075. }
  12076. /// \brief Mark any declarations that appear within this expression or any
  12077. /// potentially-evaluated subexpressions as "referenced".
  12078. ///
  12079. /// \param SkipLocalVariables If true, don't mark local variables as
  12080. /// 'referenced'.
  12081. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  12082. bool SkipLocalVariables) {
  12083. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  12084. }
  12085. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  12086. /// of the program being compiled.
  12087. ///
  12088. /// This routine emits the given diagnostic when the code currently being
  12089. /// type-checked is "potentially evaluated", meaning that there is a
  12090. /// possibility that the code will actually be executable. Code in sizeof()
  12091. /// expressions, code used only during overload resolution, etc., are not
  12092. /// potentially evaluated. This routine will suppress such diagnostics or,
  12093. /// in the absolutely nutty case of potentially potentially evaluated
  12094. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  12095. /// later.
  12096. ///
  12097. /// This routine should be used for all diagnostics that describe the run-time
  12098. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  12099. /// Failure to do so will likely result in spurious diagnostics or failures
  12100. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  12101. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  12102. const PartialDiagnostic &PD) {
  12103. switch (ExprEvalContexts.back().Context) {
  12104. case Unevaluated:
  12105. case UnevaluatedAbstract:
  12106. // The argument will never be evaluated, so don't complain.
  12107. break;
  12108. case ConstantEvaluated:
  12109. // Relevant diagnostics should be produced by constant evaluation.
  12110. break;
  12111. case PotentiallyEvaluated:
  12112. case PotentiallyEvaluatedIfUsed:
  12113. if (Statement && getCurFunctionOrMethodDecl()) {
  12114. FunctionScopes.back()->PossiblyUnreachableDiags.
  12115. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  12116. }
  12117. else
  12118. Diag(Loc, PD);
  12119. return true;
  12120. }
  12121. return false;
  12122. }
  12123. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  12124. CallExpr *CE, FunctionDecl *FD) {
  12125. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  12126. return false;
  12127. // If we're inside a decltype's expression, don't check for a valid return
  12128. // type or construct temporaries until we know whether this is the last call.
  12129. if (ExprEvalContexts.back().IsDecltype) {
  12130. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  12131. return false;
  12132. }
  12133. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  12134. FunctionDecl *FD;
  12135. CallExpr *CE;
  12136. public:
  12137. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  12138. : FD(FD), CE(CE) { }
  12139. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  12140. if (!FD) {
  12141. S.Diag(Loc, diag::err_call_incomplete_return)
  12142. << T << CE->getSourceRange();
  12143. return;
  12144. }
  12145. S.Diag(Loc, diag::err_call_function_incomplete_return)
  12146. << CE->getSourceRange() << FD->getDeclName() << T;
  12147. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  12148. << FD->getDeclName();
  12149. }
  12150. } Diagnoser(FD, CE);
  12151. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  12152. return true;
  12153. return false;
  12154. }
  12155. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  12156. // will prevent this condition from triggering, which is what we want.
  12157. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  12158. SourceLocation Loc;
  12159. unsigned diagnostic = diag::warn_condition_is_assignment;
  12160. bool IsOrAssign = false;
  12161. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  12162. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  12163. return;
  12164. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  12165. // Greylist some idioms by putting them into a warning subcategory.
  12166. if (ObjCMessageExpr *ME
  12167. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  12168. Selector Sel = ME->getSelector();
  12169. // self = [<foo> init...]
  12170. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  12171. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12172. // <foo> = [<bar> nextObject]
  12173. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  12174. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  12175. }
  12176. Loc = Op->getOperatorLoc();
  12177. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  12178. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  12179. return;
  12180. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  12181. Loc = Op->getOperatorLoc();
  12182. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  12183. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  12184. else {
  12185. // Not an assignment.
  12186. return;
  12187. }
  12188. Diag(Loc, diagnostic) << E->getSourceRange();
  12189. SourceLocation Open = E->getLocStart();
  12190. SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
  12191. Diag(Loc, diag::note_condition_assign_silence)
  12192. << FixItHint::CreateInsertion(Open, "(")
  12193. << FixItHint::CreateInsertion(Close, ")");
  12194. if (IsOrAssign)
  12195. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  12196. << FixItHint::CreateReplacement(Loc, "!=");
  12197. else
  12198. Diag(Loc, diag::note_condition_assign_to_comparison)
  12199. << FixItHint::CreateReplacement(Loc, "==");
  12200. }
  12201. /// \brief Redundant parentheses over an equality comparison can indicate
  12202. /// that the user intended an assignment used as condition.
  12203. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  12204. // Don't warn if the parens came from a macro.
  12205. SourceLocation parenLoc = ParenE->getLocStart();
  12206. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  12207. return;
  12208. // Don't warn for dependent expressions.
  12209. if (ParenE->isTypeDependent())
  12210. return;
  12211. Expr *E = ParenE->IgnoreParens();
  12212. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  12213. if (opE->getOpcode() == BO_EQ &&
  12214. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  12215. == Expr::MLV_Valid) {
  12216. SourceLocation Loc = opE->getOperatorLoc();
  12217. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  12218. SourceRange ParenERange = ParenE->getSourceRange();
  12219. Diag(Loc, diag::note_equality_comparison_silence)
  12220. << FixItHint::CreateRemoval(ParenERange.getBegin())
  12221. << FixItHint::CreateRemoval(ParenERange.getEnd());
  12222. Diag(Loc, diag::note_equality_comparison_to_assign)
  12223. << FixItHint::CreateReplacement(Loc, "=");
  12224. }
  12225. }
  12226. ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
  12227. DiagnoseAssignmentAsCondition(E);
  12228. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  12229. DiagnoseEqualityWithExtraParens(parenE);
  12230. ExprResult result = CheckPlaceholderExpr(E);
  12231. if (result.isInvalid()) return ExprError();
  12232. E = result.get();
  12233. if (!E->isTypeDependent()) {
  12234. if (getLangOpts().CPlusPlus)
  12235. return CheckCXXBooleanCondition(E); // C++ 6.4p4
  12236. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  12237. if (ERes.isInvalid())
  12238. return ExprError();
  12239. E = ERes.get();
  12240. QualType T = E->getType();
  12241. if (!T->isScalarType()) { // C99 6.8.4.1p1
  12242. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  12243. << T << E->getSourceRange();
  12244. return ExprError();
  12245. }
  12246. CheckBoolLikeConversion(E, Loc);
  12247. }
  12248. return E;
  12249. }
  12250. ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
  12251. Expr *SubExpr) {
  12252. if (!SubExpr)
  12253. return ExprError();
  12254. return CheckBooleanCondition(SubExpr, Loc);
  12255. }
  12256. namespace {
  12257. /// A visitor for rebuilding a call to an __unknown_any expression
  12258. /// to have an appropriate type.
  12259. struct RebuildUnknownAnyFunction
  12260. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  12261. Sema &S;
  12262. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  12263. ExprResult VisitStmt(Stmt *S) {
  12264. llvm_unreachable("unexpected statement!");
  12265. }
  12266. ExprResult VisitExpr(Expr *E) {
  12267. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  12268. << E->getSourceRange();
  12269. return ExprError();
  12270. }
  12271. /// Rebuild an expression which simply semantically wraps another
  12272. /// expression which it shares the type and value kind of.
  12273. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12274. ExprResult SubResult = Visit(E->getSubExpr());
  12275. if (SubResult.isInvalid()) return ExprError();
  12276. Expr *SubExpr = SubResult.get();
  12277. E->setSubExpr(SubExpr);
  12278. E->setType(SubExpr->getType());
  12279. E->setValueKind(SubExpr->getValueKind());
  12280. assert(E->getObjectKind() == OK_Ordinary);
  12281. return E;
  12282. }
  12283. ExprResult VisitParenExpr(ParenExpr *E) {
  12284. return rebuildSugarExpr(E);
  12285. }
  12286. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12287. return rebuildSugarExpr(E);
  12288. }
  12289. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12290. ExprResult SubResult = Visit(E->getSubExpr());
  12291. if (SubResult.isInvalid()) return ExprError();
  12292. Expr *SubExpr = SubResult.get();
  12293. E->setSubExpr(SubExpr);
  12294. E->setType(S.Context.getPointerType(SubExpr->getType()));
  12295. assert(E->getValueKind() == VK_RValue);
  12296. assert(E->getObjectKind() == OK_Ordinary);
  12297. return E;
  12298. }
  12299. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  12300. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  12301. E->setType(VD->getType());
  12302. assert(E->getValueKind() == VK_RValue);
  12303. if (S.getLangOpts().CPlusPlus &&
  12304. !(isa<CXXMethodDecl>(VD) &&
  12305. cast<CXXMethodDecl>(VD)->isInstance()))
  12306. E->setValueKind(VK_LValue);
  12307. return E;
  12308. }
  12309. ExprResult VisitMemberExpr(MemberExpr *E) {
  12310. return resolveDecl(E, E->getMemberDecl());
  12311. }
  12312. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12313. return resolveDecl(E, E->getDecl());
  12314. }
  12315. };
  12316. }
  12317. /// Given a function expression of unknown-any type, try to rebuild it
  12318. /// to have a function type.
  12319. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  12320. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  12321. if (Result.isInvalid()) return ExprError();
  12322. return S.DefaultFunctionArrayConversion(Result.get());
  12323. }
  12324. namespace {
  12325. /// A visitor for rebuilding an expression of type __unknown_anytype
  12326. /// into one which resolves the type directly on the referring
  12327. /// expression. Strict preservation of the original source
  12328. /// structure is not a goal.
  12329. struct RebuildUnknownAnyExpr
  12330. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  12331. Sema &S;
  12332. /// The current destination type.
  12333. QualType DestType;
  12334. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  12335. : S(S), DestType(CastType) {}
  12336. ExprResult VisitStmt(Stmt *S) {
  12337. llvm_unreachable("unexpected statement!");
  12338. }
  12339. ExprResult VisitExpr(Expr *E) {
  12340. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12341. << E->getSourceRange();
  12342. return ExprError();
  12343. }
  12344. ExprResult VisitCallExpr(CallExpr *E);
  12345. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  12346. /// Rebuild an expression which simply semantically wraps another
  12347. /// expression which it shares the type and value kind of.
  12348. template <class T> ExprResult rebuildSugarExpr(T *E) {
  12349. ExprResult SubResult = Visit(E->getSubExpr());
  12350. if (SubResult.isInvalid()) return ExprError();
  12351. Expr *SubExpr = SubResult.get();
  12352. E->setSubExpr(SubExpr);
  12353. E->setType(SubExpr->getType());
  12354. E->setValueKind(SubExpr->getValueKind());
  12355. assert(E->getObjectKind() == OK_Ordinary);
  12356. return E;
  12357. }
  12358. ExprResult VisitParenExpr(ParenExpr *E) {
  12359. return rebuildSugarExpr(E);
  12360. }
  12361. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  12362. return rebuildSugarExpr(E);
  12363. }
  12364. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  12365. const PointerType *Ptr = DestType->getAs<PointerType>();
  12366. if (!Ptr) {
  12367. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  12368. << E->getSourceRange();
  12369. return ExprError();
  12370. }
  12371. assert(E->getValueKind() == VK_RValue);
  12372. assert(E->getObjectKind() == OK_Ordinary);
  12373. E->setType(DestType);
  12374. // Build the sub-expression as if it were an object of the pointee type.
  12375. DestType = Ptr->getPointeeType();
  12376. ExprResult SubResult = Visit(E->getSubExpr());
  12377. if (SubResult.isInvalid()) return ExprError();
  12378. E->setSubExpr(SubResult.get());
  12379. return E;
  12380. }
  12381. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  12382. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  12383. ExprResult VisitMemberExpr(MemberExpr *E) {
  12384. return resolveDecl(E, E->getMemberDecl());
  12385. }
  12386. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  12387. return resolveDecl(E, E->getDecl());
  12388. }
  12389. };
  12390. }
  12391. /// Rebuilds a call expression which yielded __unknown_anytype.
  12392. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  12393. Expr *CalleeExpr = E->getCallee();
  12394. enum FnKind {
  12395. FK_MemberFunction,
  12396. FK_FunctionPointer,
  12397. FK_BlockPointer
  12398. };
  12399. FnKind Kind;
  12400. QualType CalleeType = CalleeExpr->getType();
  12401. if (CalleeType == S.Context.BoundMemberTy) {
  12402. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  12403. Kind = FK_MemberFunction;
  12404. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  12405. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  12406. CalleeType = Ptr->getPointeeType();
  12407. Kind = FK_FunctionPointer;
  12408. } else {
  12409. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  12410. Kind = FK_BlockPointer;
  12411. }
  12412. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  12413. // Verify that this is a legal result type of a function.
  12414. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12415. unsigned diagID = diag::err_func_returning_array_function;
  12416. if (Kind == FK_BlockPointer)
  12417. diagID = diag::err_block_returning_array_function;
  12418. S.Diag(E->getExprLoc(), diagID)
  12419. << DestType->isFunctionType() << DestType;
  12420. return ExprError();
  12421. }
  12422. // Otherwise, go ahead and set DestType as the call's result.
  12423. E->setType(DestType.getNonLValueExprType(S.Context));
  12424. E->setValueKind(Expr::getValueKindForType(DestType));
  12425. assert(E->getObjectKind() == OK_Ordinary);
  12426. // Rebuild the function type, replacing the result type with DestType.
  12427. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  12428. if (Proto) {
  12429. // __unknown_anytype(...) is a special case used by the debugger when
  12430. // it has no idea what a function's signature is.
  12431. //
  12432. // We want to build this call essentially under the K&R
  12433. // unprototyped rules, but making a FunctionNoProtoType in C++
  12434. // would foul up all sorts of assumptions. However, we cannot
  12435. // simply pass all arguments as variadic arguments, nor can we
  12436. // portably just call the function under a non-variadic type; see
  12437. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  12438. // However, it turns out that in practice it is generally safe to
  12439. // call a function declared as "A foo(B,C,D);" under the prototype
  12440. // "A foo(B,C,D,...);". The only known exception is with the
  12441. // Windows ABI, where any variadic function is implicitly cdecl
  12442. // regardless of its normal CC. Therefore we change the parameter
  12443. // types to match the types of the arguments.
  12444. //
  12445. // This is a hack, but it is far superior to moving the
  12446. // corresponding target-specific code from IR-gen to Sema/AST.
  12447. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  12448. SmallVector<QualType, 8> ArgTypes;
  12449. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  12450. ArgTypes.reserve(E->getNumArgs());
  12451. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  12452. Expr *Arg = E->getArg(i);
  12453. QualType ArgType = Arg->getType();
  12454. if (E->isLValue()) {
  12455. ArgType = S.Context.getLValueReferenceType(ArgType);
  12456. } else if (E->isXValue()) {
  12457. ArgType = S.Context.getRValueReferenceType(ArgType);
  12458. }
  12459. ArgTypes.push_back(ArgType);
  12460. }
  12461. ParamTypes = ArgTypes;
  12462. }
  12463. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  12464. Proto->getExtProtoInfo(),
  12465. Proto->getParamMods()); // HLSL Change - assume args are preserved
  12466. } else {
  12467. DestType = S.Context.getFunctionNoProtoType(DestType,
  12468. FnType->getExtInfo());
  12469. }
  12470. // Rebuild the appropriate pointer-to-function type.
  12471. switch (Kind) {
  12472. case FK_MemberFunction:
  12473. // Nothing to do.
  12474. break;
  12475. case FK_FunctionPointer:
  12476. DestType = S.Context.getPointerType(DestType);
  12477. break;
  12478. case FK_BlockPointer:
  12479. DestType = S.Context.getBlockPointerType(DestType);
  12480. break;
  12481. }
  12482. // Finally, we can recurse.
  12483. ExprResult CalleeResult = Visit(CalleeExpr);
  12484. if (!CalleeResult.isUsable()) return ExprError();
  12485. E->setCallee(CalleeResult.get());
  12486. // Bind a temporary if necessary.
  12487. return S.MaybeBindToTemporary(E);
  12488. }
  12489. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  12490. // Verify that this is a legal result type of a call.
  12491. if (DestType->isArrayType() || DestType->isFunctionType()) {
  12492. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  12493. << DestType->isFunctionType() << DestType;
  12494. return ExprError();
  12495. }
  12496. // Rewrite the method result type if available.
  12497. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  12498. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  12499. Method->setReturnType(DestType);
  12500. }
  12501. // Change the type of the message.
  12502. E->setType(DestType.getNonReferenceType());
  12503. E->setValueKind(Expr::getValueKindForType(DestType));
  12504. return S.MaybeBindToTemporary(E);
  12505. }
  12506. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  12507. // The only case we should ever see here is a function-to-pointer decay.
  12508. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  12509. assert(E->getValueKind() == VK_RValue);
  12510. assert(E->getObjectKind() == OK_Ordinary);
  12511. E->setType(DestType);
  12512. // Rebuild the sub-expression as the pointee (function) type.
  12513. DestType = DestType->castAs<PointerType>()->getPointeeType();
  12514. ExprResult Result = Visit(E->getSubExpr());
  12515. if (!Result.isUsable()) return ExprError();
  12516. E->setSubExpr(Result.get());
  12517. return E;
  12518. } else if (E->getCastKind() == CK_LValueToRValue) {
  12519. assert(E->getValueKind() == VK_RValue);
  12520. assert(E->getObjectKind() == OK_Ordinary);
  12521. assert(isa<BlockPointerType>(E->getType()));
  12522. E->setType(DestType);
  12523. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  12524. DestType = S.Context.getLValueReferenceType(DestType);
  12525. ExprResult Result = Visit(E->getSubExpr());
  12526. if (!Result.isUsable()) return ExprError();
  12527. E->setSubExpr(Result.get());
  12528. return E;
  12529. } else {
  12530. llvm_unreachable("Unhandled cast type!");
  12531. }
  12532. }
  12533. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  12534. ExprValueKind ValueKind = VK_LValue;
  12535. QualType Type = DestType;
  12536. // We know how to make this work for certain kinds of decls:
  12537. // - functions
  12538. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  12539. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  12540. DestType = Ptr->getPointeeType();
  12541. ExprResult Result = resolveDecl(E, VD);
  12542. if (Result.isInvalid()) return ExprError();
  12543. return S.ImpCastExprToType(Result.get(), Type,
  12544. CK_FunctionToPointerDecay, VK_RValue);
  12545. }
  12546. if (!Type->isFunctionType()) {
  12547. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  12548. << VD << E->getSourceRange();
  12549. return ExprError();
  12550. }
  12551. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  12552. // We must match the FunctionDecl's type to the hack introduced in
  12553. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  12554. // type. See the lengthy commentary in that routine.
  12555. QualType FDT = FD->getType();
  12556. const FunctionType *FnType = FDT->castAs<FunctionType>();
  12557. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  12558. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  12559. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  12560. SourceLocation Loc = FD->getLocation();
  12561. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  12562. FD->getDeclContext(),
  12563. Loc, Loc, FD->getNameInfo().getName(),
  12564. DestType, FD->getTypeSourceInfo(),
  12565. SC_None, false/*isInlineSpecified*/,
  12566. FD->hasPrototype(),
  12567. false/*isConstexprSpecified*/);
  12568. if (FD->getQualifier())
  12569. NewFD->setQualifierInfo(FD->getQualifierLoc());
  12570. SmallVector<ParmVarDecl*, 16> Params;
  12571. for (const auto &AI : FT->param_types()) {
  12572. ParmVarDecl *Param =
  12573. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  12574. Param->setScopeInfo(0, Params.size());
  12575. Params.push_back(Param);
  12576. }
  12577. NewFD->setParams(Params);
  12578. DRE->setDecl(NewFD);
  12579. VD = DRE->getDecl();
  12580. }
  12581. }
  12582. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  12583. if (MD->isInstance()) {
  12584. ValueKind = VK_RValue;
  12585. Type = S.Context.BoundMemberTy;
  12586. }
  12587. // Function references aren't l-values in C.
  12588. if (!S.getLangOpts().CPlusPlus)
  12589. ValueKind = VK_RValue;
  12590. // - variables
  12591. } else if (isa<VarDecl>(VD)) {
  12592. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  12593. Type = RefTy->getPointeeType();
  12594. } else if (Type->isFunctionType()) {
  12595. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  12596. << VD << E->getSourceRange();
  12597. return ExprError();
  12598. }
  12599. // - nothing else
  12600. } else {
  12601. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  12602. << VD << E->getSourceRange();
  12603. return ExprError();
  12604. }
  12605. // Modifying the declaration like this is friendly to IR-gen but
  12606. // also really dangerous.
  12607. VD->setType(DestType);
  12608. E->setType(Type);
  12609. E->setValueKind(ValueKind);
  12610. return E;
  12611. }
  12612. /// Check a cast of an unknown-any type. We intentionally only
  12613. /// trigger this for C-style casts.
  12614. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  12615. Expr *CastExpr, CastKind &CastKind,
  12616. ExprValueKind &VK, CXXCastPath &Path) {
  12617. // Rewrite the casted expression from scratch.
  12618. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  12619. if (!result.isUsable()) return ExprError();
  12620. CastExpr = result.get();
  12621. VK = CastExpr->getValueKind();
  12622. CastKind = CK_NoOp;
  12623. return CastExpr;
  12624. }
  12625. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  12626. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  12627. }
  12628. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  12629. Expr *arg, QualType &paramType) {
  12630. // If the syntactic form of the argument is not an explicit cast of
  12631. // any sort, just do default argument promotion.
  12632. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  12633. if (!castArg) {
  12634. ExprResult result = DefaultArgumentPromotion(arg);
  12635. if (result.isInvalid()) return ExprError();
  12636. paramType = result.get()->getType();
  12637. return result;
  12638. }
  12639. // Otherwise, use the type that was written in the explicit cast.
  12640. assert(!arg->hasPlaceholderType());
  12641. paramType = castArg->getTypeAsWritten();
  12642. // Copy-initialize a parameter of that type.
  12643. InitializedEntity entity =
  12644. InitializedEntity::InitializeParameter(Context, paramType,
  12645. /*consumed*/ false);
  12646. return PerformCopyInitialization(entity, callLoc, arg);
  12647. }
  12648. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  12649. Expr *orig = E;
  12650. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  12651. while (true) {
  12652. E = E->IgnoreParenImpCasts();
  12653. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  12654. E = call->getCallee();
  12655. diagID = diag::err_uncasted_call_of_unknown_any;
  12656. } else {
  12657. break;
  12658. }
  12659. }
  12660. SourceLocation loc;
  12661. NamedDecl *d;
  12662. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  12663. loc = ref->getLocation();
  12664. d = ref->getDecl();
  12665. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  12666. loc = mem->getMemberLoc();
  12667. d = mem->getMemberDecl();
  12668. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  12669. diagID = diag::err_uncasted_call_of_unknown_any;
  12670. loc = msg->getSelectorStartLoc();
  12671. d = msg->getMethodDecl();
  12672. if (!d) {
  12673. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  12674. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  12675. << orig->getSourceRange();
  12676. return ExprError();
  12677. }
  12678. } else {
  12679. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  12680. << E->getSourceRange();
  12681. return ExprError();
  12682. }
  12683. S.Diag(loc, diagID) << d << orig->getSourceRange();
  12684. // Never recoverable.
  12685. return ExprError();
  12686. }
  12687. /// Check for operands with placeholder types and complain if found.
  12688. /// Returns true if there was an error and no recovery was possible.
  12689. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  12690. if (!getLangOpts().CPlusPlus) {
  12691. // C cannot handle TypoExpr nodes on either side of a binop because it
  12692. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12693. // been dealt with before checking the operands.
  12694. ExprResult Result = CorrectDelayedTyposInExpr(E);
  12695. if (!Result.isUsable()) return ExprError();
  12696. E = Result.get();
  12697. }
  12698. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  12699. if (!placeholderType) return E;
  12700. switch (placeholderType->getKind()) {
  12701. // Overloaded expressions.
  12702. case BuiltinType::Overload: {
  12703. // Try to resolve a single function template specialization.
  12704. // This is obligatory.
  12705. ExprResult result = E;
  12706. if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
  12707. return result;
  12708. // If that failed, try to recover with a call.
  12709. } else {
  12710. tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
  12711. /*complain*/ true);
  12712. return result;
  12713. }
  12714. }
  12715. // Bound member functions.
  12716. case BuiltinType::BoundMember: {
  12717. ExprResult result = E;
  12718. const Expr *BME = E->IgnoreParens();
  12719. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  12720. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  12721. if (isa<CXXPseudoDestructorExpr>(BME)) {
  12722. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  12723. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  12724. if (ME->getMemberNameInfo().getName().getNameKind() ==
  12725. DeclarationName::CXXDestructorName)
  12726. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  12727. }
  12728. tryToRecoverWithCall(result, PD,
  12729. /*complain*/ true);
  12730. return result;
  12731. }
  12732. // ARC unbridged casts.
  12733. case BuiltinType::ARCUnbridgedCast: {
  12734. Expr *realCast = stripARCUnbridgedCast(E);
  12735. diagnoseARCUnbridgedCast(realCast);
  12736. return realCast;
  12737. }
  12738. // Expressions of unknown type.
  12739. case BuiltinType::UnknownAny:
  12740. return diagnoseUnknownAnyExpr(*this, E);
  12741. // Pseudo-objects.
  12742. case BuiltinType::PseudoObject:
  12743. return checkPseudoObjectRValue(E);
  12744. case BuiltinType::BuiltinFn: {
  12745. // Accept __noop without parens by implicitly converting it to a call expr.
  12746. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  12747. if (DRE) {
  12748. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  12749. if (FD->getBuiltinID() == Builtin::BI__noop) {
  12750. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  12751. CK_BuiltinFnToFnPtr).get();
  12752. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  12753. VK_RValue, SourceLocation());
  12754. }
  12755. }
  12756. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  12757. return ExprError();
  12758. }
  12759. // Everything else should be impossible.
  12760. #define BUILTIN_TYPE(Id, SingletonId) \
  12761. case BuiltinType::Id:
  12762. #define PLACEHOLDER_TYPE(Id, SingletonId)
  12763. #include "clang/AST/BuiltinTypes.def"
  12764. break;
  12765. }
  12766. llvm_unreachable("invalid placeholder type!");
  12767. }
  12768. bool Sema::CheckCaseExpression(Expr *E) {
  12769. if (E->isTypeDependent())
  12770. return true;
  12771. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  12772. return E->getType()->isIntegralOrEnumerationType();
  12773. return false;
  12774. }
  12775. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  12776. ExprResult
  12777. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  12778. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  12779. "Unknown Objective-C Boolean value!");
  12780. QualType BoolT = Context.ObjCBuiltinBoolTy;
  12781. if (!Context.getBOOLDecl()) {
  12782. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  12783. Sema::LookupOrdinaryName);
  12784. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  12785. NamedDecl *ND = Result.getFoundDecl();
  12786. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  12787. Context.setBOOLDecl(TD);
  12788. }
  12789. }
  12790. if (Context.getBOOLDecl())
  12791. BoolT = Context.getBOOLType();
  12792. return new (Context)
  12793. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  12794. }