SemaHLSL.cpp 368 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795
  1. //===--- SemaHLSL.cpp - HLSL support for AST nodes and operations ---===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // SemaHLSL.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This file implements the semantic support for HLSL. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Attr.h"
  14. #include "clang/AST/DeclCXX.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/ExternalASTSource.h"
  19. #include "clang/AST/TypeLoc.h"
  20. #include "clang/AST/HlslTypes.h"
  21. #include "clang/Sema/Overload.h"
  22. #include "clang/Sema/SemaDiagnostic.h"
  23. #include "clang/Sema/Initialization.h"
  24. #include "clang/Sema/ExternalSemaSource.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/Template.h"
  27. #include "clang/Sema/TemplateDeduction.h"
  28. #include "clang/Sema/SemaHLSL.h"
  29. #include <map>
  30. #include "dxc/Support/Global.h"
  31. #include "dxc/Support/WinIncludes.h"
  32. #include "dxc/dxcapi.internal.h"
  33. #include "dxc/HlslIntrinsicOp.h"
  34. #include "gen_intrin_main_tables_15.h"
  35. #include "dxc/HLSL/HLOperations.h"
  36. #include <array>
  37. enum ArBasicKind {
  38. AR_BASIC_BOOL,
  39. AR_BASIC_LITERAL_FLOAT,
  40. AR_BASIC_FLOAT16,
  41. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  42. AR_BASIC_FLOAT32,
  43. AR_BASIC_FLOAT64,
  44. AR_BASIC_LITERAL_INT,
  45. AR_BASIC_INT8,
  46. AR_BASIC_UINT8,
  47. AR_BASIC_INT16,
  48. AR_BASIC_UINT16,
  49. AR_BASIC_INT32,
  50. AR_BASIC_UINT32,
  51. AR_BASIC_INT64,
  52. AR_BASIC_UINT64,
  53. AR_BASIC_MIN10FLOAT,
  54. AR_BASIC_MIN16FLOAT,
  55. AR_BASIC_MIN12INT,
  56. AR_BASIC_MIN16INT,
  57. AR_BASIC_MIN16UINT,
  58. AR_BASIC_COUNT,
  59. //
  60. // Pseudo-entries for intrinsic tables and such.
  61. //
  62. AR_BASIC_NONE,
  63. AR_BASIC_UNKNOWN,
  64. AR_BASIC_NOCAST,
  65. //
  66. // The following pseudo-entries represent higher-level
  67. // object types that are treated as units.
  68. //
  69. AR_BASIC_POINTER,
  70. AR_OBJECT_NULL,
  71. AR_OBJECT_STRING,
  72. // AR_OBJECT_TEXTURE,
  73. AR_OBJECT_TEXTURE1D,
  74. AR_OBJECT_TEXTURE1D_ARRAY,
  75. AR_OBJECT_TEXTURE2D,
  76. AR_OBJECT_TEXTURE2D_ARRAY,
  77. AR_OBJECT_TEXTURE3D,
  78. AR_OBJECT_TEXTURECUBE,
  79. AR_OBJECT_TEXTURECUBE_ARRAY,
  80. AR_OBJECT_TEXTURE2DMS,
  81. AR_OBJECT_TEXTURE2DMS_ARRAY,
  82. AR_OBJECT_SAMPLER,
  83. AR_OBJECT_SAMPLER1D,
  84. AR_OBJECT_SAMPLER2D,
  85. AR_OBJECT_SAMPLER3D,
  86. AR_OBJECT_SAMPLERCUBE,
  87. AR_OBJECT_SAMPLERCOMPARISON,
  88. AR_OBJECT_BUFFER,
  89. //
  90. // View objects are only used as variable/types within the Effects
  91. // framework, for example in calls to OMSetRenderTargets.
  92. //
  93. AR_OBJECT_RENDERTARGETVIEW,
  94. AR_OBJECT_DEPTHSTENCILVIEW,
  95. //
  96. // Shader objects are only used as variable/types within the Effects
  97. // framework, for example as a result of CompileShader().
  98. //
  99. AR_OBJECT_COMPUTESHADER,
  100. AR_OBJECT_DOMAINSHADER,
  101. AR_OBJECT_GEOMETRYSHADER,
  102. AR_OBJECT_HULLSHADER,
  103. AR_OBJECT_PIXELSHADER,
  104. AR_OBJECT_VERTEXSHADER,
  105. AR_OBJECT_PIXELFRAGMENT,
  106. AR_OBJECT_VERTEXFRAGMENT,
  107. AR_OBJECT_STATEBLOCK,
  108. AR_OBJECT_RASTERIZER,
  109. AR_OBJECT_DEPTHSTENCIL,
  110. AR_OBJECT_BLEND,
  111. AR_OBJECT_POINTSTREAM,
  112. AR_OBJECT_LINESTREAM,
  113. AR_OBJECT_TRIANGLESTREAM,
  114. AR_OBJECT_INPUTPATCH,
  115. AR_OBJECT_OUTPUTPATCH,
  116. AR_OBJECT_RWTEXTURE1D,
  117. AR_OBJECT_RWTEXTURE1D_ARRAY,
  118. AR_OBJECT_RWTEXTURE2D,
  119. AR_OBJECT_RWTEXTURE2D_ARRAY,
  120. AR_OBJECT_RWTEXTURE3D,
  121. AR_OBJECT_RWBUFFER,
  122. AR_OBJECT_BYTEADDRESS_BUFFER,
  123. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  124. AR_OBJECT_STRUCTURED_BUFFER,
  125. AR_OBJECT_RWSTRUCTURED_BUFFER,
  126. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  127. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  128. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  129. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  130. AR_OBJECT_CONSTANT_BUFFER,
  131. AR_OBJECT_TEXTURE_BUFFER,
  132. AR_OBJECT_ROVBUFFER,
  133. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  134. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  135. AR_OBJECT_ROVTEXTURE1D,
  136. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  137. AR_OBJECT_ROVTEXTURE2D,
  138. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  139. AR_OBJECT_ROVTEXTURE3D,
  140. AR_OBJECT_INNER, // Used for internal type object
  141. AR_OBJECT_LEGACY_EFFECT,
  142. AR_OBJECT_WAVE,
  143. AR_BASIC_MAXIMUM_COUNT
  144. };
  145. #define AR_BASIC_TEXTURE_MS_CASES \
  146. case AR_OBJECT_TEXTURE2DMS: \
  147. case AR_OBJECT_TEXTURE2DMS_ARRAY
  148. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  149. case AR_OBJECT_TEXTURE1D: \
  150. case AR_OBJECT_TEXTURE1D_ARRAY: \
  151. case AR_OBJECT_TEXTURE2D: \
  152. case AR_OBJECT_TEXTURE2D_ARRAY: \
  153. case AR_OBJECT_TEXTURE3D: \
  154. case AR_OBJECT_TEXTURECUBE: \
  155. case AR_OBJECT_TEXTURECUBE_ARRAY
  156. #define AR_BASIC_TEXTURE_CASES \
  157. AR_BASIC_TEXTURE_MS_CASES: \
  158. AR_BASIC_NON_TEXTURE_MS_CASES
  159. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  160. case AR_OBJECT_SAMPLER: \
  161. case AR_OBJECT_SAMPLER1D: \
  162. case AR_OBJECT_SAMPLER2D: \
  163. case AR_OBJECT_SAMPLER3D: \
  164. case AR_OBJECT_SAMPLERCUBE
  165. #define AR_BASIC_ROBJECT_CASES \
  166. case AR_OBJECT_BLEND: \
  167. case AR_OBJECT_RASTERIZER: \
  168. case AR_OBJECT_DEPTHSTENCIL: \
  169. case AR_OBJECT_STATEBLOCK
  170. //
  171. // Properties of entries in the ArBasicKind enumeration.
  172. // These properties are intended to allow easy identification
  173. // of classes of basic kinds. More specific checks on the
  174. // actual kind values could then be done.
  175. //
  176. // The first four bits are used as a subtype indicator,
  177. // such as bit count for primitive kinds or specific
  178. // types for non-primitive-data kinds.
  179. #define BPROP_SUBTYPE_MASK 0x0000000f
  180. // Bit counts must be ordered from smaller to larger.
  181. #define BPROP_BITS0 0x00000000
  182. #define BPROP_BITS8 0x00000001
  183. #define BPROP_BITS10 0x00000002
  184. #define BPROP_BITS12 0x00000003
  185. #define BPROP_BITS16 0x00000004
  186. #define BPROP_BITS32 0x00000005
  187. #define BPROP_BITS64 0x00000006
  188. #define BPROP_BITS_NON_PRIM 0x00000007
  189. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  190. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  191. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  192. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  193. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  194. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  195. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  196. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  197. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  198. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  199. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  200. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  201. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  202. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  203. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  204. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  205. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  206. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  207. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  208. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  209. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  210. #define GET_BPROP_PRIM_KIND(_Props) \
  211. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  212. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  213. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  214. #define IS_BPROP_PRIMITIVE(_Props) \
  215. (((_Props) & BPROP_PRIMITIVE) != 0)
  216. #define IS_BPROP_BOOL(_Props) \
  217. (((_Props) & BPROP_BOOLEAN) != 0)
  218. #define IS_BPROP_FLOAT(_Props) \
  219. (((_Props) & BPROP_FLOATING) != 0)
  220. #define IS_BPROP_SINT(_Props) \
  221. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  222. BPROP_INTEGER)
  223. #define IS_BPROP_UINT(_Props) \
  224. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  225. (BPROP_INTEGER | BPROP_UNSIGNED))
  226. #define IS_BPROP_AINT(_Props) \
  227. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  228. #define IS_BPROP_STREAM(_Props) \
  229. (((_Props) & BPROP_STREAM) != 0)
  230. #define IS_BPROP_SAMPLER(_Props) \
  231. (((_Props) & BPROP_SAMPLER) != 0)
  232. #define IS_BPROP_TEXTURE(_Props) \
  233. (((_Props) & BPROP_TEXTURE) != 0)
  234. #define IS_BPROP_OBJECT(_Props) \
  235. (((_Props) & BPROP_OBJECT) != 0)
  236. #define IS_BPROP_MIN_PRECISION(_Props) \
  237. (((_Props) & BPROP_MIN_PRECISION) != 0)
  238. #define IS_BPROP_UNSIGNABLE(_Props) \
  239. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  240. const UINT g_uBasicKindProps[] =
  241. {
  242. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  243. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  244. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  245. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  246. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  247. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  248. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  249. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  250. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  251. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  252. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  253. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  254. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  255. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  256. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  257. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  258. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  259. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  260. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  261. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  262. BPROP_OTHER, // AR_BASIC_COUNT
  263. //
  264. // Pseudo-entries for intrinsic tables and such.
  265. //
  266. 0, // AR_BASIC_NONE
  267. BPROP_OTHER, // AR_BASIC_UNKNOWN
  268. BPROP_OTHER, // AR_BASIC_NOCAST
  269. //
  270. // The following pseudo-entries represent higher-level
  271. // object types that are treated as units.
  272. //
  273. BPROP_POINTER, // AR_BASIC_POINTER
  274. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  275. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  276. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  277. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  278. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  279. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  280. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  281. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  282. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  283. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  284. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  285. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  286. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  287. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  288. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  289. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  290. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  291. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  292. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  293. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  294. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  295. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  296. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  297. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  298. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  299. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  300. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  301. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  302. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  303. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  304. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  305. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  306. BPROP_OBJECT, // AR_OBJECT_BLEND
  307. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  308. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  309. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  310. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  311. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  312. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  313. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  314. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  315. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  316. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  317. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  318. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  319. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  320. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  321. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  322. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  323. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  324. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  325. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  326. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  327. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  328. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  329. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  330. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  331. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  332. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  333. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  334. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  335. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  336. BPROP_OBJECT, // AR_OBJECT_INNER
  337. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  338. BPROP_OBJECT, // AR_OBJECT_WAVE
  339. // AR_BASIC_MAXIMUM_COUNT
  340. };
  341. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  342. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  343. #define GET_BASIC_BITS(_Kind) \
  344. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  345. #define GET_BASIC_PRIM_KIND(_Kind) \
  346. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  347. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  348. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  349. #define IS_BASIC_PRIMITIVE(_Kind) \
  350. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  351. #define IS_BASIC_BOOL(_Kind) \
  352. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  353. #define IS_BASIC_FLOAT(_Kind) \
  354. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  355. #define IS_BASIC_SINT(_Kind) \
  356. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  357. #define IS_BASIC_UINT(_Kind) \
  358. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  359. #define IS_BASIC_AINT(_Kind) \
  360. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  361. #define IS_BASIC_STREAM(_Kind) \
  362. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  363. #define IS_BASIC_SAMPLER(_Kind) \
  364. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  365. #define IS_BASIC_TEXTURE(_Kind) \
  366. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  367. #define IS_BASIC_OBJECT(_Kind) \
  368. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  369. #define IS_BASIC_MIN_PRECISION(_Kind) \
  370. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  371. #define IS_BASIC_UNSIGNABLE(_Kind) \
  372. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  373. #define BITWISE_ENUM_OPS(_Type) \
  374. inline _Type operator|(_Type F1, _Type F2) \
  375. { \
  376. return (_Type)((UINT)F1 | (UINT)F2); \
  377. } \
  378. inline _Type operator&(_Type F1, _Type F2) \
  379. { \
  380. return (_Type)((UINT)F1 & (UINT)F2); \
  381. } \
  382. inline _Type& operator|=(_Type& F1, _Type F2) \
  383. { \
  384. F1 = F1 | F2; \
  385. return F1; \
  386. } \
  387. inline _Type& operator&=(_Type& F1, _Type F2) \
  388. { \
  389. F1 = F1 & F2; \
  390. return F1; \
  391. } \
  392. inline _Type& operator&=(_Type& F1, UINT F2) \
  393. { \
  394. F1 = (_Type)((UINT)F1 & F2); \
  395. return F1; \
  396. }
  397. enum ArTypeObjectKind {
  398. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  399. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  400. AR_TOBJ_BASIC, // Represents a primitive type.
  401. AR_TOBJ_COMPOUND, // Represents a struct or class.
  402. AR_TOBJ_INTERFACE, // Represents an interface.
  403. AR_TOBJ_POINTER, // Represents a pointer to another type.
  404. AR_TOBJ_OBJECT, // Represents a built-in object.
  405. AR_TOBJ_ARRAY, // Represents an array of other types.
  406. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  407. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  408. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  409. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  410. // indexer object used to implement .mips[1].
  411. };
  412. enum TYPE_CONVERSION_FLAGS
  413. {
  414. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  415. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  416. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  417. };
  418. enum TYPE_CONVERSION_REMARKS
  419. {
  420. TYPE_CONVERSION_NONE = 0x00000000,
  421. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  422. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  423. TYPE_CONVERSION_TO_VOID = 0x00000004,
  424. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  425. };
  426. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  427. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  428. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  429. #define AR_TPROP_VOID 0x0000000000000001
  430. #define AR_TPROP_CONST 0x0000000000000002
  431. #define AR_TPROP_IMP_CONST 0x0000000000000004
  432. #define AR_TPROP_OBJECT 0x0000000000000008
  433. #define AR_TPROP_SCALAR 0x0000000000000010
  434. #define AR_TPROP_UNSIGNED 0x0000000000000020
  435. #define AR_TPROP_NUMERIC 0x0000000000000040
  436. #define AR_TPROP_INTEGRAL 0x0000000000000080
  437. #define AR_TPROP_FLOATING 0x0000000000000100
  438. #define AR_TPROP_LITERAL 0x0000000000000200
  439. #define AR_TPROP_POINTER 0x0000000000000400
  440. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  441. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  442. #define AR_TPROP_INH_IFACE 0x0000000000002000
  443. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  444. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  445. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  446. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  447. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  448. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  449. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  450. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  451. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  452. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  453. #define AR_TPROP_INDEXABLE 0x0000000001000000
  454. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  455. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  456. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  457. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  458. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  459. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  460. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  461. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  462. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  463. #define AR_TPROP_ALL 0xffffffffffffffff
  464. #define AR_TPROP_HAS_OBJECTS \
  465. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  466. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  467. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  468. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  469. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  470. #define AR_TPROP_HAS_BASIC_RESOURCES \
  471. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  472. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  473. AR_TPROP_HAS_UAVS)
  474. #define AR_TPROP_UNION_BITS \
  475. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  476. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  477. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  478. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  479. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  480. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  481. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  482. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  483. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  484. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  485. #define AR_TINFO_PACK_SCALAR 0x00000010
  486. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  487. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  488. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  489. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  490. #define AR_TINFO_PACK_CBUFFER 0
  491. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  492. #define AR_TINFO_SIMPLE_OBJECTS \
  493. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  494. struct ArTypeInfo {
  495. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  496. ArBasicKind EltKind; // The primitive type of elements in this type.
  497. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  498. UINT uRows;
  499. UINT uCols;
  500. UINT uTotalElts;
  501. };
  502. using namespace clang;
  503. using namespace clang::sema;
  504. using namespace hlsl;
  505. static const int FirstTemplateDepth = 0;
  506. static const int FirstParamPosition = 0;
  507. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  508. static const bool InheritedFalse = false; // template parameter default value is not inherited.
  509. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  510. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  511. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  512. static const bool DelayTypeCreationFalse = false; // immediately create a type when the declaration is created
  513. static const unsigned int NoQuals = 0; // no qualifiers in effect
  514. static const SourceLocation NoLoc; // no source location attribution available
  515. static const SourceRange NoRange; // no source range attribution available
  516. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  517. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  518. static const bool IsConstexprFalse = false; // function is not constexpr
  519. static const bool ListInitializationFalse = false;// not performing a list initialization
  520. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  521. static const bool SuppressWarningsTrue = true; // suppress warning diagnostics
  522. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  523. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  524. static const int OneRow = 1; // a single row for a type
  525. static const bool MipsFalse = false; // a type does not support the .mips member
  526. static const bool MipsTrue = true; // a type supports the .mips member
  527. static const bool SampleFalse = false; // a type does not support the .sample member
  528. static const bool SampleTrue = true; // a type supports the .sample member
  529. static const size_t MaxVectorSize = 4; // maximum size for a vector
  530. static
  531. QualType GetOrCreateTemplateSpecialization(
  532. ASTContext& context,
  533. Sema& sema,
  534. _In_ ClassTemplateDecl* templateDecl,
  535. ArrayRef<TemplateArgument> templateArgs
  536. )
  537. {
  538. DXASSERT_NOMSG(templateDecl);
  539. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  540. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  541. for (const TemplateArgument& Arg : templateArgs) {
  542. if (Arg.getKind() == TemplateArgument::Type) {
  543. // the class template need to use CanonicalType
  544. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  545. }else
  546. templateArgsForDecl.emplace_back(Arg);
  547. }
  548. // First, try looking up existing specialization
  549. void* InsertPos = nullptr;
  550. ClassTemplateSpecializationDecl* specializationDecl =
  551. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  552. if (specializationDecl) {
  553. // Instantiate the class template if not yet.
  554. if (specializationDecl->getInstantiatedFrom().isNull()) {
  555. // InstantiateClassTemplateSpecialization returns true if it finds an
  556. // error.
  557. DXVERIFY_NOMSG(false ==
  558. sema.InstantiateClassTemplateSpecialization(
  559. NoLoc, specializationDecl,
  560. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  561. true));
  562. }
  563. return context.getTemplateSpecializationType(
  564. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  565. context.getTypeDeclType(specializationDecl));
  566. }
  567. specializationDecl = ClassTemplateSpecializationDecl::Create(
  568. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  569. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  570. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  571. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  572. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  573. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  574. specializationDecl->setImplicit(true);
  575. QualType canonType = context.getTypeDeclType(specializationDecl);
  576. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  577. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  578. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  579. for (unsigned i = 0; i < templateArgs.size(); i++) {
  580. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  581. }
  582. return context.getTemplateSpecializationType(
  583. TemplateName(templateDecl), templateArgumentList, canonType);
  584. }
  585. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  586. static
  587. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  588. _In_ ClassTemplateDecl* matrixTemplateDecl,
  589. QualType elementType, uint64_t rowCount, uint64_t colCount)
  590. {
  591. DXASSERT_NOMSG(sema);
  592. TemplateArgument templateArgs[3] = {
  593. TemplateArgument(elementType),
  594. TemplateArgument(
  595. context,
  596. llvm::APSInt(
  597. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  598. context.IntTy),
  599. TemplateArgument(
  600. context,
  601. llvm::APSInt(
  602. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  603. context.IntTy)};
  604. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  605. #ifdef DBG
  606. // Verify that we can read the field member from the template record.
  607. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  608. "type of non-dependent specialization is not a RecordType");
  609. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  610. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  611. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  612. #endif
  613. return matrixSpecializationType;
  614. }
  615. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  616. static
  617. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  618. _In_ ClassTemplateDecl* vectorTemplateDecl,
  619. QualType elementType, uint64_t colCount)
  620. {
  621. DXASSERT_NOMSG(sema);
  622. DXASSERT_NOMSG(vectorTemplateDecl);
  623. TemplateArgument templateArgs[2] = {
  624. TemplateArgument(elementType),
  625. TemplateArgument(
  626. context,
  627. llvm::APSInt(
  628. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  629. context.IntTy)};
  630. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  631. #ifdef DBG
  632. // Verify that we can read the field member from the template record.
  633. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  634. "type of non-dependent specialization is not a RecordType");
  635. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  636. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  637. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  638. #endif
  639. return vectorSpecializationType;
  640. }
  641. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  642. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  643. static const unsigned kAtomicDstOperandIdx = 1;
  644. static const ArTypeObjectKind g_ScalarTT[] =
  645. {
  646. AR_TOBJ_SCALAR,
  647. AR_TOBJ_UNKNOWN
  648. };
  649. static const ArTypeObjectKind g_VectorTT[] =
  650. {
  651. AR_TOBJ_VECTOR,
  652. AR_TOBJ_UNKNOWN
  653. };
  654. static const ArTypeObjectKind g_MatrixTT[] =
  655. {
  656. AR_TOBJ_MATRIX,
  657. AR_TOBJ_UNKNOWN
  658. };
  659. static const ArTypeObjectKind g_AnyTT[] =
  660. {
  661. AR_TOBJ_SCALAR,
  662. AR_TOBJ_VECTOR,
  663. AR_TOBJ_MATRIX,
  664. AR_TOBJ_UNKNOWN
  665. };
  666. static const ArTypeObjectKind g_ObjectTT[] =
  667. {
  668. AR_TOBJ_OBJECT,
  669. AR_TOBJ_UNKNOWN
  670. };
  671. static const ArTypeObjectKind g_NullTT[] =
  672. {
  673. AR_TOBJ_VOID,
  674. AR_TOBJ_UNKNOWN
  675. };
  676. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  677. {
  678. g_NullTT,
  679. g_ScalarTT,
  680. g_VectorTT,
  681. g_MatrixTT,
  682. g_AnyTT,
  683. g_ObjectTT,
  684. };
  685. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  686. //
  687. // The first one is used to name the representative group, so make
  688. // sure its name will make sense in error messages.
  689. //
  690. static const ArBasicKind g_BoolCT[] =
  691. {
  692. AR_BASIC_BOOL,
  693. AR_BASIC_UNKNOWN
  694. };
  695. static const ArBasicKind g_IntCT[] =
  696. {
  697. AR_BASIC_INT32,
  698. AR_BASIC_LITERAL_INT,
  699. AR_BASIC_UNKNOWN
  700. };
  701. static const ArBasicKind g_UIntCT[] =
  702. {
  703. AR_BASIC_UINT32,
  704. AR_BASIC_LITERAL_INT,
  705. AR_BASIC_UNKNOWN
  706. };
  707. static const ArBasicKind g_AnyIntCT[] =
  708. {
  709. AR_BASIC_INT32,
  710. AR_BASIC_UINT32,
  711. AR_BASIC_INT64,
  712. AR_BASIC_UINT64,
  713. AR_BASIC_LITERAL_INT,
  714. AR_BASIC_UNKNOWN
  715. };
  716. static const ArBasicKind g_AnyInt32CT[] =
  717. {
  718. AR_BASIC_INT32,
  719. AR_BASIC_UINT32,
  720. AR_BASIC_LITERAL_INT,
  721. AR_BASIC_UNKNOWN
  722. };
  723. static const ArBasicKind g_UIntOnlyCT[] =
  724. {
  725. AR_BASIC_UINT32,
  726. AR_BASIC_UINT64,
  727. AR_BASIC_LITERAL_INT,
  728. AR_BASIC_NOCAST,
  729. AR_BASIC_UNKNOWN
  730. };
  731. static const ArBasicKind g_FloatCT[] =
  732. {
  733. AR_BASIC_FLOAT32,
  734. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  735. AR_BASIC_LITERAL_FLOAT,
  736. AR_BASIC_UNKNOWN
  737. };
  738. static const ArBasicKind g_AnyFloatCT[] =
  739. {
  740. AR_BASIC_FLOAT32,
  741. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  742. // TODO - AR_BASIC_FLOAT16,
  743. AR_BASIC_FLOAT64,
  744. AR_BASIC_LITERAL_FLOAT,
  745. AR_BASIC_MIN10FLOAT,
  746. AR_BASIC_MIN16FLOAT,
  747. AR_BASIC_UNKNOWN
  748. };
  749. static const ArBasicKind g_FloatLikeCT[] =
  750. {
  751. AR_BASIC_FLOAT32,
  752. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  753. AR_BASIC_LITERAL_FLOAT,
  754. AR_BASIC_MIN10FLOAT,
  755. AR_BASIC_MIN16FLOAT,
  756. AR_BASIC_UNKNOWN
  757. };
  758. static const ArBasicKind g_FloatDoubleCT[] =
  759. {
  760. AR_BASIC_FLOAT32,
  761. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  762. AR_BASIC_FLOAT64,
  763. AR_BASIC_LITERAL_FLOAT,
  764. AR_BASIC_UNKNOWN
  765. };
  766. static const ArBasicKind g_DoubleCT[] =
  767. {
  768. AR_BASIC_FLOAT64,
  769. AR_BASIC_LITERAL_FLOAT,
  770. AR_BASIC_UNKNOWN
  771. };
  772. static const ArBasicKind g_DoubleOnlyCT[] =
  773. {
  774. AR_BASIC_FLOAT64,
  775. AR_BASIC_NOCAST,
  776. AR_BASIC_UNKNOWN
  777. };
  778. static const ArBasicKind g_NumericCT[] =
  779. {
  780. AR_BASIC_LITERAL_FLOAT,
  781. AR_BASIC_FLOAT32,
  782. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  783. // TODO - AR_BASIC_FLOAT16,
  784. AR_BASIC_FLOAT64,
  785. AR_BASIC_MIN10FLOAT,
  786. AR_BASIC_MIN16FLOAT,
  787. AR_BASIC_LITERAL_INT,
  788. AR_BASIC_INT32,
  789. AR_BASIC_UINT32,
  790. AR_BASIC_MIN12INT,
  791. AR_BASIC_MIN16INT,
  792. AR_BASIC_MIN16UINT,
  793. AR_BASIC_INT64,
  794. AR_BASIC_UINT64,
  795. AR_BASIC_UNKNOWN
  796. };
  797. static const ArBasicKind g_Numeric32CT[] =
  798. {
  799. AR_BASIC_LITERAL_FLOAT,
  800. AR_BASIC_FLOAT32,
  801. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  802. AR_BASIC_LITERAL_INT,
  803. AR_BASIC_INT32,
  804. AR_BASIC_UINT32,
  805. AR_BASIC_UNKNOWN
  806. };
  807. static const ArBasicKind g_Numeric32OnlyCT[] =
  808. {
  809. AR_BASIC_LITERAL_FLOAT,
  810. AR_BASIC_FLOAT32,
  811. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  812. AR_BASIC_LITERAL_INT,
  813. AR_BASIC_INT32,
  814. AR_BASIC_UINT32,
  815. AR_BASIC_NOCAST,
  816. AR_BASIC_UNKNOWN
  817. };
  818. static const ArBasicKind g_AnyCT[] =
  819. {
  820. AR_BASIC_LITERAL_FLOAT,
  821. AR_BASIC_FLOAT32,
  822. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  823. // TODO - AR_BASIC_FLOAT16,
  824. AR_BASIC_FLOAT64,
  825. AR_BASIC_MIN10FLOAT,
  826. AR_BASIC_MIN16FLOAT,
  827. AR_BASIC_LITERAL_INT,
  828. AR_BASIC_INT32,
  829. AR_BASIC_UINT32,
  830. AR_BASIC_MIN12INT,
  831. AR_BASIC_MIN16INT,
  832. AR_BASIC_MIN16UINT,
  833. AR_BASIC_BOOL,
  834. AR_BASIC_INT64,
  835. AR_BASIC_UINT64,
  836. AR_BASIC_UNKNOWN
  837. };
  838. static const ArBasicKind g_Sampler1DCT[] =
  839. {
  840. AR_OBJECT_SAMPLER1D,
  841. AR_BASIC_UNKNOWN
  842. };
  843. static const ArBasicKind g_Sampler2DCT[] =
  844. {
  845. AR_OBJECT_SAMPLER2D,
  846. AR_BASIC_UNKNOWN
  847. };
  848. static const ArBasicKind g_Sampler3DCT[] =
  849. {
  850. AR_OBJECT_SAMPLER3D,
  851. AR_BASIC_UNKNOWN
  852. };
  853. static const ArBasicKind g_SamplerCUBECT[] =
  854. {
  855. AR_OBJECT_SAMPLERCUBE,
  856. AR_BASIC_UNKNOWN
  857. };
  858. static const ArBasicKind g_SamplerCmpCT[] =
  859. {
  860. AR_OBJECT_SAMPLERCOMPARISON,
  861. AR_BASIC_UNKNOWN
  862. };
  863. static const ArBasicKind g_SamplerCT[] =
  864. {
  865. AR_OBJECT_SAMPLER,
  866. AR_BASIC_UNKNOWN
  867. };
  868. static const ArBasicKind g_StringCT[] =
  869. {
  870. AR_OBJECT_STRING,
  871. AR_BASIC_UNKNOWN
  872. };
  873. static const ArBasicKind g_NullCT[] =
  874. {
  875. AR_OBJECT_NULL,
  876. AR_BASIC_UNKNOWN
  877. };
  878. static const ArBasicKind g_WaveCT[] =
  879. {
  880. AR_OBJECT_WAVE,
  881. AR_BASIC_UNKNOWN
  882. };
  883. static const ArBasicKind g_UInt64CT[] =
  884. {
  885. AR_BASIC_UINT64,
  886. AR_BASIC_UNKNOWN
  887. };
  888. static const ArBasicKind g_UInt3264CT[] =
  889. {
  890. AR_BASIC_UINT32,
  891. AR_BASIC_UINT64,
  892. AR_BASIC_LITERAL_INT,
  893. AR_BASIC_UNKNOWN
  894. };
  895. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  896. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  897. {
  898. g_NullCT, // LICOMPTYPE_VOID
  899. g_BoolCT, // LICOMPTYPE_BOOL
  900. g_IntCT, // LICOMPTYPE_INT
  901. g_UIntCT, // LICOMPTYPE_UINT
  902. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  903. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  904. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  905. g_FloatCT, // LICOMPTYPE_FLOAT
  906. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  907. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  908. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  909. g_DoubleCT, // LICOMPTYPE_DOUBLE
  910. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  911. g_NumericCT, // LICOMPTYPE_NUMERIC
  912. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  913. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  914. g_AnyCT, // LICOMPTYPE_ANY
  915. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  916. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  917. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  918. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  919. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  920. g_SamplerCT, // LICOMPTYPE_SAMPLER
  921. g_StringCT, // LICOMPTYPE_STRING
  922. g_WaveCT, // LICOMPTYPE_WAVE
  923. g_UInt64CT, // LICOMPTYPE_UINT64
  924. g_UInt3264CT // LICOMPTYPE_UINT32_64
  925. };
  926. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT);
  927. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  928. // Basic kind objects that are represented as HLSL structures or templates.
  929. static
  930. const ArBasicKind g_ArBasicKindsAsTypes[] =
  931. {
  932. AR_OBJECT_BUFFER, // Buffer
  933. // AR_OBJECT_TEXTURE,
  934. AR_OBJECT_TEXTURE1D, // Texture1D
  935. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  936. AR_OBJECT_TEXTURE2D, // Texture2D
  937. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  938. AR_OBJECT_TEXTURE3D, // Texture3D
  939. AR_OBJECT_TEXTURECUBE, // TextureCube
  940. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  941. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  942. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  943. AR_OBJECT_SAMPLER,
  944. //AR_OBJECT_SAMPLER1D,
  945. //AR_OBJECT_SAMPLER2D,
  946. //AR_OBJECT_SAMPLER3D,
  947. //AR_OBJECT_SAMPLERCUBE,
  948. AR_OBJECT_SAMPLERCOMPARISON,
  949. AR_OBJECT_POINTSTREAM,
  950. AR_OBJECT_LINESTREAM,
  951. AR_OBJECT_TRIANGLESTREAM,
  952. AR_OBJECT_INPUTPATCH,
  953. AR_OBJECT_OUTPUTPATCH,
  954. AR_OBJECT_RWTEXTURE1D,
  955. AR_OBJECT_RWTEXTURE1D_ARRAY,
  956. AR_OBJECT_RWTEXTURE2D,
  957. AR_OBJECT_RWTEXTURE2D_ARRAY,
  958. AR_OBJECT_RWTEXTURE3D,
  959. AR_OBJECT_RWBUFFER,
  960. AR_OBJECT_BYTEADDRESS_BUFFER,
  961. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  962. AR_OBJECT_STRUCTURED_BUFFER,
  963. AR_OBJECT_RWSTRUCTURED_BUFFER,
  964. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  965. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  966. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  967. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  968. AR_OBJECT_ROVBUFFER,
  969. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  970. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  971. AR_OBJECT_ROVTEXTURE1D,
  972. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  973. AR_OBJECT_ROVTEXTURE2D,
  974. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  975. AR_OBJECT_ROVTEXTURE3D,
  976. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  977. AR_OBJECT_WAVE
  978. };
  979. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  980. static
  981. const uint8_t g_ArBasicKindsTemplateCount[] =
  982. {
  983. 1, // AR_OBJECT_BUFFER
  984. // AR_OBJECT_TEXTURE,
  985. 1, // AR_OBJECT_TEXTURE1D
  986. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  987. 1, // AR_OBJECT_TEXTURE2D
  988. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  989. 1, // AR_OBJECT_TEXTURE3D
  990. 1, // AR_OBJECT_TEXTURECUBE
  991. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  992. 2, // AR_OBJECT_TEXTURE2DMS
  993. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  994. 0, // AR_OBJECT_SAMPLER
  995. //AR_OBJECT_SAMPLER1D,
  996. //AR_OBJECT_SAMPLER2D,
  997. //AR_OBJECT_SAMPLER3D,
  998. //AR_OBJECT_SAMPLERCUBE,
  999. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1000. 1, // AR_OBJECT_POINTSTREAM
  1001. 1, // AR_OBJECT_LINESTREAM
  1002. 1, // AR_OBJECT_TRIANGLESTREAM
  1003. 2, // AR_OBJECT_INPUTPATCH
  1004. 2, // AR_OBJECT_OUTPUTPATCH
  1005. 1, // AR_OBJECT_RWTEXTURE1D
  1006. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1007. 1, // AR_OBJECT_RWTEXTURE2D
  1008. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1009. 1, // AR_OBJECT_RWTEXTURE3D
  1010. 1, // AR_OBJECT_RWBUFFER
  1011. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1012. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1013. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1014. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1015. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1016. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1017. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1018. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1019. 1, // AR_OBJECT_ROVBUFFER
  1020. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1021. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1022. 1, // AR_OBJECT_ROVTEXTURE1D
  1023. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1024. 1, // AR_OBJECT_ROVTEXTURE2D
  1025. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1026. 1, // AR_OBJECT_ROVTEXTURE3D
  1027. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1028. 0, // AR_OBJECT_WAVE
  1029. };
  1030. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1031. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1032. struct SubscriptOperatorRecord
  1033. {
  1034. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1035. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1036. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1037. };
  1038. // Subscript operators for objects that are represented as HLSL structures or templates.
  1039. static
  1040. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1041. {
  1042. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1043. // AR_OBJECT_TEXTURE,
  1044. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1045. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1046. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1047. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1048. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1049. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1050. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1051. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1052. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1053. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1054. //AR_OBJECT_SAMPLER1D,
  1055. //AR_OBJECT_SAMPLER2D,
  1056. //AR_OBJECT_SAMPLER3D,
  1057. //AR_OBJECT_SAMPLERCUBE,
  1058. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1059. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1060. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1061. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1062. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1063. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1064. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1065. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1066. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1067. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1068. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1069. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1070. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1071. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1072. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1073. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1074. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1075. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1076. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1077. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1078. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1079. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1080. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1081. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1082. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1083. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1084. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1085. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1086. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1087. { 0, MipsFalse, SampleFalse } // AR_OBJECT_WAVE
  1088. };
  1089. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1090. // Type names for ArBasicKind values.
  1091. static
  1092. const char* g_ArBasicTypeNames[] =
  1093. {
  1094. "bool", "float", "<float16>", "half", "float", "double",
  1095. "int", "sbyte", "byte", "short", "ushort",
  1096. "int", "uint", "long", "ulong",
  1097. "min10float", "min16float",
  1098. "min12int", "min16int", "min16uint",
  1099. "<count>",
  1100. "<none>",
  1101. "<unknown>",
  1102. "<nocast>",
  1103. "<pointer>",
  1104. "null",
  1105. "string",
  1106. // "texture",
  1107. "Texture1D",
  1108. "Texture1DArray",
  1109. "Texture2D",
  1110. "Texture2DArray",
  1111. "Texture3D",
  1112. "TextureCube",
  1113. "TextureCubeArray",
  1114. "Texture2DMS",
  1115. "Texture2DMSArray",
  1116. "SamplerState",
  1117. "sampler1D",
  1118. "sampler2D",
  1119. "sampler3D",
  1120. "samplerCUBE",
  1121. "SamplerComparisonState",
  1122. "Buffer",
  1123. "RenderTargetView",
  1124. "DepthStencilView",
  1125. "ComputeShader",
  1126. "DomainShader",
  1127. "GeometryShader",
  1128. "HullShader",
  1129. "PixelShader",
  1130. "VertexShader",
  1131. "pixelfragment",
  1132. "vertexfragment",
  1133. "StateBlock",
  1134. "Rasterizer",
  1135. "DepthStencil",
  1136. "Blend",
  1137. "PointStream",
  1138. "LineStream",
  1139. "TriangleStream",
  1140. "InputPatch",
  1141. "OutputPatch",
  1142. "RWTexture1D",
  1143. "RWTexture1DArray",
  1144. "RWTexture2D",
  1145. "RWTexture2DArray",
  1146. "RWTexture3D",
  1147. "RWBuffer",
  1148. "ByteAddressBuffer",
  1149. "RWByteAddressBuffer",
  1150. "StructuredBuffer",
  1151. "RWStructuredBuffer",
  1152. "RWStructuredBuffer(Incrementable)",
  1153. "RWStructuredBuffer(Decrementable)",
  1154. "AppendStructuredBuffer",
  1155. "ConsumeStructuredBuffer",
  1156. "ConstantBuffer",
  1157. "TextureBuffer",
  1158. "RasterizerOrderedBuffer",
  1159. "RasterizerOrderedByteAddressBuffer",
  1160. "RasterizerOrderedStructuredBuffer",
  1161. "RasterizerOrderedTexture1D",
  1162. "RasterizerOrderedTexture1DArray",
  1163. "RasterizerOrderedTexture2D",
  1164. "RasterizerOrderedTexture2DArray",
  1165. "RasterizerOrderedTexture3D",
  1166. "<internal inner type object>",
  1167. "deprecated effect object",
  1168. "wave_t"
  1169. };
  1170. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1171. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1172. #define DXASSERT_VALIDBASICKIND(kind) \
  1173. DXASSERT(\
  1174. kind != AR_BASIC_COUNT && \
  1175. kind != AR_BASIC_NONE && \
  1176. kind != AR_BASIC_UNKNOWN && \
  1177. kind != AR_BASIC_NOCAST && \
  1178. kind != AR_BASIC_POINTER && \
  1179. kind != AR_OBJECT_RENDERTARGETVIEW && \
  1180. kind != AR_OBJECT_DEPTHSTENCILVIEW && \
  1181. kind != AR_OBJECT_COMPUTESHADER && \
  1182. kind != AR_OBJECT_DOMAINSHADER && \
  1183. kind != AR_OBJECT_GEOMETRYSHADER && \
  1184. kind != AR_OBJECT_HULLSHADER && \
  1185. kind != AR_OBJECT_PIXELSHADER && \
  1186. kind != AR_OBJECT_VERTEXSHADER && \
  1187. kind != AR_OBJECT_PIXELFRAGMENT && \
  1188. kind != AR_OBJECT_VERTEXFRAGMENT, "otherwise caller is using a special flag or an unsupported kind value");
  1189. static
  1190. const char* g_DeprecatedEffectObjectNames[] =
  1191. {
  1192. // These are case insensitive in fxc, but we'll just create two case aliases
  1193. // to capture the majority of cases
  1194. "texture", "Texture",
  1195. "pixelshader", "PixelShader",
  1196. "vertexshader", "VertexShader",
  1197. // These are case sensitive in fxc
  1198. "pixelfragment", // 13
  1199. "vertexfragment", // 14
  1200. "ComputeShader", // 13
  1201. "DomainShader", // 12
  1202. "GeometryShader", // 14
  1203. "HullShader", // 10
  1204. "BlendState", // 10
  1205. "DepthStencilState",// 17
  1206. "DepthStencilView", // 16
  1207. "RasterizerState", // 15
  1208. "RenderTargetView", // 16
  1209. };
  1210. // The CompareStringsWithLen function lexicographically compares LHS and RHS and
  1211. // returns a value indicating the relationship between the strings - < 0 if LHS is
  1212. // less than RHS, 0 if they are equal, > 0 if LHS is greater than RHS.
  1213. static
  1214. int CompareStringsWithLen(
  1215. _In_count_(LHSlen) const char* LHS, size_t LHSlen,
  1216. _In_count_(RHSlen) const char* RHS, size_t RHSlen
  1217. )
  1218. {
  1219. // Check whether the name is greater or smaller (without walking past end).
  1220. size_t maxNameComparable = std::min(LHSlen, RHSlen);
  1221. int comparison = strncmp(LHS, RHS, maxNameComparable);
  1222. if (comparison != 0) return comparison;
  1223. // Check whether the name is greater or smaller based on extra characters.
  1224. return LHSlen - RHSlen;
  1225. }
  1226. static hlsl::ParameterModifier
  1227. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1228. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1229. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1230. }
  1231. if (pArg->qwUsage == AR_QUAL_OUT) {
  1232. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1233. }
  1234. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1235. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1236. }
  1237. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1238. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1239. // The first argument is the return value, which isn't included.
  1240. for (UINT i = 1; i < pIntrinsic->uNumArgs; ++i) {
  1241. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1242. }
  1243. }
  1244. static bool IsAtomicOperation(IntrinsicOp op) {
  1245. switch (op) {
  1246. case IntrinsicOp::IOP_InterlockedAdd:
  1247. case IntrinsicOp::IOP_InterlockedAnd:
  1248. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1249. case IntrinsicOp::IOP_InterlockedCompareStore:
  1250. case IntrinsicOp::IOP_InterlockedExchange:
  1251. case IntrinsicOp::IOP_InterlockedMax:
  1252. case IntrinsicOp::IOP_InterlockedMin:
  1253. case IntrinsicOp::IOP_InterlockedOr:
  1254. case IntrinsicOp::IOP_InterlockedXor:
  1255. case IntrinsicOp::MOP_InterlockedAdd:
  1256. case IntrinsicOp::MOP_InterlockedAnd:
  1257. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1258. case IntrinsicOp::MOP_InterlockedCompareStore:
  1259. case IntrinsicOp::MOP_InterlockedExchange:
  1260. case IntrinsicOp::MOP_InterlockedMax:
  1261. case IntrinsicOp::MOP_InterlockedMin:
  1262. case IntrinsicOp::MOP_InterlockedOr:
  1263. case IntrinsicOp::MOP_InterlockedXor:
  1264. return true;
  1265. default:
  1266. return false;
  1267. }
  1268. }
  1269. static bool IsBuiltinTable(LPCSTR tableName) {
  1270. return tableName == kBuiltinIntrinsicTableName;
  1271. }
  1272. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1273. LPCSTR tableName, LPCSTR lowering,
  1274. const HLSL_INTRINSIC *pIntrinsic) {
  1275. unsigned opcode = (unsigned)pIntrinsic->Op;
  1276. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1277. QualType Ty = FD->getReturnType();
  1278. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(pIntrinsic->Op);
  1279. if (pIntrinsic->iOverloadParamIndex != -1) {
  1280. const FunctionProtoType *FT =
  1281. FD->getFunctionType()->getAs<FunctionProtoType>();
  1282. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1283. }
  1284. // TODO: refine the code for getting element type
  1285. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1286. Ty = VecTy->getElementType();
  1287. }
  1288. if (Ty->isUnsignedIntegerType()) {
  1289. opcode = hlsl::GetUnsignedOpcode(opcode);
  1290. }
  1291. }
  1292. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1293. if (pIntrinsic->bReadNone)
  1294. FD->addAttr(ConstAttr::CreateImplicit(context));
  1295. if (pIntrinsic->bReadOnly)
  1296. FD->addAttr(PureAttr::CreateImplicit(context));
  1297. }
  1298. static
  1299. FunctionDecl *AddHLSLIntrinsicFunction(
  1300. ASTContext &context, _In_ NamespaceDecl *NS,
  1301. LPCSTR tableName, LPCSTR lowering,
  1302. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1303. _In_count_(functionArgTypeCount) QualType *functionArgQualTypes,
  1304. _In_range_(0, g_MaxIntrinsicParamCount - 1) size_t functionArgTypeCount) {
  1305. DXASSERT(functionArgTypeCount - 1 < g_MaxIntrinsicParamCount,
  1306. "otherwise g_MaxIntrinsicParamCount should be larger");
  1307. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1308. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1309. InitParamMods(pIntrinsic, paramMods);
  1310. // Change dest address into reference type for atomic.
  1311. if (IsBuiltinTable(tableName)) {
  1312. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1313. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1314. "else operation was misrecognized");
  1315. functionArgQualTypes[kAtomicDstOperandIdx] =
  1316. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1317. }
  1318. }
  1319. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1320. // Change out/inout param to reference type.
  1321. if (paramMods[i-1].isAnyOut()) {
  1322. functionArgQualTypes[i] = context.getLValueReferenceType(functionArgQualTypes[i]);
  1323. }
  1324. }
  1325. IdentifierInfo &functionId = context.Idents.get(
  1326. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1327. DeclarationName functionName(&functionId);
  1328. QualType returnQualType = functionArgQualTypes[0];
  1329. QualType functionType = context.getFunctionType(
  1330. functionArgQualTypes[0],
  1331. ArrayRef<QualType>(functionArgQualTypes + 1,
  1332. functionArgQualTypes + functionArgTypeCount),
  1333. clang::FunctionProtoType::ExtProtoInfo(), paramMods);
  1334. FunctionDecl *functionDecl = FunctionDecl::Create(
  1335. context, currentDeclContext, NoLoc,
  1336. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1337. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1338. currentDeclContext->addDecl(functionDecl);
  1339. functionDecl->setLexicalDeclContext(currentDeclContext);
  1340. // put under hlsl namespace
  1341. functionDecl->setDeclContext(NS);
  1342. // Add intrinsic attribute
  1343. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1344. ParmVarDecl *paramDecls[g_MaxIntrinsicParamCount];
  1345. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1346. IdentifierInfo &parameterId = context.Idents.get(
  1347. StringRef(pIntrinsic->pArgs[i].pName), tok::TokenKind::identifier);
  1348. ParmVarDecl *paramDecl =
  1349. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1350. functionArgQualTypes[i], nullptr,
  1351. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1352. functionDecl->addDecl(paramDecl);
  1353. paramDecls[i - 1] = paramDecl;
  1354. }
  1355. functionDecl->setParams(
  1356. ArrayRef<ParmVarDecl *>(paramDecls, functionArgTypeCount - 1));
  1357. functionDecl->setImplicit(true);
  1358. return functionDecl;
  1359. }
  1360. /// <summary>
  1361. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1362. /// </summary>
  1363. static
  1364. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1365. {
  1366. DXASSERT_NOMSG(expr != nullptr);
  1367. expr = expr->IgnoreParens();
  1368. return
  1369. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1370. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1371. }
  1372. /// <summary>
  1373. /// Silences diagnostics for the initialization sequence, typically because they have already
  1374. /// been emitted.
  1375. /// </summary>
  1376. static
  1377. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1378. {
  1379. DXASSERT_NOMSG(initSequence != nullptr);
  1380. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1381. }
  1382. class UsedIntrinsic
  1383. {
  1384. public:
  1385. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1386. {
  1387. // The canonical representations are unique'd in an ASTContext, and so these
  1388. // should be stable.
  1389. return RHS.getTypePtr() - LHS.getTypePtr();
  1390. }
  1391. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1392. {
  1393. // The intrinsics are defined in a single static table, and so should be stable.
  1394. return RHS - LHS;
  1395. }
  1396. int compare(const UsedIntrinsic& other) const
  1397. {
  1398. // Check whether it's the same instance.
  1399. if (this == &other) return 0;
  1400. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1401. if (result != 0) return result;
  1402. // At this point, it's the exact same intrinsic name.
  1403. // Compare the arguments for ordering then.
  1404. DXASSERT(m_argLength == other.m_argLength, "intrinsics aren't overloaded on argument count, so we should never create a key with different #s");
  1405. for (size_t i = 0; i < m_argLength; i++) {
  1406. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1407. if (argComparison != 0) return argComparison;
  1408. }
  1409. // Exactly the same.
  1410. return 0;
  1411. }
  1412. public:
  1413. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, _In_count_(argCount) QualType* args, size_t argCount)
  1414. : m_intrinsicSource(intrinsicSource), m_argLength(argCount), m_functionDecl(nullptr)
  1415. {
  1416. std::copy(args, args + argCount, m_args);
  1417. }
  1418. void setFunctionDecl(FunctionDecl* value) const
  1419. {
  1420. DXASSERT(value != nullptr, "no reason to clear this out");
  1421. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1422. m_functionDecl = value;
  1423. }
  1424. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1425. bool operator==(const UsedIntrinsic& other) const
  1426. {
  1427. return compare(other) == 0;
  1428. }
  1429. bool operator<(const UsedIntrinsic& other) const
  1430. {
  1431. return compare(other) < 0;
  1432. }
  1433. private:
  1434. QualType m_args[g_MaxIntrinsicParamCount];
  1435. size_t m_argLength;
  1436. const HLSL_INTRINSIC* m_intrinsicSource;
  1437. mutable FunctionDecl* m_functionDecl;
  1438. };
  1439. template <typename T>
  1440. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1441. {
  1442. if (ptr != nullptr)
  1443. {
  1444. *ptr = value;
  1445. }
  1446. }
  1447. static bool CombineBasicTypes(
  1448. ArBasicKind LeftKind,
  1449. ArBasicKind RightKind,
  1450. _Out_ ArBasicKind* pOutKind,
  1451. _Out_opt_ CastKind* leftCastKind = nullptr,
  1452. _Out_opt_ CastKind* rightCastKind = nullptr)
  1453. {
  1454. AssignOpt(CastKind::CK_NoOp, leftCastKind);
  1455. AssignOpt(CastKind::CK_NoOp, rightCastKind);
  1456. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1457. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1458. return false;
  1459. }
  1460. if (LeftKind == RightKind) {
  1461. *pOutKind = LeftKind;
  1462. return true;
  1463. }
  1464. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1465. UINT uRightProps = GetBasicKindProps(RightKind);
  1466. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1467. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1468. UINT uBothFlags = uLeftProps & uRightProps;
  1469. UINT uEitherFlags = uLeftProps | uRightProps;
  1470. if ((BPROP_BOOLEAN & uBothFlags) != 0)
  1471. {
  1472. *pOutKind = AR_BASIC_BOOL;
  1473. return true;
  1474. }
  1475. if ((BPROP_LITERAL & uBothFlags) != 0)
  1476. {
  1477. if ((BPROP_INTEGER & uBothFlags) != 0)
  1478. {
  1479. *pOutKind = AR_BASIC_LITERAL_INT;
  1480. }
  1481. else
  1482. {
  1483. *pOutKind = AR_BASIC_LITERAL_FLOAT;
  1484. }
  1485. return true;
  1486. }
  1487. if ((BPROP_UNSIGNED & uBothFlags) != 0)
  1488. {
  1489. switch (uBits)
  1490. {
  1491. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1492. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1493. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1494. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1495. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1496. default: DXASSERT_NOMSG(false); break;
  1497. }
  1498. AssignOpt(CK_IntegralCast, leftCastKind);
  1499. AssignOpt(CK_IntegralCast, rightCastKind);
  1500. return true;
  1501. }
  1502. if ((BPROP_INTEGER & uBothFlags) != 0)
  1503. {
  1504. if ((BPROP_UNSIGNED & uEitherFlags) != 0)
  1505. {
  1506. switch (uBits)
  1507. {
  1508. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1509. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1510. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1511. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1512. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1513. default: DXASSERT_NOMSG(false); break;
  1514. }
  1515. }
  1516. else
  1517. {
  1518. switch (uBits)
  1519. {
  1520. case BPROP_BITS0: *pOutKind = AR_BASIC_LITERAL_INT; break;
  1521. case BPROP_BITS8: *pOutKind = AR_BASIC_INT8; break;
  1522. case BPROP_BITS12: *pOutKind = AR_BASIC_MIN12INT; break;
  1523. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1524. *pOutKind = AR_BASIC_MIN16INT : *pOutKind = AR_BASIC_INT16; break;
  1525. case BPROP_BITS32: *pOutKind = AR_BASIC_INT32; break;
  1526. case BPROP_BITS64: *pOutKind = AR_BASIC_INT64; break;
  1527. default: DXASSERT_NOMSG(false); break;
  1528. }
  1529. }
  1530. AssignOpt(CK_IntegralCast, leftCastKind);
  1531. AssignOpt(CK_IntegralCast, rightCastKind);
  1532. return true;
  1533. }
  1534. // At least one side is floating-point. Assume both are and fix later
  1535. // in this function.
  1536. DXASSERT_NOMSG((BPROP_FLOATING & uEitherFlags) != 0);
  1537. AssignOpt(CK_FloatingCast, leftCastKind);
  1538. AssignOpt(CK_FloatingCast, rightCastKind);
  1539. if ((BPROP_FLOATING & uBothFlags) == 0)
  1540. {
  1541. // One side is floating-point and one isn't,
  1542. // convert to the floating-point type.
  1543. if ((BPROP_FLOATING & uLeftProps) != 0)
  1544. {
  1545. uBits = GET_BPROP_BITS(uLeftProps);
  1546. AssignOpt(CK_IntegralToFloating, rightCastKind);
  1547. }
  1548. else
  1549. {
  1550. DXASSERT_NOMSG((BPROP_FLOATING & uRightProps) != 0);
  1551. uBits = GET_BPROP_BITS(uRightProps);
  1552. AssignOpt(CK_IntegralToFloating, leftCastKind);
  1553. }
  1554. if (uBits == 0)
  1555. {
  1556. // We have a literal plus a non-literal so drop
  1557. // any literalness.
  1558. uBits = BPROP_BITS32;
  1559. }
  1560. }
  1561. switch (uBits)
  1562. {
  1563. case BPROP_BITS10:
  1564. *pOutKind = AR_BASIC_MIN10FLOAT;
  1565. break;
  1566. case BPROP_BITS16:
  1567. if ((uEitherFlags & BPROP_MIN_PRECISION) != 0)
  1568. {
  1569. *pOutKind = AR_BASIC_MIN16FLOAT;
  1570. }
  1571. else
  1572. {
  1573. *pOutKind = AR_BASIC_FLOAT16;
  1574. }
  1575. break;
  1576. case BPROP_BITS32:
  1577. if ((uEitherFlags & BPROP_LITERAL) != 0 &&
  1578. (uEitherFlags & BPROP_PARTIAL_PRECISION) != 0)
  1579. {
  1580. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1581. }
  1582. else if ((uBothFlags & BPROP_PARTIAL_PRECISION) != 0)
  1583. {
  1584. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1585. }
  1586. else
  1587. {
  1588. *pOutKind = AR_BASIC_FLOAT32;
  1589. }
  1590. break;
  1591. case BPROP_BITS64:
  1592. *pOutKind = AR_BASIC_FLOAT64;
  1593. break;
  1594. default:
  1595. DXASSERT(false, "unexpected bit count");
  1596. *pOutKind = AR_BASIC_FLOAT32;
  1597. break;
  1598. }
  1599. return true;
  1600. }
  1601. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1602. {
  1603. };
  1604. static
  1605. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1606. {
  1607. DXASSERT_NOMSG(intrinsics != nullptr);
  1608. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1609. switch (kind)
  1610. {
  1611. case AR_OBJECT_TRIANGLESTREAM:
  1612. case AR_OBJECT_POINTSTREAM:
  1613. case AR_OBJECT_LINESTREAM:
  1614. *intrinsics = g_StreamMethods;
  1615. *intrinsicCount = _countof(g_StreamMethods);
  1616. break;
  1617. case AR_OBJECT_TEXTURE1D:
  1618. *intrinsics = g_Texture1DMethods;
  1619. *intrinsicCount = _countof(g_Texture1DMethods);
  1620. break;
  1621. case AR_OBJECT_TEXTURE1D_ARRAY:
  1622. *intrinsics = g_Texture1DArrayMethods;
  1623. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1624. break;
  1625. case AR_OBJECT_TEXTURE2D:
  1626. *intrinsics = g_Texture2DMethods;
  1627. *intrinsicCount = _countof(g_Texture2DMethods);
  1628. break;
  1629. case AR_OBJECT_TEXTURE2DMS:
  1630. *intrinsics = g_Texture2DMSMethods;
  1631. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1632. break;
  1633. case AR_OBJECT_TEXTURE2D_ARRAY:
  1634. *intrinsics = g_Texture2DArrayMethods;
  1635. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1636. break;
  1637. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1638. *intrinsics = g_Texture2DArrayMSMethods;
  1639. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1640. break;
  1641. case AR_OBJECT_TEXTURE3D:
  1642. *intrinsics = g_Texture3DMethods;
  1643. *intrinsicCount = _countof(g_Texture3DMethods);
  1644. break;
  1645. case AR_OBJECT_TEXTURECUBE:
  1646. *intrinsics = g_TextureCUBEMethods;
  1647. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1648. break;
  1649. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1650. *intrinsics = g_TextureCUBEArrayMethods;
  1651. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1652. break;
  1653. case AR_OBJECT_BUFFER:
  1654. *intrinsics = g_BufferMethods;
  1655. *intrinsicCount = _countof(g_BufferMethods);
  1656. break;
  1657. case AR_OBJECT_RWTEXTURE1D:
  1658. case AR_OBJECT_ROVTEXTURE1D:
  1659. *intrinsics = g_RWTexture1DMethods;
  1660. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1661. break;
  1662. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1663. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1664. *intrinsics = g_RWTexture1DArrayMethods;
  1665. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1666. break;
  1667. case AR_OBJECT_RWTEXTURE2D:
  1668. case AR_OBJECT_ROVTEXTURE2D:
  1669. *intrinsics = g_RWTexture2DMethods;
  1670. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1671. break;
  1672. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1673. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1674. *intrinsics = g_RWTexture2DArrayMethods;
  1675. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1676. break;
  1677. case AR_OBJECT_RWTEXTURE3D:
  1678. case AR_OBJECT_ROVTEXTURE3D:
  1679. *intrinsics = g_RWTexture3DMethods;
  1680. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1681. break;
  1682. case AR_OBJECT_RWBUFFER:
  1683. case AR_OBJECT_ROVBUFFER:
  1684. *intrinsics = g_RWBufferMethods;
  1685. *intrinsicCount = _countof(g_RWBufferMethods);
  1686. break;
  1687. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1688. *intrinsics = g_ByteAddressBufferMethods;
  1689. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1690. break;
  1691. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1692. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1693. *intrinsics = g_RWByteAddressBufferMethods;
  1694. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1695. break;
  1696. case AR_OBJECT_STRUCTURED_BUFFER:
  1697. *intrinsics = g_StructuredBufferMethods;
  1698. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1699. break;
  1700. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1701. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1702. *intrinsics = g_RWStructuredBufferMethods;
  1703. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1704. break;
  1705. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1706. *intrinsics = g_AppendStructuredBufferMethods;
  1707. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1708. break;
  1709. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1710. *intrinsics = g_ConsumeStructuredBufferMethods;
  1711. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1712. break;
  1713. default:
  1714. *intrinsics = nullptr;
  1715. *intrinsicCount = 0;
  1716. break;
  1717. }
  1718. }
  1719. static
  1720. bool IsRowOrColumnVariable(size_t value)
  1721. {
  1722. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1723. }
  1724. static
  1725. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1726. {
  1727. return
  1728. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1729. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1730. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1731. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1732. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1733. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1734. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1735. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1736. value == LICOMPTYPE_ANY; // any time
  1737. }
  1738. static
  1739. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1740. {
  1741. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1742. }
  1743. static
  1744. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  1745. {
  1746. // Note that LITEMPLATE_OBJECT can accept different types, but it
  1747. // specifies a single 'layout'. In practice, this information is used
  1748. // together with a component type that specifies a single object.
  1749. return value == LITEMPLATE_ANY; // Any layout
  1750. }
  1751. static
  1752. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  1753. {
  1754. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  1755. }
  1756. static
  1757. bool DoesIntrinsicRequireTemplate(const HLSL_INTRINSIC* intrinsic)
  1758. {
  1759. const HLSL_INTRINSIC_ARGUMENT* argument = intrinsic->pArgs;
  1760. for (size_t i = 0; i < intrinsic->uNumArgs; i++)
  1761. {
  1762. // The intrinsic will require a template for any of these reasons:
  1763. // - A type template (layout) or component needs to match something else.
  1764. // - A parameter can take multiple types.
  1765. // - Row or columns numbers may vary.
  1766. if (
  1767. argument->uTemplateId != i ||
  1768. DoesLegalTemplateAcceptMultipleTypes(argument->uLegalTemplates) ||
  1769. DoesComponentTypeAcceptMultipleTypes(argument->uLegalComponentTypes) ||
  1770. IsRowOrColumnVariable(argument->uCols) ||
  1771. IsRowOrColumnVariable(argument->uRows))
  1772. {
  1773. return true;
  1774. }
  1775. argument++;
  1776. }
  1777. return false;
  1778. }
  1779. static
  1780. bool TemplateHasDefaultType(ArBasicKind kind)
  1781. {
  1782. return
  1783. kind == AR_OBJECT_BUFFER ||
  1784. kind == AR_OBJECT_TEXTURE1D || kind == AR_OBJECT_TEXTURE2D || kind == AR_OBJECT_TEXTURE3D ||
  1785. kind == AR_OBJECT_TEXTURE1D_ARRAY || kind == AR_OBJECT_TEXTURE2D_ARRAY ||
  1786. kind == AR_OBJECT_TEXTURECUBE || kind == AR_OBJECT_TEXTURECUBE_ARRAY;
  1787. }
  1788. /// <summary>
  1789. /// Use this class to iterate over intrinsic definitions that come from an external source.
  1790. /// </summary>
  1791. class IntrinsicTableDefIter
  1792. {
  1793. private:
  1794. StringRef _typeName;
  1795. StringRef _functionName;
  1796. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  1797. const HLSL_INTRINSIC* _tableIntrinsic;
  1798. UINT64 _tableLookupCookie;
  1799. unsigned _tableIndex;
  1800. unsigned _argCount;
  1801. bool _firstChecked;
  1802. IntrinsicTableDefIter(
  1803. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1804. StringRef typeName,
  1805. StringRef functionName,
  1806. unsigned argCount) :
  1807. _tables(tables), _typeName(typeName), _functionName(functionName), _argCount(argCount),
  1808. _tableIndex(0), _tableLookupCookie(0), _tableIntrinsic(nullptr), _firstChecked(false)
  1809. {
  1810. }
  1811. void CheckForIntrinsic() {
  1812. if (_tableIndex >= _tables.size()) {
  1813. return;
  1814. }
  1815. _firstChecked = true;
  1816. // TODO: review this - this will allocate at least once per string
  1817. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  1818. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  1819. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  1820. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  1821. _tableLookupCookie = 0;
  1822. _tableIntrinsic = nullptr;
  1823. }
  1824. }
  1825. void MoveToNext() {
  1826. for (;;) {
  1827. // If we don't have an intrinsic, try the following table.
  1828. if (_firstChecked && _tableIntrinsic == nullptr) {
  1829. _tableIndex++;
  1830. }
  1831. CheckForIntrinsic();
  1832. if (_tableIndex == _tables.size() ||
  1833. (_tableIntrinsic != nullptr &&
  1834. _tableIntrinsic->uNumArgs ==
  1835. (_argCount + 1))) // uNumArgs includes return
  1836. break;
  1837. }
  1838. }
  1839. public:
  1840. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1841. StringRef typeName,
  1842. StringRef functionName,
  1843. unsigned argCount)
  1844. {
  1845. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  1846. return result;
  1847. }
  1848. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  1849. {
  1850. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  1851. result._tableIndex = tables.size();
  1852. return result;
  1853. }
  1854. bool operator!=(const IntrinsicTableDefIter& other)
  1855. {
  1856. if (!_firstChecked) {
  1857. MoveToNext();
  1858. }
  1859. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  1860. }
  1861. const HLSL_INTRINSIC* operator*()
  1862. {
  1863. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  1864. return _tableIntrinsic;
  1865. }
  1866. LPCSTR GetTableName()
  1867. {
  1868. LPCSTR tableName = nullptr;
  1869. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  1870. return nullptr;
  1871. }
  1872. return tableName;
  1873. }
  1874. LPCSTR GetLoweringStrategy()
  1875. {
  1876. LPCSTR lowering = nullptr;
  1877. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  1878. return nullptr;
  1879. }
  1880. return lowering;
  1881. }
  1882. IntrinsicTableDefIter& operator++()
  1883. {
  1884. MoveToNext();
  1885. return *this;
  1886. }
  1887. };
  1888. /// <summary>
  1889. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  1890. /// </summary>
  1891. class IntrinsicDefIter
  1892. {
  1893. const HLSL_INTRINSIC* _current;
  1894. const HLSL_INTRINSIC* _end;
  1895. IntrinsicTableDefIter _tableIter;
  1896. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  1897. _current(value), _end(end), _tableIter(tableIter)
  1898. { }
  1899. public:
  1900. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  1901. {
  1902. return IntrinsicDefIter(start, table + count, tableIter);
  1903. }
  1904. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  1905. {
  1906. return IntrinsicDefIter(table + count, table + count, tableIter);
  1907. }
  1908. bool operator!=(const IntrinsicDefIter& other)
  1909. {
  1910. return _current != other._current || _tableIter.operator!=(other._tableIter);
  1911. }
  1912. const HLSL_INTRINSIC* operator*()
  1913. {
  1914. return (_current != _end) ? _current : *_tableIter;
  1915. }
  1916. LPCSTR GetTableName()
  1917. {
  1918. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  1919. }
  1920. LPCSTR GetLoweringStrategy()
  1921. {
  1922. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  1923. }
  1924. IntrinsicDefIter& operator++()
  1925. {
  1926. if (_current != _end) {
  1927. const HLSL_INTRINSIC* next = _current + 1;
  1928. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  1929. _current = next;
  1930. }
  1931. else {
  1932. _current = _end;
  1933. }
  1934. } else {
  1935. ++_tableIter;
  1936. }
  1937. return *this;
  1938. }
  1939. };
  1940. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  1941. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  1942. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  1943. }
  1944. class HLSLExternalSource : public ExternalSemaSource {
  1945. private:
  1946. // Inner types.
  1947. struct FindStructBasicTypeResult {
  1948. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  1949. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  1950. FindStructBasicTypeResult(ArBasicKind kind,
  1951. unsigned int basicKindAsTypeIndex)
  1952. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  1953. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  1954. };
  1955. // Declaration for matrix and vector templates.
  1956. ClassTemplateDecl* m_matrixTemplateDecl;
  1957. ClassTemplateDecl* m_vectorTemplateDecl;
  1958. // Namespace decl for hlsl intrin functions
  1959. NamespaceDecl* m_hlslNSDecl;
  1960. // Context being processed.
  1961. _Notnull_ ASTContext* m_context;
  1962. // Semantic analyzer being processed.
  1963. Sema* m_sema;
  1964. // Intrinsic tables available externally.
  1965. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  1966. // Scalar types indexed by HLSLScalarType.
  1967. QualType m_scalarTypes[HLSLScalarTypeCount];
  1968. // Matrix types already built indexed by type, row-count, col-count. Should probably move to a sparse map. Instrument to figure out best initial size.
  1969. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  1970. // Matrix types already built, in shorthand form.
  1971. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  1972. // Vector types already built.
  1973. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  1974. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  1975. // Built-in object types declarations, indexed by basic kind constant.
  1976. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  1977. // Map from object decl to the object index.
  1978. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  1979. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  1980. // Mask for object which not has methods created.
  1981. uint64_t m_objectTypeLazyInitMask;
  1982. UsedIntrinsicStore m_usedIntrinsics;
  1983. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  1984. void AddHLSLScalarTypes();
  1985. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  1986. {
  1987. DXASSERT_NOMSG(recordDecl != nullptr);
  1988. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  1989. NamedDecl* parameterDecl = parameterList->getParam(0);
  1990. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  1991. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  1992. return QualType(parmDecl->getTypeForDecl(), 0);
  1993. }
  1994. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  1995. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  1996. {
  1997. int templateRef = intrinsic->pArgs[index].uTemplateId;
  1998. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  1999. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2000. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2001. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2002. if (
  2003. templateRef >= 0 &&
  2004. templateArg->uTemplateId == templateRef &&
  2005. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2006. componentRef >= 0 &&
  2007. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2008. componentArg->uComponentTypeId == 0 &&
  2009. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2010. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2011. !IsRowOrColumnVariable(matrixArg->uRows))
  2012. {
  2013. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2014. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2015. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2016. }
  2017. return QualType();
  2018. }
  2019. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2020. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2021. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2022. _Inout_ size_t* templateParamNamedDeclsCount)
  2023. {
  2024. DXASSERT_NOMSG(name != nullptr);
  2025. DXASSERT_NOMSG(recordDecl != nullptr);
  2026. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2027. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2028. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2029. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2030. // Create the declaration for the template parameter.
  2031. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2032. TemplateTypeParmDecl* templateTypeParmDecl =
  2033. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2034. id, TypenameTrue, ParameterPackFalse);
  2035. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2036. // Create the type that the parameter represents.
  2037. QualType result = m_context->getTemplateTypeParmType(
  2038. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2039. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2040. // it need not concern itself with maintaining this value.
  2041. (*templateParamNamedDeclsCount)++;
  2042. return result;
  2043. }
  2044. // Adds a function specified by the given intrinsic to a record declaration.
  2045. // The template depth will be zero for records that don't have a "template<>" line
  2046. // even if conceptual; or one if it does have one.
  2047. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2048. {
  2049. DXASSERT_NOMSG(recordDecl != nullptr);
  2050. DXASSERT_NOMSG(intrinsic != nullptr);
  2051. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2052. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2053. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2054. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2055. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2056. //
  2057. // Build template parameters, parameter types, and the return type.
  2058. // Parameter declarations are built after the function is created, to use it as their scope.
  2059. //
  2060. unsigned int numParams = intrinsic->uNumArgs - 1;
  2061. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2062. size_t templateParamNamedDeclsCount = 0;
  2063. QualType argsQTs[g_MaxIntrinsicParamCount];
  2064. StringRef argNames[g_MaxIntrinsicParamCount];
  2065. QualType functionResultQT;
  2066. DXASSERT(
  2067. _countof(templateParamNamedDecls) >= numParams + 1,
  2068. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2069. // Handle the return type.
  2070. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2071. // if (functionResultQT.isNull()) {
  2072. // Workaround for template parameter argument count mismatch.
  2073. // Create template parameter for return type always
  2074. // TODO: reenable the check and skip template argument.
  2075. functionResultQT = AddTemplateParamToArray(
  2076. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2077. &templateParamNamedDeclsCount);
  2078. // }
  2079. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2080. InitParamMods(intrinsic, paramMods);
  2081. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2082. // Handle parameters.
  2083. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2084. {
  2085. //
  2086. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2087. //
  2088. // However this may produce template instantiations with equivalent template arguments
  2089. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2090. // but the current intrinsic table has rules that are hard to process in their current form
  2091. // to find all cases.
  2092. //
  2093. char name[g_MaxIntrinsicParamName + 2];
  2094. name[0] = 'T';
  2095. name[1] = '\0';
  2096. strcat_s(name, intrinsic->pArgs[i].pName);
  2097. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2098. // Change out/inout param to reference type.
  2099. if (paramMods[i-1].isAnyOut())
  2100. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2101. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2102. }
  2103. // Create the declaration.
  2104. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2105. DeclarationName declarationName = DeclarationName(ii);
  2106. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2107. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2108. declarationName, true);
  2109. functionDecl->setImplicit(true);
  2110. // If the function is a template function, create the declaration and cross-reference.
  2111. if (templateParamNamedDeclsCount > 0)
  2112. {
  2113. hlsl::CreateFunctionTemplateDecl(
  2114. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2115. }
  2116. }
  2117. // Checks whether the two specified intrinsics generate equivalent templates.
  2118. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2119. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2120. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2121. {
  2122. if (left == right)
  2123. {
  2124. return true;
  2125. }
  2126. if (left == nullptr || right == nullptr)
  2127. {
  2128. return false;
  2129. }
  2130. return (left->uNumArgs == right->uNumArgs &&
  2131. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2132. }
  2133. // Adds all the intrinsic methods that correspond to the specified type.
  2134. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2135. {
  2136. DXASSERT_NOMSG(recordDecl != nullptr);
  2137. DXASSERT_NOMSG(templateDepth >= 0);
  2138. const HLSL_INTRINSIC* intrinsics;
  2139. const HLSL_INTRINSIC* prior = nullptr;
  2140. size_t intrinsicCount;
  2141. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2142. DXASSERT(
  2143. (intrinsics == nullptr) == (intrinsicCount == 0),
  2144. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2145. while (intrinsicCount--)
  2146. {
  2147. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2148. {
  2149. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2150. prior = intrinsics;
  2151. }
  2152. intrinsics++;
  2153. }
  2154. }
  2155. void AddDoubleSubscriptSupport(
  2156. _In_ ClassTemplateDecl* typeDecl,
  2157. _In_ CXXRecordDecl* recordDecl,
  2158. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2159. _In_z_ const char* type0Name,
  2160. _In_z_ const char* type1Name,
  2161. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2162. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2163. {
  2164. DXASSERT_NOMSG(typeDecl != nullptr);
  2165. DXASSERT_NOMSG(recordDecl != nullptr);
  2166. DXASSERT_NOMSG(memberName != nullptr);
  2167. DXASSERT_NOMSG(!elementType.isNull());
  2168. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2169. DXASSERT_NOMSG(type0Name != nullptr);
  2170. DXASSERT_NOMSG(type1Name != nullptr);
  2171. DXASSERT_NOMSG(indexer0Name != nullptr);
  2172. DXASSERT_NOMSG(!indexer0Type.isNull());
  2173. DXASSERT_NOMSG(indexer1Name != nullptr);
  2174. DXASSERT_NOMSG(!indexer1Type.isNull());
  2175. //
  2176. // Add inner types to the templates to represent the following C++ code inside the class.
  2177. // public:
  2178. // class sample_slice_type
  2179. // {
  2180. // public: TElement operator[](uint3 index);
  2181. // };
  2182. // class sample_type
  2183. // {
  2184. // public: sample_slice_type operator[](uint slice);
  2185. // };
  2186. // sample_type sample;
  2187. //
  2188. // Variable names reflect this structure, but this code will also produce the types
  2189. // for .mips access.
  2190. //
  2191. const bool MutableTrue = true;
  2192. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2193. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2194. &m_context->Idents.get(StringRef(type1Name)));
  2195. sampleSliceTypeDecl->setAccess(AS_public);
  2196. sampleSliceTypeDecl->setImplicit();
  2197. recordDecl->addDecl(sampleSliceTypeDecl);
  2198. sampleSliceTypeDecl->startDefinition();
  2199. const bool MutableFalse = false;
  2200. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2201. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2202. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2203. sliceHandleDecl->setAccess(AS_private);
  2204. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2205. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2206. sampleSliceTypeDecl, elementType,
  2207. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2208. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2209. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2210. sampleSliceTypeDecl->completeDefinition();
  2211. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2212. &m_context->Idents.get(StringRef(type0Name)));
  2213. sampleTypeDecl->setAccess(AS_public);
  2214. recordDecl->addDecl(sampleTypeDecl);
  2215. sampleTypeDecl->startDefinition();
  2216. sampleTypeDecl->setImplicit();
  2217. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2218. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2219. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2220. sampleHandleDecl->setAccess(AS_private);
  2221. sampleTypeDecl->addDecl(sampleHandleDecl);
  2222. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2223. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2224. sampleTypeDecl, m_context->getRValueReferenceType(sampleSliceType), // TODO: choose LValueRef if writable.
  2225. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2226. sampleTypeDecl->completeDefinition();
  2227. // Add subscript attribute
  2228. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2229. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2230. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2231. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2232. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2233. sampleFieldDecl->setAccess(AS_public);
  2234. recordDecl->addDecl(sampleFieldDecl);
  2235. }
  2236. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2237. _In_ CXXRecordDecl *recordDecl,
  2238. SubscriptOperatorRecord op) {
  2239. DXASSERT_NOMSG(typeDecl != nullptr);
  2240. DXASSERT_NOMSG(recordDecl != nullptr);
  2241. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2242. op.SubscriptCardinality <= 3);
  2243. DXASSERT(op.SubscriptCardinality > 0 ||
  2244. (op.HasMips == false && op.HasSample == false),
  2245. "objects that have .mips or .sample member also have a plain "
  2246. "subscript defined (otherwise static table is "
  2247. "likely incorrect, and this function won't know the cardinality "
  2248. "of the position parameter");
  2249. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2250. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2251. "read/write objects don't have .mips or .sample members");
  2252. // Return early if there is no work to be done.
  2253. if (op.SubscriptCardinality == 0) {
  2254. return;
  2255. }
  2256. const unsigned int templateDepth = 1;
  2257. // Add an operator[].
  2258. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2259. typeDecl->getTemplateParameters()->getParam(0));
  2260. QualType resultType = m_context->getTemplateTypeParmType(
  2261. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2262. if (isReadWrite)
  2263. resultType = m_context->getLValueReferenceType(resultType, false);
  2264. else
  2265. resultType = m_context->getRValueReferenceType(resultType);
  2266. QualType indexType =
  2267. op.SubscriptCardinality == 1
  2268. ? m_context->UnsignedIntTy
  2269. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2270. op.SubscriptCardinality);
  2271. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2272. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2273. ArrayRef<StringRef>(StringRef("index")),
  2274. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2275. hlsl::CreateFunctionTemplateDecl(
  2276. *m_context, recordDecl, functionDecl,
  2277. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2278. // Add a .mips member if necessary.
  2279. QualType uintType = m_context->UnsignedIntTy;
  2280. if (op.HasMips) {
  2281. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2282. templateTypeParmDecl, "mips_type",
  2283. "mips_slice_type", "mipSlice", uintType, "pos",
  2284. indexType);
  2285. }
  2286. // Add a .sample member if necessary.
  2287. if (op.HasSample) {
  2288. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2289. templateTypeParmDecl, "sample_type",
  2290. "sample_slice_type", "sampleSlice", uintType,
  2291. "pos", indexType);
  2292. // TODO: support operator[][](indexType, uint).
  2293. }
  2294. }
  2295. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2296. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2297. return a.first < b.first;
  2298. };
  2299. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2300. auto begin = m_objectTypeDeclsMap.begin();
  2301. auto end = m_objectTypeDeclsMap.end();
  2302. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2303. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2304. if (low == end)
  2305. return -1;
  2306. if (recordDecl == low->first)
  2307. return low->second;
  2308. else
  2309. return -1;
  2310. }
  2311. // Adds all built-in HLSL object types.
  2312. void AddObjectTypes()
  2313. {
  2314. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2315. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2316. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2317. m_objectTypeLazyInitMask = 0;
  2318. unsigned effectKindIndex = 0;
  2319. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2320. {
  2321. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2322. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2323. continue;
  2324. }
  2325. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2326. effectKindIndex = i;
  2327. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2328. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2329. const char* typeName = g_ArBasicTypeNames[kind];
  2330. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2331. CXXRecordDecl* recordDecl = nullptr;
  2332. if (templateArgCount == 0)
  2333. {
  2334. AddRecordTypeWithHandle(*m_context, &recordDecl, typeName);
  2335. DXASSERT(recordDecl != nullptr, "AddRecordTypeWithHandle failed to return the object declaration");
  2336. recordDecl->setImplicit(true);
  2337. }
  2338. else
  2339. {
  2340. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2341. ClassTemplateDecl* typeDecl = nullptr;
  2342. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2343. AddTemplateTypeWithHandle(*m_context, &typeDecl, &recordDecl, typeName, templateArgCount, typeDefault);
  2344. DXASSERT(typeDecl != nullptr, "AddTemplateTypeWithHandle failed to return the object declaration");
  2345. typeDecl->setImplicit(true);
  2346. recordDecl->setImplicit(true);
  2347. }
  2348. m_objectTypeDecls[i] = recordDecl;
  2349. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2350. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2351. }
  2352. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2353. {
  2354. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2355. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2356. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2357. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2358. currentDeclContext->addDecl(samplerDecl);
  2359. samplerDecl->setImplicit(true);
  2360. // Create decls for each deprecated effect object type:
  2361. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2362. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2363. for (int i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2364. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2365. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2366. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2367. currentDeclContext->addDecl(effectObjDecl);
  2368. effectObjDecl->setImplicit(true);
  2369. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2370. }
  2371. }
  2372. // Make sure it's in order.
  2373. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2374. }
  2375. FunctionDecl* AddSubscriptSpecialization(
  2376. _In_ FunctionTemplateDecl* functionTemplate,
  2377. QualType objectElement,
  2378. const FindStructBasicTypeResult& findResult);
  2379. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  2380. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2381. }
  2382. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  2383. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2384. }
  2385. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType);
  2386. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  2387. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2388. rowCount >= 0 && rowCount <= 4 && colCount >= 0 &&
  2389. colCount <= 4);
  2390. TypedefDecl *qts =
  2391. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  2392. if (qts == nullptr) {
  2393. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  2394. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  2395. rowCount, colCount);
  2396. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  2397. }
  2398. return qts;
  2399. }
  2400. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  2401. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2402. colCount >= 0 && colCount <= 4);
  2403. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  2404. if (qts == nullptr) {
  2405. QualType type = LookupVectorType(scalarType, colCount);
  2406. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  2407. colCount);
  2408. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  2409. }
  2410. return qts;
  2411. }
  2412. public:
  2413. HLSLExternalSource() :
  2414. m_context(nullptr),
  2415. m_sema(nullptr),
  2416. m_vectorTemplateDecl(nullptr),
  2417. m_matrixTemplateDecl(nullptr)
  2418. {
  2419. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  2420. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  2421. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  2422. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  2423. }
  2424. ~HLSLExternalSource() { }
  2425. static HLSLExternalSource* FromSema(_In_ Sema* self)
  2426. {
  2427. DXASSERT_NOMSG(self != nullptr);
  2428. ExternalSemaSource* externalSource = self->getExternalSource();
  2429. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  2430. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  2431. return hlsl;
  2432. }
  2433. void InitializeSema(Sema& S) override
  2434. {
  2435. m_sema = &S;
  2436. S.addExternalSource(this);
  2437. AddObjectTypes();
  2438. AddStdIsEqualImplementation(S.getASTContext(), S);
  2439. for (auto && intrinsic : m_intrinsicTables) {
  2440. AddIntrinsicTableMethods(intrinsic);
  2441. }
  2442. }
  2443. void ForgetSema() override
  2444. {
  2445. m_sema = nullptr;
  2446. }
  2447. Sema* getSema() {
  2448. return m_sema;
  2449. }
  2450. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  2451. {
  2452. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  2453. if (qt.isNull()) {
  2454. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  2455. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  2456. }
  2457. return qt;
  2458. }
  2459. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  2460. {
  2461. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  2462. if (qt.isNull()) {
  2463. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  2464. m_vectorTypes[scalarType][colCount - 1] = qt;
  2465. }
  2466. return qt;
  2467. }
  2468. bool LookupUnqualified(LookupResult &R, Scope *S) override
  2469. {
  2470. const DeclarationNameInfo declName = R.getLookupNameInfo();
  2471. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  2472. if (idInfo == nullptr) {
  2473. return false;
  2474. }
  2475. StringRef nameIdentifier = idInfo->getName();
  2476. HLSLScalarType parsedType;
  2477. int rowCount;
  2478. int colCount;
  2479. if (TryParseMatrixShorthand(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount)) {
  2480. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseMatrixShorthand should not have succeeded");
  2481. QualType qt = LookupMatrixType(parsedType, rowCount, colCount);
  2482. if (parsedType == HLSLScalarType_int_min12)
  2483. m_sema->Diag(R.getNameLoc(), diag::warn_hlsl_sema_minprecision_promotion) << "min12int" << "min16int";
  2484. else if (parsedType == HLSLScalarType_float_min10)
  2485. m_sema->Diag(R.getNameLoc(), diag::warn_hlsl_sema_minprecision_promotion) << "min10float" << "min16float";
  2486. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  2487. R.addDecl(qts);
  2488. return true;
  2489. } else if (TryParseVectorShorthand(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &colCount)) {
  2490. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseVectorShorthand should not have succeeded");
  2491. QualType qt = LookupVectorType(parsedType, colCount);
  2492. if (parsedType == HLSLScalarType_int_min12)
  2493. m_sema->Diag(R.getNameLoc(), diag::warn_hlsl_sema_minprecision_promotion) << "min12int" << "min16int";
  2494. else if (parsedType == HLSLScalarType_float_min10)
  2495. m_sema->Diag(R.getNameLoc(), diag::warn_hlsl_sema_minprecision_promotion) << "min10float" << "min16float";
  2496. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  2497. R.addDecl(qts);
  2498. return true;
  2499. }
  2500. return false;
  2501. }
  2502. /// <summary>
  2503. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  2504. /// </sumary>
  2505. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  2506. {
  2507. DXASSERT_NOMSG(type != nullptr);
  2508. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2509. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2510. if (templateSpecializationDecl) {
  2511. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  2512. if (decl == m_matrixTemplateDecl)
  2513. return AR_TOBJ_MATRIX;
  2514. else if (decl == m_vectorTemplateDecl)
  2515. return AR_TOBJ_VECTOR;
  2516. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  2517. return AR_TOBJ_OBJECT;
  2518. }
  2519. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2520. if (typeRecordDecl->getDeclContext()->isFileContext())
  2521. return AR_TOBJ_OBJECT;
  2522. else
  2523. return AR_TOBJ_INNER_OBJ;
  2524. }
  2525. return AR_TOBJ_COMPOUND;
  2526. }
  2527. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  2528. bool IsBuiltInObjectType(QualType type)
  2529. {
  2530. type = GetStructuralForm(type);
  2531. if (!type.isNull() && type->isStructureOrClassType()) {
  2532. const RecordType* recordType = type->getAs<RecordType>();
  2533. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  2534. }
  2535. return false;
  2536. }
  2537. /// <summary>
  2538. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  2539. /// possibly refering to original template record if it's a specialization; this makes the result
  2540. /// suitable for looking up in initialization tables.
  2541. /// </summary>
  2542. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  2543. {
  2544. const CXXRecordDecl* recordDecl;
  2545. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  2546. {
  2547. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  2548. }
  2549. else
  2550. {
  2551. recordDecl = dyn_cast<CXXRecordDecl>(context);
  2552. }
  2553. return recordDecl;
  2554. }
  2555. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  2556. ArTypeObjectKind GetTypeObjectKind(QualType type)
  2557. {
  2558. DXASSERT_NOMSG(!type.isNull());
  2559. type = GetStructuralForm(type);
  2560. if (type->isVoidType()) return AR_TOBJ_VOID;
  2561. if (type->isArrayType()) return AR_TOBJ_ARRAY;
  2562. if (type->isPointerType()) {
  2563. return AR_TOBJ_POINTER;
  2564. }
  2565. if (type->isStructureOrClassType()) {
  2566. const RecordType* recordType = type->getAs<RecordType>();
  2567. return ClassifyRecordType(recordType);
  2568. } else if (const InjectedClassNameType *ClassNameTy =
  2569. type->getAs<InjectedClassNameType>()) {
  2570. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  2571. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  2572. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2573. if (templateSpecializationDecl) {
  2574. ClassTemplateDecl *decl =
  2575. templateSpecializationDecl->getSpecializedTemplate();
  2576. if (decl == m_matrixTemplateDecl)
  2577. return AR_TOBJ_MATRIX;
  2578. else if (decl == m_vectorTemplateDecl)
  2579. return AR_TOBJ_VECTOR;
  2580. DXASSERT(decl->isImplicit(),
  2581. "otherwise object template decl is not set to implicit");
  2582. return AR_TOBJ_OBJECT;
  2583. }
  2584. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2585. if (typeRecordDecl->getDeclContext()->isFileContext())
  2586. return AR_TOBJ_OBJECT;
  2587. else
  2588. return AR_TOBJ_INNER_OBJ;
  2589. }
  2590. return AR_TOBJ_COMPOUND;
  2591. }
  2592. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  2593. return AR_TOBJ_INVALID;
  2594. }
  2595. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  2596. QualType GetMatrixOrVectorElementType(QualType type)
  2597. {
  2598. type = GetStructuralForm(type);
  2599. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2600. DXASSERT_NOMSG(typeRecordDecl);
  2601. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2602. DXASSERT_NOMSG(templateSpecializationDecl);
  2603. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  2604. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  2605. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  2606. }
  2607. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  2608. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  2609. QualType GetStructuralForm(QualType type)
  2610. {
  2611. if (type.isNull()) {
  2612. return type;
  2613. }
  2614. const ReferenceType *RefType = nullptr;
  2615. const AttributedType *AttrType = nullptr;
  2616. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  2617. (AttrType = dyn_cast<AttributedType>(type)))
  2618. {
  2619. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  2620. }
  2621. return type->getCanonicalTypeUnqualified();
  2622. }
  2623. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  2624. ArBasicKind GetTypeElementKind(QualType type)
  2625. {
  2626. type = GetStructuralForm(type);
  2627. ArTypeObjectKind kind = GetTypeObjectKind(type);
  2628. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  2629. QualType elementType = GetMatrixOrVectorElementType(type);
  2630. return GetTypeElementKind(elementType);
  2631. }
  2632. if (type->isArrayType()) {
  2633. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  2634. return GetTypeElementKind(arrayType->getElementType());
  2635. }
  2636. if (kind == AR_TOBJ_INNER_OBJ) {
  2637. return AR_OBJECT_INNER;
  2638. } else if (kind == AR_TOBJ_OBJECT) {
  2639. // Classify the object as the element type.
  2640. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  2641. int index = FindObjectBasicKindIndex(typeRecordDecl);
  2642. // NOTE: this will likely need to be updated for specialized records
  2643. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  2644. return g_ArBasicKindsAsTypes[index];
  2645. }
  2646. CanQualType canType = type->getCanonicalTypeUnqualified();
  2647. return BasicTypeForScalarType(canType);
  2648. }
  2649. ArBasicKind BasicTypeForScalarType(CanQualType type)
  2650. {
  2651. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  2652. {
  2653. switch (BT->getKind())
  2654. {
  2655. case BuiltinType::Bool: return AR_BASIC_BOOL;
  2656. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  2657. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  2658. case BuiltinType::Half: return AR_BASIC_MIN16FLOAT; // rather than AR_BASIC_FLOAT16
  2659. case BuiltinType::Int: return AR_BASIC_INT32;
  2660. case BuiltinType::UInt: return AR_BASIC_UINT32;
  2661. case BuiltinType::Short: return AR_BASIC_MIN16INT; // rather than AR_BASIC_INT16
  2662. case BuiltinType::UShort: return AR_BASIC_MIN16UINT; // rather than AR_BASIC_UINT16
  2663. case BuiltinType::LongLong: return AR_BASIC_INT64;
  2664. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  2665. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  2666. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  2667. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  2668. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  2669. }
  2670. }
  2671. return AR_BASIC_UNKNOWN;
  2672. }
  2673. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  2674. DXASSERT_NOMSG(table != nullptr);
  2675. // Function intrinsics are added on-demand, objects get template methods.
  2676. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  2677. // Grab information already processed by AddObjectTypes.
  2678. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2679. const char *typeName = g_ArBasicTypeNames[kind];
  2680. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2681. DXASSERT(0 <= templateArgCount && templateArgCount <= 2,
  2682. "otherwise a new case has been added");
  2683. int startDepth = (templateArgCount == 0) ? 0 : 1;
  2684. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  2685. if (recordDecl == nullptr) {
  2686. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  2687. continue;
  2688. }
  2689. // This is a variation of AddObjectMethods using the new table.
  2690. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  2691. const HLSL_INTRINSIC *pPrior = nullptr;
  2692. UINT64 lookupCookie = 0;
  2693. CA2W wideTypeName(typeName);
  2694. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  2695. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  2696. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  2697. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  2698. // NOTE: this only works with the current implementation because
  2699. // intrinsics are alive as long as the table is alive.
  2700. pPrior = pIntrinsic;
  2701. }
  2702. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  2703. }
  2704. }
  2705. }
  2706. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  2707. DXASSERT_NOMSG(table != nullptr);
  2708. m_intrinsicTables.push_back(table);
  2709. // If already initialized, add methods immediately.
  2710. if (m_sema != nullptr) {
  2711. AddIntrinsicTableMethods(table);
  2712. }
  2713. }
  2714. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  2715. {
  2716. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  2717. switch (kind) {
  2718. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  2719. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  2720. case AR_BASIC_FLOAT16: return HLSLScalarType_float_min16;
  2721. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  2722. return HLSLScalarType_float;
  2723. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  2724. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  2725. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  2726. case AR_BASIC_INT8: return HLSLScalarType_int;
  2727. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  2728. case AR_BASIC_INT16: return HLSLScalarType_uint;
  2729. case AR_BASIC_UINT16: return HLSLScalarType_uint;
  2730. case AR_BASIC_INT32: return HLSLScalarType_int;
  2731. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  2732. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  2733. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  2734. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  2735. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  2736. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  2737. case AR_BASIC_INT64: return HLSLScalarType_int64;
  2738. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  2739. default:
  2740. return HLSLScalarType_unknown;
  2741. }
  2742. }
  2743. QualType GetBasicKindType(ArBasicKind kind)
  2744. {
  2745. DXASSERT_VALIDBASICKIND(kind);
  2746. switch (kind) {
  2747. case AR_OBJECT_NULL: return m_context->VoidTy;
  2748. case AR_BASIC_BOOL: return m_context->BoolTy;
  2749. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  2750. case AR_BASIC_FLOAT16: return m_context->FloatTy;
  2751. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->FloatTy;
  2752. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  2753. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  2754. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  2755. case AR_BASIC_INT8: return m_context->IntTy;
  2756. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  2757. case AR_BASIC_INT16: return m_context->IntTy;
  2758. case AR_BASIC_UINT16: return m_context->UnsignedIntTy;
  2759. case AR_BASIC_INT32: return m_context->IntTy;
  2760. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  2761. case AR_BASIC_INT64: return m_context->LongLongTy;
  2762. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  2763. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  2764. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  2765. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  2766. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  2767. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  2768. case AR_OBJECT_STRING: return QualType();
  2769. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  2770. case AR_OBJECT_TEXTURE1D:
  2771. case AR_OBJECT_TEXTURE1D_ARRAY:
  2772. case AR_OBJECT_TEXTURE2D:
  2773. case AR_OBJECT_TEXTURE2D_ARRAY:
  2774. case AR_OBJECT_TEXTURE3D:
  2775. case AR_OBJECT_TEXTURECUBE:
  2776. case AR_OBJECT_TEXTURECUBE_ARRAY:
  2777. case AR_OBJECT_TEXTURE2DMS:
  2778. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  2779. case AR_OBJECT_SAMPLER:
  2780. case AR_OBJECT_SAMPLERCOMPARISON:
  2781. case AR_OBJECT_BUFFER:
  2782. case AR_OBJECT_POINTSTREAM:
  2783. case AR_OBJECT_LINESTREAM:
  2784. case AR_OBJECT_TRIANGLESTREAM:
  2785. case AR_OBJECT_INPUTPATCH:
  2786. case AR_OBJECT_OUTPUTPATCH:
  2787. case AR_OBJECT_RWTEXTURE1D:
  2788. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  2789. case AR_OBJECT_RWTEXTURE2D:
  2790. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  2791. case AR_OBJECT_RWTEXTURE3D:
  2792. case AR_OBJECT_RWBUFFER:
  2793. case AR_OBJECT_BYTEADDRESS_BUFFER:
  2794. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  2795. case AR_OBJECT_STRUCTURED_BUFFER:
  2796. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  2797. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  2798. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  2799. case AR_OBJECT_WAVE:
  2800. {
  2801. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  2802. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  2803. size_t index = match - g_ArBasicKindsAsTypes;
  2804. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  2805. }
  2806. case AR_OBJECT_SAMPLER1D:
  2807. case AR_OBJECT_SAMPLER2D:
  2808. case AR_OBJECT_SAMPLER3D:
  2809. case AR_OBJECT_SAMPLERCUBE:
  2810. // Turn dimension-typed samplers into sampler states.
  2811. return GetBasicKindType(AR_OBJECT_SAMPLER);
  2812. case AR_OBJECT_STATEBLOCK:
  2813. case AR_OBJECT_RASTERIZER:
  2814. case AR_OBJECT_DEPTHSTENCIL:
  2815. case AR_OBJECT_BLEND:
  2816. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  2817. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  2818. default:
  2819. return QualType();
  2820. }
  2821. }
  2822. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  2823. /// <param name="E">Expression to typecast.</param>
  2824. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  2825. ExprResult PromoteToIntIfBool(ExprResult& E);
  2826. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  2827. {
  2828. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  2829. (qwUsages);
  2830. return type;
  2831. }
  2832. QualType NewSimpleAggregateType(
  2833. _In_ ArTypeObjectKind ExplicitKind,
  2834. _In_ ArBasicKind componentType,
  2835. _In_ UINT64 qwQual,
  2836. _In_ UINT uRows,
  2837. _In_ UINT uCols)
  2838. {
  2839. DXASSERT_VALIDBASICKIND(componentType);
  2840. QualType pType; // The type to return.
  2841. QualType pEltType = GetBasicKindType(componentType);
  2842. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  2843. // TODO: handle adding qualifications like const
  2844. pType = NewQualifiedType(
  2845. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  2846. pEltType);
  2847. if (uRows > 1 ||
  2848. uCols > 1 ||
  2849. ExplicitKind == AR_TOBJ_VECTOR ||
  2850. ExplicitKind == AR_TOBJ_MATRIX)
  2851. {
  2852. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  2853. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  2854. if ((uRows == 1 &&
  2855. ExplicitKind != AR_TOBJ_MATRIX) ||
  2856. ExplicitKind == AR_TOBJ_VECTOR)
  2857. {
  2858. pType = LookupVectorType(scalarType, uCols);
  2859. }
  2860. else
  2861. {
  2862. pType = LookupMatrixType(scalarType, uRows, uCols);
  2863. }
  2864. // TODO: handle colmajor/rowmajor
  2865. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  2866. //{
  2867. // VN(pType = NewQualifiedType(pSrcLoc,
  2868. // qwQual & (AR_QUAL_COLMAJOR |
  2869. // AR_QUAL_ROWMAJOR),
  2870. // pMatrix));
  2871. //}
  2872. //else
  2873. //{
  2874. // pType = pMatrix;
  2875. //}
  2876. }
  2877. return pType;
  2878. }
  2879. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  2880. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  2881. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  2882. /// <param name="Args">Invocation arguments to match.</param>
  2883. /// <param name="argTypes">After exectuion, type of arguments.</param>
  2884. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  2885. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  2886. bool MatchArguments(
  2887. _In_ const HLSL_INTRINSIC *pIntrinsic,
  2888. _In_ QualType objectElement,
  2889. _In_ ArrayRef<Expr *> Args,
  2890. _Out_writes_(g_MaxIntrinsicParamCount + 1) QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  2891. _Out_range_(0, g_MaxIntrinsicParamCount + 1) size_t* argCount);
  2892. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  2893. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  2894. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  2895. bool IsValidateObjectElement(
  2896. _In_ const HLSL_INTRINSIC *pIntrinsic,
  2897. _In_ QualType objectElement);
  2898. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  2899. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  2900. size_t tableSize,
  2901. StringRef typeName,
  2902. StringRef nameIdentifier,
  2903. size_t argumentCount)
  2904. {
  2905. // TODO: avoid linear scan
  2906. for (unsigned int i = 0; i < tableSize; i++) {
  2907. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  2908. // Do some quick checks to verify size and name.
  2909. if (pIntrinsic->uNumArgs != 1 + argumentCount) {
  2910. continue;
  2911. }
  2912. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  2913. continue;
  2914. }
  2915. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  2916. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  2917. }
  2918. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  2919. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  2920. }
  2921. bool AddOverloadedCallCandidates(
  2922. UnresolvedLookupExpr *ULE,
  2923. ArrayRef<Expr *> Args,
  2924. OverloadCandidateSet &CandidateSet,
  2925. bool PartialOverloading) override
  2926. {
  2927. DXASSERT_NOMSG(ULE != nullptr);
  2928. const DeclarationNameInfo declName = ULE->getNameInfo();
  2929. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  2930. if (idInfo == nullptr)
  2931. {
  2932. return false;
  2933. }
  2934. StringRef nameIdentifier = idInfo->getName();
  2935. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  2936. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  2937. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  2938. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  2939. while (cursor != end)
  2940. {
  2941. // If this is the intrinsic we're interested in, build up a representation
  2942. // of the types we need.
  2943. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  2944. LPCSTR tableName = cursor.GetTableName();
  2945. LPCSTR lowering = cursor.GetLoweringStrategy();
  2946. DXASSERT(
  2947. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  2948. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  2949. QualType functionArgTypes[g_MaxIntrinsicParamCount + 1];
  2950. size_t functionArgTypeCount = 0;
  2951. if (!MatchArguments(pIntrinsic, QualType(), Args, functionArgTypes, &functionArgTypeCount))
  2952. {
  2953. ++cursor;
  2954. continue;
  2955. }
  2956. // Get or create the overload we're interested in.
  2957. FunctionDecl* intrinsicFuncDecl = nullptr;
  2958. std::pair<UsedIntrinsicStore::iterator, bool> insertResult = m_usedIntrinsics.insert(UsedIntrinsic(
  2959. pIntrinsic, functionArgTypes, functionArgTypeCount));
  2960. bool insertedNewValue = insertResult.second;
  2961. if (insertedNewValue)
  2962. {
  2963. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  2964. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, functionArgTypes, functionArgTypeCount);
  2965. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  2966. }
  2967. else
  2968. {
  2969. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  2970. }
  2971. OverloadCandidate& candidate = CandidateSet.addCandidate();
  2972. candidate.Function = intrinsicFuncDecl;
  2973. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  2974. candidate.Viable = true;
  2975. return true;
  2976. }
  2977. return false;
  2978. }
  2979. bool Initialize(ASTContext& context)
  2980. {
  2981. m_context = &context;
  2982. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  2983. /*Inline*/ false, SourceLocation(),
  2984. SourceLocation(), &context.Idents.get("hlsl"),
  2985. /*PrevDecl*/ nullptr);
  2986. m_hlslNSDecl->setImplicit();
  2987. AddHLSLScalarTypes();
  2988. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  2989. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  2990. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  2991. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  2992. return true;
  2993. }
  2994. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  2995. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  2996. /// <summary>Checks whether the specified type is a scalar type.</summary>
  2997. bool IsScalarType(const QualType& type) {
  2998. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  2999. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3000. }
  3001. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3002. bool IsValidVectorSize(size_t length) {
  3003. return 1 <= length && length <= 4;
  3004. }
  3005. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3006. bool IsValidMatrixColOrRowSize(size_t length) {
  3007. return 1 <= length && length <= 4;
  3008. }
  3009. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3010. if (type.isNull()) {
  3011. return false;
  3012. }
  3013. if (type.hasQualifiers()) {
  3014. return false;
  3015. }
  3016. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3017. if (type->getTypeClass() == Type::TemplateTypeParm)
  3018. return true;
  3019. QualType qt = GetStructuralForm(type);
  3020. if (requireScalar) {
  3021. if (!IsScalarType(qt)) {
  3022. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3023. return false;
  3024. }
  3025. return true;
  3026. }
  3027. else {
  3028. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3029. if (qt->isArrayType()) {
  3030. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3031. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3032. }
  3033. else if (objectKind == AR_TOBJ_VECTOR) {
  3034. bool valid = true;
  3035. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3036. valid = false;
  3037. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3038. }
  3039. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3040. valid = false;
  3041. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3042. }
  3043. return valid;
  3044. }
  3045. else if (objectKind == AR_TOBJ_MATRIX) {
  3046. bool valid = true;
  3047. UINT rowCount, colCount;
  3048. GetRowsAndCols(type, rowCount, colCount);
  3049. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3050. valid = false;
  3051. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3052. }
  3053. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3054. valid = false;
  3055. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3056. }
  3057. return valid;
  3058. }
  3059. else if (qt->isStructureType()) {
  3060. const RecordType* recordType = qt->getAsStructureType();
  3061. objectKind = ClassifyRecordType(recordType);
  3062. switch (objectKind)
  3063. {
  3064. case AR_TOBJ_OBJECT:
  3065. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3066. return false;
  3067. case AR_TOBJ_COMPOUND:
  3068. {
  3069. const RecordDecl* recordDecl = recordType->getDecl();
  3070. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3071. RecordDecl::field_iterator end = recordDecl->field_end();
  3072. bool result = true;
  3073. while (begin != end) {
  3074. const FieldDecl* fieldDecl = *begin;
  3075. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3076. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3077. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3078. result = false;
  3079. }
  3080. begin++;
  3081. }
  3082. return result;
  3083. }
  3084. default:
  3085. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3086. return false;
  3087. }
  3088. }
  3089. else if(IsScalarType(qt)) {
  3090. return true;
  3091. }
  3092. else {
  3093. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3094. return false;
  3095. }
  3096. }
  3097. }
  3098. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3099. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3100. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3101. _Inout_opt_ StandardConversionSequence* sequence);
  3102. /// <summary>Produces an expression that turns the given expression into the specified numeric type.</summary>
  3103. Expr* CastExprToTypeNumeric(Expr* expr, QualType targetType);
  3104. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3105. void GetConversionForm(
  3106. QualType type,
  3107. bool explicitConversion,
  3108. ArTypeInfo* pTypeInfo);
  3109. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3110. bool suppressWarnings, bool suppressErrors,
  3111. _Inout_opt_ StandardConversionSequence* sequence);
  3112. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3113. bool ValidateTypeRequirements(
  3114. SourceLocation loc,
  3115. ArBasicKind elementKind,
  3116. ArTypeObjectKind objectKind,
  3117. bool requiresIntegrals,
  3118. bool requiresNumerics);
  3119. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3120. /// <param name="OpLoc">Source location for operator.</param>
  3121. /// <param name="Opc">Kind of binary operator.</param>
  3122. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3123. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3124. /// <param name="ResultTy">Result type for operator expression.</param>
  3125. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3126. /// <param name="CompResultTy">Type of computation result.</param>
  3127. void CheckBinOpForHLSL(
  3128. SourceLocation OpLoc,
  3129. BinaryOperatorKind Opc,
  3130. ExprResult& LHS,
  3131. ExprResult& RHS,
  3132. QualType& ResultTy,
  3133. QualType& CompLHSTy,
  3134. QualType& CompResultTy);
  3135. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3136. /// <param name="OpLoc">Source location for operator.</param>
  3137. /// <param name="Opc">Kind of operator.</param>
  3138. /// <param name="InputExpr">Input expression to the operator.</param>
  3139. /// <param name="VK">Value kind for resulting expression.</param>
  3140. /// <param name="OK">Object kind for resulting expression.</param>
  3141. /// <returns>The result type for the expression.</returns>
  3142. QualType CheckUnaryOpForHLSL(
  3143. SourceLocation OpLoc,
  3144. UnaryOperatorKind Opc,
  3145. ExprResult& InputExpr,
  3146. ExprValueKind& VK,
  3147. ExprObjectKind& OK);
  3148. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3149. /// <param name="Cond">Vector condition expression.</param>
  3150. /// <param name="LHS">Left hand side.</param>
  3151. /// <param name="RHS">Right hand side.</param>
  3152. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3153. /// <returns>Result type of vector conditional expression.</returns>
  3154. clang::QualType HLSLExternalSource::CheckVectorConditional(
  3155. _In_ ExprResult &Cond,
  3156. _In_ ExprResult &LHS,
  3157. _In_ ExprResult &RHS,
  3158. _In_ SourceLocation QuestionLoc);
  3159. clang::QualType ApplyTypeSpecSignToParsedType(
  3160. _In_ clang::QualType &type,
  3161. _In_ TypeSpecifierSign TSS,
  3162. _In_ SourceLocation Loc
  3163. );
  3164. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3165. {
  3166. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3167. {
  3168. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3169. return true;
  3170. }
  3171. return false;
  3172. }
  3173. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3174. bool
  3175. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3176. SourceLocation /* TemplateLoc */,
  3177. TemplateArgumentListInfo &TemplateArgList) {
  3178. DXASSERT_NOMSG(Template != nullptr);
  3179. // Determine which object type the template refers to.
  3180. StringRef templateName = Template->getName();
  3181. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3182. if (templateName.equals(StringRef("is_same"))) {
  3183. return false;
  3184. }
  3185. bool isMatrix = Template->getCanonicalDecl() ==
  3186. m_matrixTemplateDecl->getCanonicalDecl();
  3187. bool isVector = Template->getCanonicalDecl() ==
  3188. m_vectorTemplateDecl->getCanonicalDecl();
  3189. bool requireScalar = isMatrix || isVector;
  3190. // Check constraints on the type. Right now we only check that template
  3191. // types are primitive types.
  3192. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3193. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3194. SourceLocation argSrcLoc = argLoc.getLocation();
  3195. const TemplateArgument &arg = argLoc.getArgument();
  3196. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3197. QualType argType = arg.getAsType();
  3198. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3199. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3200. return true;
  3201. }
  3202. }
  3203. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  3204. if (isMatrix || isVector) {
  3205. Expr *expr = arg.getAsExpr();
  3206. llvm::APSInt constantResult;
  3207. if (expr != nullptr &&
  3208. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  3209. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  3210. return true;
  3211. }
  3212. }
  3213. }
  3214. }
  3215. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  3216. if (isMatrix || isVector) {
  3217. llvm::APSInt Val = arg.getAsIntegral();
  3218. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  3219. return true;
  3220. }
  3221. }
  3222. }
  3223. }
  3224. return false;
  3225. }
  3226. /// <summary>Diagnoses an assignment operation.</summary>
  3227. /// <param name="ConvTy">Type of conversion assignment.</param>
  3228. /// <param name="Loc">Location for operation.</param>
  3229. /// <param name="DstType">Destination type.</param>
  3230. /// <param name="SrcType">Source type.</param>
  3231. /// <param name="SrcExpr">Source expression.</param>
  3232. /// <param name="Action">Action that triggers the assignment (assignment, passing, return, etc).</param>
  3233. /// <param name="Complained">Whether a diagnostic was emitted.</param>
  3234. void DiagnoseAssignmentResultForHLSL(
  3235. Sema::AssignConvertType ConvTy,
  3236. SourceLocation Loc,
  3237. QualType DstType, QualType SrcType,
  3238. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  3239. _Out_opt_ bool *Complained);
  3240. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  3241. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  3242. /// <param name="functionDeclContext">Declaration context of function.</param>
  3243. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  3244. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  3245. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  3246. void FindIntrinsicTable(
  3247. _In_ DeclContext* functionDeclContext,
  3248. _Outptr_result_z_ const char** name,
  3249. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  3250. _Out_ size_t* intrinsicCount);
  3251. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  3252. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  3253. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  3254. /// <param name="Args">Array of expressions being used as arguments.</param>
  3255. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  3256. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  3257. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  3258. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  3259. FunctionTemplateDecl *FunctionTemplate,
  3260. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3261. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  3262. clang::OverloadingResult GetBestViableFunction(
  3263. clang::SourceLocation Loc,
  3264. clang::OverloadCandidateSet& set,
  3265. clang::OverloadCandidateSet::iterator& Best);
  3266. /// <summary>
  3267. /// Initializes the specified <paramref name="initSequence" /> describing how
  3268. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  3269. /// </summary>
  3270. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  3271. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  3272. /// <param name="Args">Arguments to the initialization.</param>
  3273. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  3274. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  3275. void InitializeInitSequenceForHLSL(
  3276. const InitializedEntity& Entity,
  3277. const InitializationKind& Kind,
  3278. MultiExprArg Args,
  3279. bool TopLevelOfInitList,
  3280. _Inout_ InitializationSequence* initSequence);
  3281. /// <summary>
  3282. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3283. /// </summary>
  3284. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3285. bool IsConversionToLessOrEqualElements(
  3286. const ExprResult& sourceExpr,
  3287. const QualType& targetType,
  3288. bool explicitConversion);
  3289. /// <summary>
  3290. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3291. /// </summary>
  3292. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3293. bool IsConversionToLessOrEqualElements(
  3294. const QualType& sourceType,
  3295. const QualType& targetType,
  3296. bool explicitConversion);
  3297. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  3298. /// <param name="BaseExpr">Base expression for member access.</param>
  3299. /// <param name="MemberName">Name of member to look up.</param>
  3300. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3301. /// <param name="OpLoc">Location of access operand.</param>
  3302. /// <param name="MemberLoc">Location of member.</param>
  3303. /// <param name="result">Result of lookup operation.</param>
  3304. /// <returns>true if the base type is a matrix and the lookup has been handled.</returns>
  3305. bool LookupMatrixMemberExprForHLSL(
  3306. Expr& BaseExpr,
  3307. DeclarationName MemberName,
  3308. bool IsArrow,
  3309. SourceLocation OpLoc,
  3310. SourceLocation MemberLoc,
  3311. ExprResult* result);
  3312. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  3313. /// <param name="BaseExpr">Base expression for member access.</param>
  3314. /// <param name="MemberName">Name of member to look up.</param>
  3315. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3316. /// <param name="OpLoc">Location of access operand.</param>
  3317. /// <param name="MemberLoc">Location of member.</param>
  3318. /// <param name="result">Result of lookup operation.</param>
  3319. /// <returns>true if the base type is a vector and the lookup has been handled.</returns>
  3320. bool LookupVectorMemberExprForHLSL(
  3321. Expr& BaseExpr,
  3322. DeclarationName MemberName,
  3323. bool IsArrow,
  3324. SourceLocation OpLoc,
  3325. SourceLocation MemberLoc,
  3326. ExprResult* result);
  3327. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  3328. /// <param name="E">Expression to convert.</param>
  3329. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  3330. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  3331. clang::Expr *HLSLImpCastToScalar(
  3332. _In_ clang::Sema* self,
  3333. _In_ clang::Expr* From,
  3334. ArTypeObjectKind FromShape,
  3335. ArBasicKind EltKind);
  3336. clang::ExprResult PerformHLSLConversion(
  3337. _In_ clang::Expr* From,
  3338. _In_ clang::QualType targetType,
  3339. _In_ const clang::StandardConversionSequence &SCS,
  3340. _In_ clang::Sema::CheckedConversionKind CCK);
  3341. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  3342. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  3343. /// <summary>
  3344. /// Checks if a static cast can be performed, and performs it if possible.
  3345. /// </summary>
  3346. /// <param name="SrcExpr">Expression to cast.</param>
  3347. /// <param name="DestType">Type to cast SrcExpr to.</param>
  3348. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  3349. /// <param name="OpRange">Source range for the cast operation.</param>
  3350. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  3351. /// <param name="Kind">The kind of operation required for a conversion.</param>
  3352. /// <param name="BasePath">A simple array of base specifiers.</param>
  3353. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  3354. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  3355. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  3356. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  3357. QualType DestType,
  3358. Sema::CheckedConversionKind CCK,
  3359. const SourceRange &OpRange, unsigned &msg,
  3360. CastKind &Kind, CXXCastPath &BasePath,
  3361. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  3362. _Inout_opt_ StandardConversionSequence* standard);
  3363. /// <summary>
  3364. /// Checks if a subscript index argument can be initialized from the given expression.
  3365. /// </summary>
  3366. /// <param name="SrcExpr">Source expression used as argument.</param>
  3367. /// <param name="DestType">Parameter type to initialize.</param>
  3368. /// <remarks>
  3369. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  3370. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  3371. /// </remarks>
  3372. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  3373. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  3374. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  3375. // Everything is ready.
  3376. if (m_objectTypeLazyInitMask == 0)
  3377. return;
  3378. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  3379. int idx = FindObjectBasicKindIndex(recordDecl);
  3380. // Not object type.
  3381. if (idx == -1)
  3382. return;
  3383. uint64_t bit = ((uint64_t)1)<<idx;
  3384. // Already created.
  3385. if ((m_objectTypeLazyInitMask & bit) == 0)
  3386. return;
  3387. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  3388. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  3389. int startDepth = 0;
  3390. if (templateArgCount > 0) {
  3391. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  3392. "otherwise a new case has been added");
  3393. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  3394. AddObjectSubscripts(kind, typeDecl, recordDecl,
  3395. g_ArBasicKindsSubscripts[idx]);
  3396. startDepth = 1;
  3397. }
  3398. AddObjectMethods(kind, recordDecl, startDepth);
  3399. // Clear the object.
  3400. m_objectTypeLazyInitMask &= ~bit;
  3401. }
  3402. FunctionDecl* AddHLSLIntrinsicMethod(
  3403. LPCSTR tableName,
  3404. LPCSTR lowering,
  3405. _In_ const HLSL_INTRINSIC* intrinsic,
  3406. _In_ FunctionTemplateDecl *FunctionTemplate,
  3407. ArrayRef<Expr *> Args,
  3408. _In_count_(parameterTypeCount) QualType* parameterTypes,
  3409. size_t parameterTypeCount)
  3410. {
  3411. DXASSERT_NOMSG(intrinsic != nullptr);
  3412. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  3413. DXASSERT_NOMSG(parameterTypes != nullptr);
  3414. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  3415. // Create the template arguments.
  3416. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  3417. for (size_t i = 0; i < parameterTypeCount; i++) {
  3418. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  3419. }
  3420. // Look for an existing specialization.
  3421. void *InsertPos = nullptr;
  3422. FunctionDecl *SpecFunc =
  3423. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  3424. if (SpecFunc != nullptr) {
  3425. return SpecFunc;
  3426. }
  3427. // Change return type to rvalue reference type for aggregate types
  3428. QualType retTy = parameterTypes[0];
  3429. if (retTy->isAggregateType() && !IsHLSLVecMatType(retTy))
  3430. parameterTypes[0] = m_context->getRValueReferenceType(retTy);
  3431. // Create a new specialization.
  3432. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  3433. InitParamMods(intrinsic, paramMods);
  3434. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3435. // Change out/inout parameter type to rvalue reference type.
  3436. if (paramMods[i - 1].isAnyOut()) {
  3437. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  3438. }
  3439. }
  3440. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  3441. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  3442. // Remove this when update intrinsic table not affect other things.
  3443. // Change vector<float,1> into float for bias.
  3444. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  3445. DXASSERT(parameterTypeCount > biasOperandID,
  3446. "else operation was misrecognized");
  3447. if (const ExtVectorType *VecTy =
  3448. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  3449. *m_context, parameterTypes[biasOperandID])) {
  3450. if (VecTy->getNumElements() == 1)
  3451. parameterTypes[biasOperandID] = VecTy->getElementType();
  3452. }
  3453. }
  3454. DeclContext *owner = FunctionTemplate->getDeclContext();
  3455. TemplateArgumentList templateArgumentList(
  3456. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  3457. templateArgs.size());
  3458. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  3459. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  3460. mlTemplateArgumentList);
  3461. FunctionProtoType::ExtProtoInfo EmptyEPI;
  3462. QualType functionType = m_context->getFunctionType(
  3463. parameterTypes[0],
  3464. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  3465. EmptyEPI, paramMods);
  3466. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  3467. FunctionProtoTypeLoc Proto =
  3468. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  3469. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  3470. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3471. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  3472. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  3473. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  3474. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  3475. Params.push_back(paramDecl);
  3476. }
  3477. QualType T = TInfo->getType();
  3478. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  3479. CXXMethodDecl* method = CXXMethodDecl::Create(
  3480. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  3481. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  3482. // Add intrinsic attr
  3483. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  3484. // Record this function template specialization.
  3485. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  3486. *m_context, templateArgs.data(), templateArgs.size());
  3487. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  3488. // Attach the parameters
  3489. for (unsigned P = 0; P < Params.size(); ++P) {
  3490. Params[P]->setOwningFunction(method);
  3491. Proto.setParam(P, Params[P]);
  3492. }
  3493. method->setParams(Params);
  3494. // Adjust access.
  3495. method->setAccess(AccessSpecifier::AS_public);
  3496. FunctionTemplate->setAccess(method->getAccess());
  3497. return method;
  3498. }
  3499. // Overload support.
  3500. UINT64 ScoreCast(QualType leftType, QualType rightType);
  3501. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  3502. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  3503. unsigned GetNumElements(QualType anyType);
  3504. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  3505. QualType GetNthElementType(QualType type, unsigned index);
  3506. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  3507. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3508. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3509. };
  3510. // Use this class to flatten a type into HLSL primitives and iterate through them.
  3511. class FlattenedTypeIterator
  3512. {
  3513. private:
  3514. enum FlattenedIterKind {
  3515. FK_Simple,
  3516. FK_Fields,
  3517. FK_Expressions,
  3518. FK_IncompleteArray
  3519. };
  3520. // Use this struct to represent a specific point in the tracked tree.
  3521. struct FlattenedTypeTracker {
  3522. QualType Type; // Type at this position in the tree.
  3523. unsigned int Count; // Count of consecutive types
  3524. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  3525. RecordDecl::field_iterator EndField; // STL-style end of fields.
  3526. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  3527. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  3528. FlattenedIterKind IterKind; // Kind of tracker.
  3529. FlattenedTypeTracker(QualType type) : Type(type), Count(0), CurrentExpr(nullptr), IterKind(FK_IncompleteArray) {}
  3530. FlattenedTypeTracker(QualType type, unsigned int count, MultiExprArg::iterator expression) :
  3531. Type(type), Count(count), CurrentExpr(expression), IterKind(FK_Simple) {}
  3532. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current, RecordDecl::field_iterator end)
  3533. : Type(type), CurrentField(current), EndField(end), Count(0), CurrentExpr(nullptr), IterKind(FK_Fields) {}
  3534. FlattenedTypeTracker(MultiExprArg::iterator current, MultiExprArg::iterator end)
  3535. : CurrentExpr(current), EndExpr(end), Count(0), IterKind(FK_Expressions) {}
  3536. /// <summary>Gets the current expression if one is available.</summary>
  3537. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  3538. /// <summary>Replaces the current expression.</summary>
  3539. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  3540. };
  3541. HLSLExternalSource& m_source; // Source driving the iteration.
  3542. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  3543. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  3544. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  3545. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  3546. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  3547. QualType m_firstType; // Name of first type found, used for diagnostics.
  3548. SourceLocation m_loc; // Location used for diagnostics.
  3549. static const size_t MaxTypeDepth = 100;
  3550. void advanceLeafTracker();
  3551. /// <summary>Consumes leaves.</summary>
  3552. void consumeLeaf();
  3553. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  3554. bool considerLeaf();
  3555. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  3556. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  3557. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  3558. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  3559. public:
  3560. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  3561. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  3562. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  3563. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  3564. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  3565. QualType getCurrentElement() const;
  3566. /// <summary>Get the number of repeated current elements.</summary>
  3567. unsigned int getCurrentElementSize() const;
  3568. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  3569. bool hasCurrentElement() const;
  3570. /// <summary>Consumes count elements on this iterator.</summary>
  3571. void advanceCurrentElement(unsigned int count);
  3572. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  3573. unsigned int countRemaining();
  3574. /// <summary>Gets the current expression if one is available.</summary>
  3575. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  3576. /// <summary>Replaces the current expression.</summary>
  3577. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  3578. struct ComparisonResult
  3579. {
  3580. unsigned int LeftCount;
  3581. unsigned int RightCount;
  3582. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  3583. bool AreElementsEqual;
  3584. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  3585. bool CanConvertElements;
  3586. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  3587. bool IsConvertibleAndEqualLength() const {
  3588. return LeftCount == RightCount;
  3589. }
  3590. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  3591. bool IsConvertibleAndLeftLonger() const {
  3592. return CanConvertElements && LeftCount > RightCount;
  3593. }
  3594. bool IsRightLonger() const {
  3595. return RightCount > LeftCount;
  3596. }
  3597. };
  3598. static ComparisonResult CompareIterators(
  3599. HLSLExternalSource& source, SourceLocation loc,
  3600. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  3601. static ComparisonResult CompareTypes(
  3602. HLSLExternalSource& source,
  3603. SourceLocation leftLoc, SourceLocation rightLoc,
  3604. QualType left, QualType right);
  3605. // Compares the arguments to initialize the left type, modifying them if necessary.
  3606. static ComparisonResult CompareTypesForInit(
  3607. HLSLExternalSource& source, QualType left, MultiExprArg args,
  3608. SourceLocation leftLoc, SourceLocation rightLoc);
  3609. };
  3610. static
  3611. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  3612. {
  3613. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  3614. if (specialization) {
  3615. const TemplateArgumentList& list = specialization->getTemplateArgs();
  3616. if (list.size()) {
  3617. return list[0].getAsType();
  3618. }
  3619. }
  3620. return QualType();
  3621. }
  3622. static
  3623. QualType GetFirstElementType(QualType type)
  3624. {
  3625. if (!type.isNull()) {
  3626. const RecordType* record = type->getAs<RecordType>();
  3627. if (record) {
  3628. return GetFirstElementTypeFromDecl(record->getDecl());
  3629. }
  3630. }
  3631. return QualType();
  3632. }
  3633. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  3634. static
  3635. QualType CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  3636. {
  3637. DXASSERT_NOMSG(context != nullptr);
  3638. DXASSERT_NOMSG(ident != nullptr);
  3639. DXASSERT_NOMSG(!baseType.isNull());
  3640. DeclContext* declContext = context->getTranslationUnitDecl();
  3641. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  3642. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  3643. declContext->addDecl(decl);
  3644. decl->setImplicit(true);
  3645. return context->getTypeDeclType(decl);
  3646. }
  3647. void HLSLExternalSource::AddHLSLScalarTypes()
  3648. {
  3649. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  3650. m_scalarTypes[HLSLScalarType_bool] = m_context->BoolTy;
  3651. m_scalarTypes[HLSLScalarType_int] = m_context->IntTy;
  3652. m_scalarTypes[HLSLScalarType_uint] = CreateGlobalTypedef(m_context, "uint", m_context->UnsignedIntTy);
  3653. m_scalarTypes[HLSLScalarType_dword] = CreateGlobalTypedef(m_context, "dword", m_context->UnsignedIntTy);
  3654. m_scalarTypes[HLSLScalarType_half] = CreateGlobalTypedef(m_context, "half", m_context->FloatTy);
  3655. m_scalarTypes[HLSLScalarType_float] = m_context->FloatTy;
  3656. m_scalarTypes[HLSLScalarType_double] = m_context->DoubleTy;
  3657. m_scalarTypes[HLSLScalarType_float_min10] = m_context->Min10FloatTy;
  3658. m_scalarTypes[HLSLScalarType_float_min16] = CreateGlobalTypedef(m_context, "min16float", m_context->HalfTy);
  3659. m_scalarTypes[HLSLScalarType_int_min12] = m_context->Min12IntTy;
  3660. m_scalarTypes[HLSLScalarType_int_min16] = CreateGlobalTypedef(m_context, "min16int", m_context->ShortTy);
  3661. m_scalarTypes[HLSLScalarType_uint_min16] = CreateGlobalTypedef(m_context, "min16uint", m_context->UnsignedShortTy);
  3662. m_scalarTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  3663. m_scalarTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  3664. m_scalarTypes[HLSLScalarType_int64] = CreateGlobalTypedef(m_context, "int64_t", m_context->LongLongTy);
  3665. m_scalarTypes[HLSLScalarType_uint64] = CreateGlobalTypedef(m_context, "uint64_t", m_context->UnsignedLongLongTy);
  3666. }
  3667. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  3668. _In_ FunctionTemplateDecl* functionTemplate,
  3669. QualType objectElement,
  3670. const FindStructBasicTypeResult& findResult)
  3671. {
  3672. DXASSERT_NOMSG(functionTemplate != nullptr);
  3673. DXASSERT_NOMSG(!objectElement.isNull());
  3674. DXASSERT_NOMSG(findResult.Found());
  3675. DXASSERT(
  3676. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  3677. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  3678. // Subscript is templated only on its return type.
  3679. // Create the template argument.
  3680. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  3681. QualType resultType = objectElement;
  3682. if (isReadWrite)
  3683. resultType = m_context->getLValueReferenceType(resultType, false);
  3684. else {
  3685. // Add const to avoid write.
  3686. resultType = m_context->getConstType(resultType);
  3687. resultType = m_context->getLValueReferenceType(resultType);
  3688. }
  3689. TemplateArgument templateArgument(resultType);
  3690. unsigned subscriptCardinality =
  3691. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  3692. QualType subscriptIndexType =
  3693. subscriptCardinality == 1
  3694. ? m_context->UnsignedIntTy
  3695. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  3696. subscriptCardinality);
  3697. // Look for an existing specialization.
  3698. void* InsertPos = nullptr;
  3699. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  3700. if (SpecFunc != nullptr) {
  3701. return SpecFunc;
  3702. }
  3703. // Create a new specialization.
  3704. DeclContext* owner = functionTemplate->getDeclContext();
  3705. TemplateArgumentList templateArgumentList(
  3706. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  3707. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  3708. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  3709. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  3710. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  3711. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  3712. QualType functionType = m_context->getFunctionType(
  3713. resultType, subscriptIndexType, templateEPI, None);
  3714. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  3715. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  3716. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  3717. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  3718. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  3719. QualType T = TInfo->getType();
  3720. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  3721. CXXMethodDecl* method = CXXMethodDecl::Create(
  3722. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  3723. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  3724. // Add subscript attribute
  3725. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  3726. // Record this function template specialization.
  3727. method->setFunctionTemplateSpecialization(functionTemplate,
  3728. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  3729. // Attach the parameters
  3730. indexerParam->setOwningFunction(method);
  3731. Proto.setParam(0, indexerParam);
  3732. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  3733. // Adjust access.
  3734. method->setAccess(AccessSpecifier::AS_public);
  3735. functionTemplate->setAccess(method->getAccess());
  3736. return method;
  3737. }
  3738. /// <summary>
  3739. /// This routine combines Source into Target. If you have a symmetric operation
  3740. /// and want to treat either side equally you should call it twice, swapping the
  3741. /// parameter order.
  3742. /// </summary>
  3743. static bool CombineObjectTypes(ArBasicKind Target, __in ArBasicKind Source,
  3744. _Out_opt_ ArBasicKind *pCombined) {
  3745. if (Target == Source) {
  3746. AssignOpt(Target, pCombined);
  3747. return true;
  3748. }
  3749. if (Source == AR_OBJECT_NULL) {
  3750. // NULL is valid for any object type.
  3751. AssignOpt(Target, pCombined);
  3752. return true;
  3753. }
  3754. switch (Target) {
  3755. AR_BASIC_ROBJECT_CASES:
  3756. if (Source == AR_OBJECT_STATEBLOCK) {
  3757. AssignOpt(Target, pCombined);
  3758. return true;
  3759. }
  3760. break;
  3761. AR_BASIC_TEXTURE_CASES:
  3762. AR_BASIC_NON_CMP_SAMPLER_CASES:
  3763. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  3764. AssignOpt(Target, pCombined);
  3765. return true;
  3766. }
  3767. break;
  3768. case AR_OBJECT_SAMPLERCOMPARISON:
  3769. if (Source == AR_OBJECT_STATEBLOCK) {
  3770. AssignOpt(Target, pCombined);
  3771. return true;
  3772. }
  3773. break;
  3774. }
  3775. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  3776. return false;
  3777. }
  3778. static ArBasicKind LiteralToConcrete(Expr *litExpr) {
  3779. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  3780. llvm::APInt val = intLit->getValue();
  3781. unsigned width = val.getActiveBits();
  3782. bool isNeg = val.isNegative();
  3783. if (isNeg) {
  3784. // Signed.
  3785. if (width <= 32)
  3786. return ArBasicKind::AR_BASIC_INT32;
  3787. else
  3788. return ArBasicKind::AR_BASIC_INT64;
  3789. } else {
  3790. // Unsigned.
  3791. if (width <= 32)
  3792. return ArBasicKind::AR_BASIC_UINT32;
  3793. else
  3794. return ArBasicKind::AR_BASIC_UINT64;
  3795. }
  3796. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  3797. llvm::APFloat val = floatLit->getValue();
  3798. unsigned width = val.getSizeInBits(val.getSemantics());
  3799. if (width <= 16)
  3800. return ArBasicKind::AR_BASIC_FLOAT16;
  3801. else if (width <= 32)
  3802. return ArBasicKind::AR_BASIC_FLOAT32;
  3803. else
  3804. return AR_BASIC_FLOAT64;
  3805. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  3806. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr());
  3807. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  3808. if (kind == ArBasicKind::AR_BASIC_UINT32)
  3809. kind = ArBasicKind::AR_BASIC_INT32;
  3810. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  3811. kind = ArBasicKind::AR_BASIC_INT64;
  3812. }
  3813. return kind;
  3814. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  3815. ArBasicKind kind = LiteralToConcrete(BO->getLHS());
  3816. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS());
  3817. CombineBasicTypes(kind, kind1, &kind);
  3818. return kind;
  3819. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  3820. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr());
  3821. return kind;
  3822. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  3823. ArBasicKind kind = LiteralToConcrete(CO->getLHS());
  3824. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS());
  3825. CombineBasicTypes(kind, kind1, &kind);
  3826. return kind;
  3827. } else {
  3828. // Could only be function call.
  3829. CallExpr *CE = cast<CallExpr>(litExpr);
  3830. // TODO: calculate the function call result.
  3831. if (CE->getNumArgs() == 1)
  3832. return LiteralToConcrete(CE->getArg(0));
  3833. else {
  3834. ArBasicKind kind = LiteralToConcrete(CE->getArg(0));
  3835. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  3836. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i));
  3837. CombineBasicTypes(kind, kindI, &kind);
  3838. }
  3839. return kind;
  3840. }
  3841. }
  3842. }
  3843. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  3844. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  3845. if (kind == *pCT)
  3846. return true;
  3847. pCT++;
  3848. }
  3849. return false;
  3850. }
  3851. static ArBasicKind ConcreteLiteralType(Expr *litExpr,
  3852. ArBasicKind kind,
  3853. unsigned uLegalComponentTypes) {
  3854. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  3855. ArBasicKind defaultKind = *pCT;
  3856. // Use first none literal kind as defaultKind.
  3857. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  3858. ArBasicKind kind = *pCT;
  3859. pCT++;
  3860. // Skip literal type.
  3861. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  3862. continue;
  3863. defaultKind = kind;
  3864. break;
  3865. }
  3866. ArBasicKind litKind = LiteralToConcrete(litExpr);
  3867. if (kind == AR_BASIC_LITERAL_INT) {
  3868. // Search for match first.
  3869. // For literal arg which don't affect return type, the search should always success.
  3870. // Unless use literal int on a float parameter.
  3871. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  3872. return litKind;
  3873. // Return the default.
  3874. return defaultKind;
  3875. }
  3876. else {
  3877. // Search for float32 first.
  3878. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  3879. return AR_BASIC_FLOAT32;
  3880. // Search for float64.
  3881. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  3882. return AR_BASIC_FLOAT64;
  3883. // return default.
  3884. return defaultKind;
  3885. }
  3886. }
  3887. _Use_decl_annotations_ bool
  3888. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  3889. QualType objectElement) {
  3890. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  3891. switch (op) {
  3892. case IntrinsicOp::MOP_Sample:
  3893. case IntrinsicOp::MOP_SampleBias:
  3894. case IntrinsicOp::MOP_SampleCmp:
  3895. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3896. case IntrinsicOp::MOP_SampleGrad:
  3897. case IntrinsicOp::MOP_SampleLevel: {
  3898. ArBasicKind kind = GetTypeElementKind(objectElement);
  3899. UINT uBits = GET_BPROP_BITS(kind);
  3900. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  3901. } break;
  3902. default:
  3903. return true;
  3904. }
  3905. }
  3906. _Use_decl_annotations_
  3907. bool HLSLExternalSource::MatchArguments(
  3908. const HLSL_INTRINSIC* pIntrinsic,
  3909. QualType objectElement,
  3910. ArrayRef<Expr *> Args,
  3911. QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  3912. size_t* argCount)
  3913. {
  3914. DXASSERT_NOMSG(pIntrinsic != nullptr);
  3915. DXASSERT_NOMSG(argCount != nullptr);
  3916. static const UINT UnusedSize = 0xFF;
  3917. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  3918. #define CAB(_) { if (!(_)) return false; }
  3919. *argCount = 0;
  3920. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  3921. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  3922. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  3923. // Reset infos
  3924. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  3925. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  3926. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  3927. const unsigned retArgIdx = 0;
  3928. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  3929. // Populate the template for each argument.
  3930. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  3931. ArrayRef<Expr*>::iterator end = Args.end();
  3932. unsigned int iArg = 1;
  3933. for (; iterArg != end; ++iterArg) {
  3934. Expr* pCallArg = *iterArg;
  3935. // No vararg support.
  3936. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  3937. return false;
  3938. }
  3939. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  3940. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  3941. DXASSERT(pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS, "no vararg support");
  3942. // If we are a type and templateID requires one, this isn't a match.
  3943. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  3944. ++iArg;
  3945. continue;
  3946. }
  3947. QualType pType = pCallArg->getType();
  3948. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  3949. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  3950. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  3951. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  3952. bool affectRetType =
  3953. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  3954. // For literal arg which don't affect return type, find concrete type.
  3955. // For literal arg affect return type,
  3956. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  3957. // where all argumentss are literal.
  3958. // CombineBasicTypes will cover the rest cases.
  3959. if (!affectRetType) {
  3960. TypeInfoEltKind = ConcreteLiteralType(
  3961. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes);
  3962. }
  3963. }
  3964. UINT TypeInfoCols = 1;
  3965. UINT TypeInfoRows = 1;
  3966. switch (TypeInfoShapeKind) {
  3967. case AR_TOBJ_MATRIX:
  3968. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  3969. break;
  3970. case AR_TOBJ_VECTOR:
  3971. TypeInfoCols = GetHLSLVecSize(pType);
  3972. break;
  3973. case AR_TOBJ_BASIC:
  3974. case AR_TOBJ_OBJECT:
  3975. break;
  3976. default:
  3977. return false; // no struct, arrays or void
  3978. }
  3979. DXASSERT(
  3980. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  3981. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  3982. // Compare template
  3983. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  3984. (AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  3985. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind)) {
  3986. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  3987. }
  3988. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  3989. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  3990. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  3991. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  3992. return false;
  3993. }
  3994. }
  3995. else {
  3996. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  3997. return false;
  3998. }
  3999. }
  4000. DXASSERT(
  4001. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4002. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4003. // Merge ComponentTypes
  4004. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4005. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4006. }
  4007. else {
  4008. if (!CombineBasicTypes(
  4009. ComponentType[pIntrinsicArg->uComponentTypeId],
  4010. TypeInfoEltKind,
  4011. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4012. return false;
  4013. }
  4014. }
  4015. // Rows
  4016. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4017. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4018. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4019. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4020. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4021. uSpecialSize[uSpecialId] = TypeInfoRows;
  4022. }
  4023. }
  4024. else {
  4025. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4026. return false;
  4027. }
  4028. }
  4029. }
  4030. // Columns
  4031. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4032. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4033. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4034. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4035. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4036. uSpecialSize[uSpecialId] = TypeInfoCols;
  4037. }
  4038. }
  4039. else {
  4040. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4041. return false;
  4042. }
  4043. }
  4044. }
  4045. // Usage
  4046. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4047. if (pCallArg->getType().isConstQualified()) {
  4048. // Can't use a const type in an out or inout parameter.
  4049. return false;
  4050. }
  4051. }
  4052. iArg++;
  4053. }
  4054. DXASSERT(iterArg == end, "otherwise the argument list wasn't fully processed");
  4055. // Default template and component type for return value
  4056. if (pIntrinsic->pArgs[0].qwUsage && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE) {
  4057. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4058. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4059. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4060. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4061. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4062. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4063. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4064. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4065. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4066. }
  4067. }
  4068. }
  4069. }
  4070. // Make sure all template, component type, and texture type selections are valid.
  4071. for (size_t i = 0; i < Args.size() + 1; i++) {
  4072. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4073. // Check template.
  4074. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4075. continue; // Already verified that this is available.
  4076. }
  4077. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4078. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4079. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4080. Template[i] = *pTT;
  4081. }
  4082. else {
  4083. while (AR_TOBJ_UNKNOWN != *pTT) {
  4084. if (Template[i] == *pTT)
  4085. break;
  4086. pTT++;
  4087. }
  4088. }
  4089. if (AR_TOBJ_UNKNOWN == *pTT)
  4090. return false;
  4091. }
  4092. else if (pTT) {
  4093. Template[i] = *pTT;
  4094. }
  4095. // Check component type.
  4096. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4097. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4098. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4099. if (ComponentType[i] == *pCT)
  4100. break;
  4101. pCT++;
  4102. }
  4103. // has to be a strict match
  4104. if (*pCT == AR_BASIC_NOCAST)
  4105. return false;
  4106. // If it is an object, see if it can be cast to the first thing in the
  4107. // list, otherwise move on to next intrinsic.
  4108. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4109. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4110. return false;
  4111. }
  4112. }
  4113. if (AR_BASIC_UNKNOWN == *pCT) {
  4114. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4115. }
  4116. }
  4117. else if (pCT) {
  4118. ComponentType[i] = *pCT;
  4119. }
  4120. }
  4121. // Default to a void return type.
  4122. argTypes[0] = m_context->VoidTy;
  4123. // Default specials sizes.
  4124. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  4125. if (UnusedSize == uSpecialSize[i]) {
  4126. uSpecialSize[i] = 1;
  4127. }
  4128. }
  4129. // Populate argTypes.
  4130. for (size_t i = 0; i <= Args.size(); i++) {
  4131. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4132. if (!pArgument->qwUsage)
  4133. continue;
  4134. QualType pNewType;
  4135. unsigned int quals = 0; // qualifications for this argument
  4136. // If we have no type, set it to our input type (templatized)
  4137. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4138. // Use the templated input type, but resize it if the
  4139. // intrinsic's rows/cols isn't 0
  4140. if (pArgument->uRows && pArgument->uCols) {
  4141. UINT uRows, uCols;
  4142. // if type is overriden, use new type size, for
  4143. // now it only supports scalars
  4144. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4145. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4146. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4147. uRows = uSpecialSize[uSpecialId];
  4148. }
  4149. else if (pArgument->uRows > 0) {
  4150. uRows = pArgument->uRows;
  4151. }
  4152. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4153. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4154. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4155. uCols = uSpecialSize[uSpecialId];
  4156. }
  4157. else if (pArgument->uCols > 0) {
  4158. uCols = pArgument->uCols;
  4159. }
  4160. // 1x1 numeric outputs are always scalar.. since these
  4161. // are most flexible
  4162. if ((1 == uCols) && (1 == uRows)) {
  4163. pNewType = objectElement;
  4164. if (pNewType.isNull()) {
  4165. return false;
  4166. }
  4167. }
  4168. else {
  4169. // non-scalars unsupported right now since nothing
  4170. // uses it, would have to create either a type
  4171. // list for sub-structures or just resize the
  4172. // given type
  4173. // VH(E_NOTIMPL);
  4174. return false;
  4175. }
  4176. }
  4177. else {
  4178. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  4179. if (objectElement.isNull()) {
  4180. return false;
  4181. }
  4182. pNewType = objectElement;
  4183. }
  4184. }
  4185. else {
  4186. ArBasicKind pEltType;
  4187. // ComponentType, if the Id is special then it gets the
  4188. // component type from the first component of the type, if
  4189. // we need more (for the second component, e.g.), then we
  4190. // can use more specials, etc.
  4191. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4192. if (objectElement.isNull()) {
  4193. return false;
  4194. }
  4195. pEltType = GetTypeElementKind(objectElement);
  4196. DXASSERT_VALIDBASICKIND(pEltType);
  4197. }
  4198. else {
  4199. pEltType = ComponentType[pArgument->uComponentTypeId];
  4200. DXASSERT_VALIDBASICKIND(pEltType);
  4201. }
  4202. UINT uRows, uCols;
  4203. // Rows
  4204. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4205. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4206. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4207. uRows = uSpecialSize[uSpecialId];
  4208. }
  4209. else {
  4210. uRows = pArgument->uRows;
  4211. }
  4212. // Cols
  4213. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4214. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4215. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4216. uCols = uSpecialSize[uSpecialId];
  4217. }
  4218. else {
  4219. uCols = pArgument->uCols;
  4220. }
  4221. // Verify that the final results are in bounds.
  4222. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  4223. // Const
  4224. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  4225. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  4226. qwQual |= AR_QUAL_CONST;
  4227. DXASSERT_VALIDBASICKIND(pEltType);
  4228. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  4229. }
  4230. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  4231. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  4232. // TODO: support out modifier
  4233. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  4234. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  4235. //}
  4236. }
  4237. *argCount = iArg;
  4238. DXASSERT(
  4239. *argCount == pIntrinsic->uNumArgs,
  4240. "In the absence of varargs, a successful match would indicate we have as many arguments and types as the intrinsic template");
  4241. return true;
  4242. #undef CAB
  4243. }
  4244. _Use_decl_annotations_
  4245. HLSLExternalSource::FindStructBasicTypeResult
  4246. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  4247. {
  4248. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4249. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  4250. // may be a simple class, such as RWByteAddressBuffer.
  4251. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  4252. // We save the caller from filtering out other types of context (like the translation unit itself).
  4253. if (recordDecl != nullptr)
  4254. {
  4255. int index = FindObjectBasicKindIndex(recordDecl);
  4256. if (index != -1) {
  4257. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  4258. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  4259. }
  4260. }
  4261. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  4262. }
  4263. _Use_decl_annotations_
  4264. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  4265. {
  4266. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4267. DXASSERT_NOMSG(name != nullptr);
  4268. DXASSERT_NOMSG(intrinsics != nullptr);
  4269. DXASSERT_NOMSG(intrinsicCount != nullptr);
  4270. *intrinsics = nullptr;
  4271. *intrinsicCount = 0;
  4272. *name = nullptr;
  4273. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  4274. if (lookup.Found()) {
  4275. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  4276. *name = g_ArBasicTypeNames[lookup.Kind];
  4277. }
  4278. }
  4279. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  4280. {
  4281. return
  4282. // Arithmetic operators.
  4283. Opc == BinaryOperatorKind::BO_Add ||
  4284. Opc == BinaryOperatorKind::BO_AddAssign ||
  4285. Opc == BinaryOperatorKind::BO_Sub ||
  4286. Opc == BinaryOperatorKind::BO_SubAssign ||
  4287. Opc == BinaryOperatorKind::BO_Rem ||
  4288. Opc == BinaryOperatorKind::BO_RemAssign ||
  4289. Opc == BinaryOperatorKind::BO_Div ||
  4290. Opc == BinaryOperatorKind::BO_DivAssign ||
  4291. Opc == BinaryOperatorKind::BO_Mul ||
  4292. Opc == BinaryOperatorKind::BO_MulAssign;
  4293. }
  4294. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  4295. {
  4296. return
  4297. // Arithmetic-and-assignment operators.
  4298. Opc == BinaryOperatorKind::BO_AddAssign ||
  4299. Opc == BinaryOperatorKind::BO_SubAssign ||
  4300. Opc == BinaryOperatorKind::BO_RemAssign ||
  4301. Opc == BinaryOperatorKind::BO_DivAssign ||
  4302. Opc == BinaryOperatorKind::BO_MulAssign ||
  4303. // Bitwise-and-assignment operators.
  4304. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4305. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4306. Opc == BinaryOperatorKind::BO_AndAssign ||
  4307. Opc == BinaryOperatorKind::BO_OrAssign ||
  4308. Opc == BinaryOperatorKind::BO_XorAssign;
  4309. }
  4310. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  4311. {
  4312. return
  4313. Opc == BinaryOperatorKind::BO_AndAssign ||
  4314. Opc == BinaryOperatorKind::BO_OrAssign ||
  4315. Opc == BinaryOperatorKind::BO_XorAssign;
  4316. }
  4317. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  4318. {
  4319. return
  4320. Opc == BinaryOperatorKind::BO_Shl ||
  4321. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4322. Opc == BinaryOperatorKind::BO_Shr ||
  4323. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4324. Opc == BinaryOperatorKind::BO_And ||
  4325. Opc == BinaryOperatorKind::BO_AndAssign ||
  4326. Opc == BinaryOperatorKind::BO_Or ||
  4327. Opc == BinaryOperatorKind::BO_OrAssign ||
  4328. Opc == BinaryOperatorKind::BO_Xor ||
  4329. Opc == BinaryOperatorKind::BO_XorAssign;
  4330. }
  4331. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  4332. {
  4333. return
  4334. Opc == BinaryOperatorKind::BO_Shl ||
  4335. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4336. Opc == BinaryOperatorKind::BO_Shr ||
  4337. Opc == BinaryOperatorKind::BO_ShrAssign;
  4338. }
  4339. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  4340. {
  4341. return
  4342. Opc == BinaryOperatorKind::BO_EQ ||
  4343. Opc == BinaryOperatorKind::BO_NE;
  4344. }
  4345. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  4346. {
  4347. return
  4348. Opc == BinaryOperatorKind::BO_LT ||
  4349. Opc == BinaryOperatorKind::BO_GT ||
  4350. Opc == BinaryOperatorKind::BO_LE ||
  4351. Opc == BinaryOperatorKind::BO_GE;
  4352. }
  4353. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  4354. {
  4355. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  4356. }
  4357. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  4358. {
  4359. return
  4360. Opc == BinaryOperatorKind::BO_LAnd ||
  4361. Opc == BinaryOperatorKind::BO_LOr;
  4362. }
  4363. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  4364. {
  4365. return
  4366. BinaryOperatorKindIsArithmetic(Opc) ||
  4367. BinaryOperatorKindIsOrderComparison(Opc) ||
  4368. BinaryOperatorKindIsLogical(Opc);
  4369. }
  4370. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  4371. {
  4372. return BinaryOperatorKindIsBitwise(Opc);
  4373. }
  4374. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  4375. {
  4376. return
  4377. BinaryOperatorKindIsBitwise(Opc) ||
  4378. BinaryOperatorKindIsArithmetic(Opc);
  4379. }
  4380. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  4381. {
  4382. return Opc == UnaryOperatorKind::UO_Not;
  4383. }
  4384. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  4385. {
  4386. return
  4387. Opc == UnaryOperatorKind::UO_LNot ||
  4388. Opc == UnaryOperatorKind::UO_Plus ||
  4389. Opc == UnaryOperatorKind::UO_Minus ||
  4390. // The omission in fxc caused objects and structs to accept this.
  4391. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4392. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4393. }
  4394. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  4395. {
  4396. return
  4397. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4398. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4399. }
  4400. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  4401. {
  4402. return
  4403. Opc == UnaryOperatorKind::UO_Not ||
  4404. Opc == UnaryOperatorKind::UO_Plus ||
  4405. Opc == UnaryOperatorKind::UO_Minus;
  4406. }
  4407. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  4408. {
  4409. return
  4410. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4411. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4412. }
  4413. /// <summary>
  4414. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  4415. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  4416. /// </summary>
  4417. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  4418. {
  4419. return
  4420. value == AR_TOBJ_BASIC ||
  4421. value == AR_TOBJ_MATRIX ||
  4422. value == AR_TOBJ_VECTOR;
  4423. }
  4424. static bool IsBasicKindIntegral(ArBasicKind value)
  4425. {
  4426. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  4427. }
  4428. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  4429. {
  4430. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  4431. }
  4432. static bool IsBasicKindNumeric(ArBasicKind value)
  4433. {
  4434. return GetBasicKindProps(value) & BPROP_NUMERIC;
  4435. }
  4436. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  4437. {
  4438. // An invalid expression is pass-through at this point.
  4439. if (E.isInvalid())
  4440. {
  4441. return E;
  4442. }
  4443. QualType qt = E.get()->getType();
  4444. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  4445. if (elementKind != AR_BASIC_BOOL)
  4446. {
  4447. return E;
  4448. }
  4449. // Construct a scalar/vector/matrix type with the same shape as E.
  4450. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  4451. QualType targetType;
  4452. UINT colCount, rowCount;
  4453. GetRowsAndColsForAny(qt, rowCount, colCount);
  4454. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  4455. if (E.get()->isLValue()) {
  4456. E = m_sema->DefaultLvalueConversion(E.get()).get();
  4457. }
  4458. switch (objectKind)
  4459. {
  4460. case AR_TOBJ_SCALAR:
  4461. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  4462. case AR_TOBJ_ARRAY:
  4463. case AR_TOBJ_VECTOR:
  4464. case AR_TOBJ_MATRIX:
  4465. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  4466. default:
  4467. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  4468. }
  4469. return E;
  4470. }
  4471. _Use_decl_annotations_
  4472. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  4473. {
  4474. DXASSERT_NOMSG(pTypeInfo != nullptr);
  4475. DXASSERT_NOMSG(!type.isNull());
  4476. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  4477. pTypeInfo->ObjKind = GetTypeElementKind(type);
  4478. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  4479. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  4480. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  4481. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  4482. }
  4483. // Highest possible score (i.e., worst possible score).
  4484. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  4485. // Leave the first two score bits to handle higher-level
  4486. // variations like target type.
  4487. #define SCORE_MIN_SHIFT 2
  4488. // Space out scores to allow up to 128 parameters to
  4489. // vary between score sets spill into each other.
  4490. #define SCORE_PARAM_SHIFT 7
  4491. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  4492. if (anyType.isNull()) {
  4493. return 0;
  4494. }
  4495. anyType = GetStructuralForm(anyType);
  4496. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  4497. switch (kind) {
  4498. case AR_TOBJ_BASIC:
  4499. case AR_TOBJ_OBJECT:
  4500. return 1;
  4501. case AR_TOBJ_COMPOUND: {
  4502. // TODO: consider caching this value for perf
  4503. unsigned total = 0;
  4504. const RecordType *recordType = anyType->getAs<RecordType>();
  4505. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  4506. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  4507. while (fi != fend) {
  4508. total += GetNumElements(fi->getType());
  4509. ++fi;
  4510. }
  4511. return total;
  4512. }
  4513. case AR_TOBJ_ARRAY:
  4514. case AR_TOBJ_MATRIX:
  4515. case AR_TOBJ_VECTOR:
  4516. return GetElementCount(anyType);
  4517. default:
  4518. DXASSERT(kind == AR_TOBJ_VOID,
  4519. "otherwise the type cannot be classified or is not supported");
  4520. return 0;
  4521. }
  4522. }
  4523. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  4524. unsigned leftSize,
  4525. QualType rightType,
  4526. unsigned rightSize) {
  4527. // We can convert from a larger type to a smaller
  4528. // but not a smaller type to a larger so default
  4529. // to just comparing the destination size.
  4530. unsigned uElts = leftSize;
  4531. leftType = GetStructuralForm(leftType);
  4532. rightType = GetStructuralForm(rightType);
  4533. if (leftType->isArrayType() && rightType->isArrayType()) {
  4534. //
  4535. // If we're comparing arrays we don't
  4536. // need to compare every element of
  4537. // the arrays since all elements
  4538. // will have the same type.
  4539. // We only need to compare enough
  4540. // elements that we've tried every
  4541. // possible mix of dst and src elements.
  4542. //
  4543. // TODO: handle multidimensional arrays and arrays of arrays
  4544. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  4545. unsigned uDstEltSize = GetNumElements(pDstElt);
  4546. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  4547. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  4548. if (uDstEltSize == uSrcEltSize) {
  4549. uElts = uDstEltSize;
  4550. } else if (uDstEltSize > uSrcEltSize) {
  4551. // If one size is not an even multiple of the other we need to let the
  4552. // full compare run in order to try all alignments.
  4553. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  4554. uElts = uDstEltSize;
  4555. }
  4556. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  4557. uElts = uSrcEltSize;
  4558. }
  4559. }
  4560. return uElts;
  4561. }
  4562. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  4563. if (type.isNull()) {
  4564. return type;
  4565. }
  4566. ArTypeObjectKind kind = GetTypeObjectKind(type);
  4567. switch (kind) {
  4568. case AR_TOBJ_BASIC:
  4569. case AR_TOBJ_OBJECT:
  4570. return (index == 0) ? type : QualType();
  4571. case AR_TOBJ_COMPOUND: {
  4572. // TODO: consider caching this value for perf
  4573. const RecordType *recordType = type->getAsStructureType();
  4574. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  4575. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  4576. while (fi != fend) {
  4577. if (!fi->getType().isNull()) {
  4578. unsigned subElements = GetNumElements(fi->getType());
  4579. if (index < subElements) {
  4580. return GetNthElementType(fi->getType(), index);
  4581. } else {
  4582. index -= subElements;
  4583. }
  4584. }
  4585. ++fi;
  4586. }
  4587. return QualType();
  4588. }
  4589. case AR_TOBJ_ARRAY: {
  4590. unsigned arraySize;
  4591. QualType elementType;
  4592. unsigned elementCount;
  4593. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  4594. elementCount = GetElementCount(elementType);
  4595. if (index < elementCount) {
  4596. return GetNthElementType(elementType, index);
  4597. }
  4598. arraySize = GetArraySize(type);
  4599. if (index >= arraySize * elementCount) {
  4600. return QualType();
  4601. }
  4602. return GetNthElementType(elementType, index % elementCount);
  4603. }
  4604. case AR_TOBJ_MATRIX:
  4605. case AR_TOBJ_VECTOR:
  4606. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  4607. : QualType();
  4608. default:
  4609. DXASSERT(kind == AR_TOBJ_VOID,
  4610. "otherwise the type cannot be classified or is not supported");
  4611. return QualType();
  4612. }
  4613. }
  4614. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  4615. // Eliminate exact matches first, then check for promotions.
  4616. if (leftKind == rightKind) {
  4617. return false;
  4618. }
  4619. switch (rightKind) {
  4620. case AR_BASIC_FLOAT16:
  4621. switch (leftKind) {
  4622. case AR_BASIC_FLOAT32:
  4623. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4624. case AR_BASIC_FLOAT64:
  4625. return true;
  4626. }
  4627. break;
  4628. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4629. switch (leftKind) {
  4630. case AR_BASIC_FLOAT32:
  4631. case AR_BASIC_FLOAT64:
  4632. return true;
  4633. }
  4634. break;
  4635. case AR_BASIC_FLOAT32:
  4636. switch (leftKind) {
  4637. case AR_BASIC_FLOAT64:
  4638. return true;
  4639. }
  4640. break;
  4641. case AR_BASIC_MIN10FLOAT:
  4642. switch (leftKind) {
  4643. case AR_BASIC_MIN16FLOAT:
  4644. case AR_BASIC_FLOAT32:
  4645. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4646. case AR_BASIC_FLOAT64:
  4647. return true;
  4648. }
  4649. break;
  4650. case AR_BASIC_MIN16FLOAT:
  4651. switch (leftKind) {
  4652. case AR_BASIC_FLOAT32:
  4653. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4654. case AR_BASIC_FLOAT64:
  4655. return true;
  4656. }
  4657. break;
  4658. case AR_BASIC_INT8:
  4659. case AR_BASIC_UINT8:
  4660. // For backwards compat we consider signed/unsigned the same.
  4661. switch (leftKind) {
  4662. case AR_BASIC_INT16:
  4663. case AR_BASIC_INT32:
  4664. case AR_BASIC_INT64:
  4665. case AR_BASIC_UINT16:
  4666. case AR_BASIC_UINT32:
  4667. case AR_BASIC_UINT64:
  4668. return true;
  4669. }
  4670. break;
  4671. case AR_BASIC_INT16:
  4672. case AR_BASIC_UINT16:
  4673. // For backwards compat we consider signed/unsigned the same.
  4674. switch (leftKind) {
  4675. case AR_BASIC_INT32:
  4676. case AR_BASIC_INT64:
  4677. case AR_BASIC_UINT32:
  4678. case AR_BASIC_UINT64:
  4679. return true;
  4680. }
  4681. break;
  4682. case AR_BASIC_INT32:
  4683. case AR_BASIC_UINT32:
  4684. // For backwards compat we consider signed/unsigned the same.
  4685. switch (leftKind) {
  4686. case AR_BASIC_INT64:
  4687. case AR_BASIC_UINT64:
  4688. return true;
  4689. }
  4690. break;
  4691. case AR_BASIC_MIN12INT:
  4692. switch (leftKind) {
  4693. case AR_BASIC_MIN16INT:
  4694. case AR_BASIC_INT32:
  4695. case AR_BASIC_INT64:
  4696. return true;
  4697. }
  4698. break;
  4699. case AR_BASIC_MIN16INT:
  4700. switch (leftKind) {
  4701. case AR_BASIC_INT32:
  4702. case AR_BASIC_INT64:
  4703. return true;
  4704. }
  4705. break;
  4706. case AR_BASIC_MIN16UINT:
  4707. switch (leftKind) {
  4708. case AR_BASIC_UINT32:
  4709. case AR_BASIC_UINT64:
  4710. return true;
  4711. }
  4712. break;
  4713. }
  4714. return false;
  4715. }
  4716. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  4717. // Eliminate exact matches first, then check for casts.
  4718. if (leftKind == rightKind) {
  4719. return false;
  4720. }
  4721. //
  4722. // All minimum-bits types are only considered matches of themselves
  4723. // and thus are not in this table.
  4724. //
  4725. switch (leftKind) {
  4726. case AR_BASIC_LITERAL_INT:
  4727. switch (rightKind) {
  4728. case AR_BASIC_INT8:
  4729. case AR_BASIC_INT16:
  4730. case AR_BASIC_INT32:
  4731. case AR_BASIC_INT64:
  4732. case AR_BASIC_UINT8:
  4733. case AR_BASIC_UINT16:
  4734. case AR_BASIC_UINT32:
  4735. case AR_BASIC_UINT64:
  4736. return false;
  4737. }
  4738. break;
  4739. case AR_BASIC_INT8:
  4740. switch (rightKind) {
  4741. // For backwards compat we consider signed/unsigned the same.
  4742. case AR_BASIC_LITERAL_INT:
  4743. case AR_BASIC_UINT8:
  4744. return false;
  4745. }
  4746. break;
  4747. case AR_BASIC_INT16:
  4748. switch (rightKind) {
  4749. // For backwards compat we consider signed/unsigned the same.
  4750. case AR_BASIC_LITERAL_INT:
  4751. case AR_BASIC_UINT16:
  4752. return false;
  4753. }
  4754. break;
  4755. case AR_BASIC_INT32:
  4756. switch (rightKind) {
  4757. // For backwards compat we consider signed/unsigned the same.
  4758. case AR_BASIC_LITERAL_INT:
  4759. case AR_BASIC_UINT32:
  4760. return false;
  4761. }
  4762. break;
  4763. case AR_BASIC_INT64:
  4764. switch (rightKind) {
  4765. // For backwards compat we consider signed/unsigned the same.
  4766. case AR_BASIC_LITERAL_INT:
  4767. case AR_BASIC_UINT64:
  4768. return false;
  4769. }
  4770. break;
  4771. case AR_BASIC_UINT8:
  4772. switch (rightKind) {
  4773. // For backwards compat we consider signed/unsigned the same.
  4774. case AR_BASIC_LITERAL_INT:
  4775. case AR_BASIC_INT8:
  4776. return false;
  4777. }
  4778. break;
  4779. case AR_BASIC_UINT16:
  4780. switch (rightKind) {
  4781. // For backwards compat we consider signed/unsigned the same.
  4782. case AR_BASIC_LITERAL_INT:
  4783. case AR_BASIC_INT16:
  4784. return false;
  4785. }
  4786. break;
  4787. case AR_BASIC_UINT32:
  4788. switch (rightKind) {
  4789. // For backwards compat we consider signed/unsigned the same.
  4790. case AR_BASIC_LITERAL_INT:
  4791. case AR_BASIC_INT32:
  4792. return false;
  4793. }
  4794. break;
  4795. case AR_BASIC_UINT64:
  4796. switch (rightKind) {
  4797. // For backwards compat we consider signed/unsigned the same.
  4798. case AR_BASIC_LITERAL_INT:
  4799. case AR_BASIC_INT64:
  4800. return false;
  4801. }
  4802. break;
  4803. case AR_BASIC_LITERAL_FLOAT:
  4804. switch (rightKind) {
  4805. case AR_BASIC_LITERAL_FLOAT:
  4806. case AR_BASIC_FLOAT16:
  4807. case AR_BASIC_FLOAT32:
  4808. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4809. case AR_BASIC_FLOAT64:
  4810. return false;
  4811. }
  4812. break;
  4813. case AR_BASIC_FLOAT16:
  4814. switch (rightKind) {
  4815. case AR_BASIC_LITERAL_FLOAT:
  4816. return false;
  4817. }
  4818. break;
  4819. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4820. switch (rightKind) {
  4821. case AR_BASIC_LITERAL_FLOAT:
  4822. return false;
  4823. }
  4824. break;
  4825. case AR_BASIC_FLOAT32:
  4826. switch (rightKind) {
  4827. case AR_BASIC_LITERAL_FLOAT:
  4828. return false;
  4829. }
  4830. break;
  4831. case AR_BASIC_FLOAT64:
  4832. switch (rightKind) {
  4833. case AR_BASIC_LITERAL_FLOAT:
  4834. return false;
  4835. }
  4836. break;
  4837. }
  4838. return true;
  4839. }
  4840. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  4841. // Eliminate exact matches first, then check for casts.
  4842. if (leftKind == rightKind) {
  4843. return false;
  4844. }
  4845. //
  4846. // All minimum-bits types are only considered matches of themselves
  4847. // and thus are not in this table.
  4848. //
  4849. switch (leftKind) {
  4850. case AR_BASIC_LITERAL_INT:
  4851. switch (rightKind) {
  4852. case AR_BASIC_INT8:
  4853. case AR_BASIC_INT16:
  4854. case AR_BASIC_INT32:
  4855. case AR_BASIC_INT64:
  4856. case AR_BASIC_UINT8:
  4857. case AR_BASIC_UINT16:
  4858. case AR_BASIC_UINT32:
  4859. case AR_BASIC_UINT64:
  4860. return false;
  4861. }
  4862. break;
  4863. case AR_BASIC_INT8:
  4864. case AR_BASIC_INT16:
  4865. case AR_BASIC_INT32:
  4866. case AR_BASIC_INT64:
  4867. case AR_BASIC_UINT8:
  4868. case AR_BASIC_UINT16:
  4869. case AR_BASIC_UINT32:
  4870. case AR_BASIC_UINT64:
  4871. switch (rightKind) {
  4872. case AR_BASIC_LITERAL_INT:
  4873. return false;
  4874. }
  4875. break;
  4876. case AR_BASIC_LITERAL_FLOAT:
  4877. switch (rightKind) {
  4878. case AR_BASIC_LITERAL_FLOAT:
  4879. case AR_BASIC_FLOAT16:
  4880. case AR_BASIC_FLOAT32:
  4881. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4882. case AR_BASIC_FLOAT64:
  4883. return false;
  4884. }
  4885. break;
  4886. case AR_BASIC_FLOAT16:
  4887. case AR_BASIC_FLOAT32:
  4888. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  4889. case AR_BASIC_FLOAT64:
  4890. switch (rightKind) {
  4891. case AR_BASIC_LITERAL_FLOAT:
  4892. return false;
  4893. }
  4894. break;
  4895. }
  4896. return true;
  4897. }
  4898. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  4899. {
  4900. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  4901. return 0;
  4902. }
  4903. UINT64 uScore = 0;
  4904. UINT uLSize = GetNumElements(pLType);
  4905. UINT uRSize = GetNumElements(pRType);
  4906. UINT uCompareSize;
  4907. bool bLCast = false;
  4908. bool bRCast = false;
  4909. bool bLIntCast = false;
  4910. bool bRIntCast = false;
  4911. bool bLPromo = false;
  4912. bool bRPromo = false;
  4913. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  4914. if (uCompareSize > uRSize) {
  4915. uCompareSize = uRSize;
  4916. }
  4917. for (UINT i = 0; i < uCompareSize; i++) {
  4918. ArBasicKind LeftElementKind, RightElementKind;
  4919. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  4920. QualType leftSub = GetNthElementType(pLType, i);
  4921. QualType rightSub = GetNthElementType(pRType, i);
  4922. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  4923. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  4924. LeftElementKind = GetTypeElementKind(leftSub);
  4925. RightElementKind = GetTypeElementKind(rightSub);
  4926. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  4927. // information needed is the ShapeKind, EltKind and ObjKind.
  4928. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  4929. bool bCombine;
  4930. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  4931. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  4932. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  4933. ArBasicKind RightObjKind = RightElementKind;
  4934. LeftElementKind = LeftObjKind;
  4935. RightElementKind = RightObjKind;
  4936. if (leftKind != rightKind) {
  4937. bCombine = false;
  4938. }
  4939. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  4940. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  4941. }
  4942. }
  4943. else {
  4944. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  4945. }
  4946. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  4947. bLPromo = true;
  4948. }
  4949. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  4950. bLCast = true;
  4951. }
  4952. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  4953. bLIntCast = true;
  4954. }
  4955. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  4956. bRPromo = true;
  4957. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  4958. bRCast = true;
  4959. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  4960. bRIntCast = true;
  4961. }
  4962. } else {
  4963. bLCast = true;
  4964. bRCast = true;
  4965. }
  4966. }
  4967. #define SCORE_COND(shift, cond) { \
  4968. if (cond) uScore += 1UI64 << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  4969. SCORE_COND(0, uRSize < uLSize);
  4970. SCORE_COND(1, bLPromo);
  4971. SCORE_COND(2, bRPromo);
  4972. SCORE_COND(3, bLIntCast);
  4973. SCORE_COND(4, bRIntCast);
  4974. SCORE_COND(5, bLCast);
  4975. SCORE_COND(6, bRCast);
  4976. SCORE_COND(7, uLSize < uRSize);
  4977. #undef SCORE_COND
  4978. // Make sure our scores fit in a UINT64.
  4979. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  4980. return uScore;
  4981. }
  4982. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  4983. DXASSERT(ics, "otherwise conversion has not been initialized");
  4984. if (!ics->isInitialized()) {
  4985. return 0;
  4986. }
  4987. if (!ics->isStandard()) {
  4988. return SCORE_MAX;
  4989. }
  4990. QualType fromType = ics->Standard.getFromType();
  4991. QualType toType = ics->Standard.getToType(2); // final type
  4992. return ScoreCast(toType, fromType);
  4993. }
  4994. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  4995. // Ignore target version mismatches.
  4996. // in/out considerations have been taken care of by viability.
  4997. // 'this' considerations don't matter without inheritance, other
  4998. // than lookup and viability.
  4999. UINT64 result = 0;
  5000. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  5001. UINT64 score;
  5002. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  5003. if (score == SCORE_MAX) {
  5004. return SCORE_MAX;
  5005. }
  5006. result += score;
  5007. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  5008. if (score == SCORE_MAX) {
  5009. return SCORE_MAX;
  5010. }
  5011. result += score;
  5012. }
  5013. return result;
  5014. }
  5015. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  5016. SourceLocation Loc,
  5017. OverloadCandidateSet& set,
  5018. OverloadCandidateSet::iterator& Best)
  5019. {
  5020. UINT64 bestScore = SCORE_MAX;
  5021. unsigned scoreMatch = 0;
  5022. Best = set.end();
  5023. if (set.size() == 1 && set.begin()->Viable) {
  5024. Best = set.begin();
  5025. return OR_Success;
  5026. }
  5027. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  5028. if (Cand->Viable) {
  5029. UINT64 score = ScoreFunction(Cand);
  5030. if (score != SCORE_MAX) {
  5031. if (score == bestScore) {
  5032. ++scoreMatch;
  5033. } else if (score < bestScore) {
  5034. Best = Cand;
  5035. scoreMatch = 1;
  5036. bestScore = score;
  5037. }
  5038. }
  5039. }
  5040. }
  5041. if (Best == set.end()) {
  5042. return OR_No_Viable_Function;
  5043. }
  5044. if (scoreMatch > 1) {
  5045. Best = set.end();
  5046. return OR_Ambiguous;
  5047. }
  5048. // No need to check for deleted functions to yield OR_Deleted.
  5049. return OR_Success;
  5050. }
  5051. /// <summary>
  5052. /// Initializes the specified <paramref name="initSequence" /> describing how
  5053. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  5054. /// </summary>
  5055. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  5056. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  5057. /// <param name="Args">Arguments to the initialization.</param>
  5058. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  5059. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  5060. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  5061. const InitializedEntity& Entity,
  5062. const InitializationKind& Kind,
  5063. MultiExprArg Args,
  5064. bool TopLevelOfInitList,
  5065. _Inout_ InitializationSequence* initSequence)
  5066. {
  5067. DXASSERT_NOMSG(initSequence != nullptr);
  5068. // In HLSL there are no default initializers, eg float4x4 m();
  5069. if (Kind.getKind() == InitializationKind::IK_Default) {
  5070. return;
  5071. }
  5072. // Value initializers occur for temporaries with empty parens or braces.
  5073. if (Kind.getKind() == InitializationKind::IK_Value) {
  5074. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  5075. SilenceSequenceDiagnostics(initSequence);
  5076. return;
  5077. }
  5078. // If we have a DirectList, we should have a single InitListExprClass argument.
  5079. DXASSERT(
  5080. Kind.getKind() != InitializationKind::IK_DirectList ||
  5081. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  5082. "otherwise caller is passing in incorrect initialization configuration");
  5083. bool isCast = Kind.isCStyleCast();
  5084. QualType destType = Entity.getType();
  5085. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  5086. // Direct initialization occurs for explicit constructor arguments.
  5087. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  5088. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  5089. !Kind.isCStyleOrFunctionalCast()) {
  5090. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  5091. SilenceSequenceDiagnostics(initSequence);
  5092. return;
  5093. }
  5094. bool flatten =
  5095. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  5096. Kind.getKind() == InitializationKind::IK_DirectList ||
  5097. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  5098. if (flatten) {
  5099. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  5100. // array types to adjust the value - we do calculate this as part of type analysis.
  5101. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  5102. FlattenedTypeIterator::ComparisonResult comparisonResult =
  5103. FlattenedTypeIterator::CompareTypesForInit(
  5104. *this, destType, Args,
  5105. Kind.getLocation(), Kind.getLocation());
  5106. if (comparisonResult.IsConvertibleAndEqualLength() ||
  5107. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  5108. {
  5109. initSequence->AddListInitializationStep(destType);
  5110. }
  5111. else
  5112. {
  5113. SourceLocation diagLocation;
  5114. if (Args.size() > 0)
  5115. {
  5116. diagLocation = Args.front()->getLocStart();
  5117. }
  5118. else
  5119. {
  5120. diagLocation = Entity.getDiagLoc();
  5121. }
  5122. m_sema->Diag(diagLocation,
  5123. diag::err_vector_incorrect_num_initializers)
  5124. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  5125. << comparisonResult.LeftCount << comparisonResult.RightCount;
  5126. SilenceSequenceDiagnostics(initSequence);
  5127. }
  5128. }
  5129. else {
  5130. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  5131. Expr* firstArg = Args.front();
  5132. if (IsExpressionBinaryComma(firstArg)) {
  5133. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  5134. }
  5135. ExprResult expr = ExprResult(firstArg);
  5136. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  5137. Sema::CheckedConversionKind::CCK_CStyleCast :
  5138. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  5139. unsigned int msg = 0;
  5140. CastKind castKind;
  5141. CXXCastPath basePath;
  5142. SourceRange range = Kind.getRange();
  5143. ImplicitConversionSequence ics;
  5144. ics.setStandard();
  5145. bool castWorked = TryStaticCastForHLSL(
  5146. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  5147. if (castWorked) {
  5148. if (destType.getCanonicalType() ==
  5149. firstArg->getType().getCanonicalType() &&
  5150. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  5151. initSequence->AddCAssignmentStep(destType);
  5152. } else {
  5153. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  5154. }
  5155. }
  5156. else {
  5157. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  5158. }
  5159. }
  5160. }
  5161. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5162. const QualType& sourceType,
  5163. const QualType& targetType,
  5164. bool explicitConversion)
  5165. {
  5166. DXASSERT_NOMSG(!sourceType.isNull());
  5167. DXASSERT_NOMSG(!targetType.isNull());
  5168. ArTypeInfo sourceTypeInfo;
  5169. ArTypeInfo targetTypeInfo;
  5170. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  5171. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  5172. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  5173. {
  5174. return false;
  5175. }
  5176. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  5177. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  5178. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  5179. !isVecMatTrunc)
  5180. {
  5181. return false;
  5182. }
  5183. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  5184. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  5185. return true;
  5186. }
  5187. // Same struct is eqaul.
  5188. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  5189. sourceType.getCanonicalType().getUnqualifiedType() ==
  5190. targetType.getCanonicalType().getUnqualifiedType()) {
  5191. return true;
  5192. }
  5193. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  5194. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  5195. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  5196. {
  5197. return false;
  5198. }
  5199. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  5200. }
  5201. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5202. const ExprResult& sourceExpr,
  5203. const QualType& targetType,
  5204. bool explicitConversion)
  5205. {
  5206. if (sourceExpr.isInvalid() || targetType.isNull())
  5207. {
  5208. return false;
  5209. }
  5210. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  5211. }
  5212. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  5213. {
  5214. DXASSERT_NOMSG(!type.isNull());
  5215. DXASSERT_NOMSG(count != nullptr);
  5216. *count = 0;
  5217. UINT subCount = 0;
  5218. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  5219. switch (shapeKind)
  5220. {
  5221. case AR_TOBJ_ARRAY:
  5222. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  5223. {
  5224. *count = subCount * GetArraySize(type);
  5225. return true;
  5226. }
  5227. return false;
  5228. case AR_TOBJ_COMPOUND:
  5229. {
  5230. FlattenedTypeIterator it(SourceLocation(), type, *this);
  5231. // Return false for empty struct.
  5232. if (!it.hasCurrentElement())
  5233. return false;
  5234. while (it.hasCurrentElement()) {
  5235. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  5236. if (!isFieldNumeric) {
  5237. return false;
  5238. }
  5239. *count += (subCount * it.getCurrentElementSize());
  5240. it.advanceCurrentElement(it.getCurrentElementSize());
  5241. }
  5242. return true;
  5243. }
  5244. default:
  5245. DXASSERT(false, "unreachable");
  5246. case AR_TOBJ_BASIC:
  5247. case AR_TOBJ_MATRIX:
  5248. case AR_TOBJ_VECTOR:
  5249. *count = GetElementCount(type);
  5250. return IsBasicKindNumeric(GetTypeElementKind(type));
  5251. case AR_TOBJ_OBJECT:
  5252. return false;
  5253. }
  5254. }
  5255. enum MatrixMemberAccessError {
  5256. MatrixMemberAccessError_None, // No errors found.
  5257. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  5258. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  5259. MatrixMemberAccessError_Empty, // No members specified.
  5260. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  5261. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  5262. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5263. };
  5264. static
  5265. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  5266. {
  5267. DXASSERT_NOMSG(memberText != nullptr);
  5268. DXASSERT_NOMSG(value != nullptr);
  5269. if ('0' <= *memberText && *memberText <= '9')
  5270. {
  5271. *value = (*memberText) - '0';
  5272. }
  5273. else
  5274. {
  5275. return MatrixMemberAccessError_BadFormat;
  5276. }
  5277. memberText++;
  5278. return MatrixMemberAccessError_None;
  5279. }
  5280. static
  5281. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  5282. {
  5283. DXASSERT_NOMSG(memberText != nullptr);
  5284. DXASSERT_NOMSG(value != nullptr);
  5285. MatrixMemberAccessPositions result;
  5286. bool zeroBasedDecided = false;
  5287. bool zeroBased = false;
  5288. // Set the output value to invalid to allow early exits when errors are found.
  5289. value->IsValid = 0;
  5290. // Assume this is true until proven otherwise.
  5291. result.IsValid = 1;
  5292. result.Count = 0;
  5293. while (*memberText)
  5294. {
  5295. // Check for a leading underscore.
  5296. if (*memberText != '_')
  5297. {
  5298. return MatrixMemberAccessError_BadFormat;
  5299. }
  5300. ++memberText;
  5301. // Check whether we have an 'm' or a digit.
  5302. if (*memberText == 'm')
  5303. {
  5304. if (zeroBasedDecided && !zeroBased)
  5305. {
  5306. return MatrixMemberAccessError_MixingRefs;
  5307. }
  5308. zeroBased = true;
  5309. zeroBasedDecided = true;
  5310. ++memberText;
  5311. }
  5312. else if (!('0' <= *memberText && *memberText <= '9'))
  5313. {
  5314. return MatrixMemberAccessError_BadFormat;
  5315. }
  5316. else
  5317. {
  5318. if (zeroBasedDecided && zeroBased)
  5319. {
  5320. return MatrixMemberAccessError_MixingRefs;
  5321. }
  5322. zeroBased = false;
  5323. zeroBasedDecided = true;
  5324. }
  5325. // Consume two digits for the position.
  5326. uint32_t rowPosition;
  5327. uint32_t colPosition;
  5328. MatrixMemberAccessError digitError;
  5329. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  5330. {
  5331. return digitError;
  5332. }
  5333. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  5334. {
  5335. return digitError;
  5336. }
  5337. // Look for specific common errors (developer likely mixed up reference style).
  5338. if (zeroBased)
  5339. {
  5340. if (rowPosition == 4 || colPosition == 4)
  5341. {
  5342. return MatrixMemberAccessError_FourInZeroBased;
  5343. }
  5344. }
  5345. else
  5346. {
  5347. if (rowPosition == 0 || colPosition == 0)
  5348. {
  5349. return MatrixMemberAccessError_ZeroInOneBased;
  5350. }
  5351. // SetPosition will use zero-based indices.
  5352. --rowPosition;
  5353. --colPosition;
  5354. }
  5355. if (result.Count == 4)
  5356. {
  5357. return MatrixMemberAccessError_TooManyPositions;
  5358. }
  5359. result.SetPosition(result.Count, rowPosition, colPosition);
  5360. result.Count++;
  5361. }
  5362. if (result.Count == 0)
  5363. {
  5364. return MatrixMemberAccessError_Empty;
  5365. }
  5366. *value = result;
  5367. return MatrixMemberAccessError_None;
  5368. }
  5369. bool HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  5370. Expr& BaseExpr,
  5371. DeclarationName MemberName,
  5372. bool IsArrow,
  5373. SourceLocation OpLoc,
  5374. SourceLocation MemberLoc,
  5375. ExprResult* result)
  5376. {
  5377. DXASSERT_NOMSG(result != nullptr);
  5378. QualType BaseType = BaseExpr.getType();
  5379. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  5380. // Assume failure.
  5381. *result = ExprError();
  5382. if (GetTypeObjectKind(BaseType) != AR_TOBJ_MATRIX)
  5383. {
  5384. return false;
  5385. }
  5386. QualType elementType;
  5387. UINT rowCount, colCount;
  5388. GetRowsAndCols(BaseType, rowCount, colCount);
  5389. elementType = GetMatrixOrVectorElementType(BaseType);
  5390. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  5391. const char *memberText = member->getNameStart();
  5392. MatrixMemberAccessPositions positions;
  5393. MatrixMemberAccessError memberAccessError;
  5394. unsigned msg = 0;
  5395. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  5396. switch (memberAccessError)
  5397. {
  5398. case MatrixMemberAccessError_BadFormat:
  5399. msg = diag::err_hlsl_matrix_member_bad_format;
  5400. break;
  5401. case MatrixMemberAccessError_Empty:
  5402. msg = diag::err_hlsl_matrix_member_empty;
  5403. break;
  5404. case MatrixMemberAccessError_FourInZeroBased:
  5405. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  5406. break;
  5407. case MatrixMemberAccessError_MixingRefs:
  5408. msg = diag::err_hlsl_matrix_member_mixing_refs;
  5409. break;
  5410. case MatrixMemberAccessError_None:
  5411. msg = 0;
  5412. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5413. // Check the position with the type now.
  5414. for (unsigned int i = 0; i < positions.Count; i++)
  5415. {
  5416. uint32_t rowPos, colPos;
  5417. positions.GetPosition(i, &rowPos, &colPos);
  5418. if (rowPos >= rowCount || colPos >= colCount)
  5419. {
  5420. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  5421. break;
  5422. }
  5423. }
  5424. break;
  5425. case MatrixMemberAccessError_TooManyPositions:
  5426. msg = diag::err_hlsl_matrix_member_too_many_positions;
  5427. break;
  5428. case MatrixMemberAccessError_ZeroInOneBased:
  5429. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  5430. break;
  5431. default:
  5432. llvm_unreachable("Unknown MatrixMemberAccessError value");
  5433. }
  5434. if (msg != 0)
  5435. {
  5436. m_sema->Diag(MemberLoc, msg) << memberText;
  5437. // It's possible that it's a simple out-of-bounds condition. In this case,
  5438. // generate the member access expression with the correct arity and continue
  5439. // processing.
  5440. if (!positions.IsValid)
  5441. {
  5442. return true;
  5443. }
  5444. }
  5445. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5446. // Consume elements
  5447. QualType resultType;
  5448. if (positions.Count == 1)
  5449. resultType = elementType;
  5450. else
  5451. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  5452. // Add qualifiers from BaseType.
  5453. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  5454. ExprValueKind VK =
  5455. positions.ContainsDuplicateElements() ? VK_RValue :
  5456. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  5457. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  5458. *result = matrixExpr;
  5459. return true;
  5460. }
  5461. enum VectorMemberAccessError {
  5462. VectorMemberAccessError_None, // No errors found.
  5463. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  5464. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  5465. VectorMemberAccessError_Empty, // No members specified.
  5466. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5467. };
  5468. static
  5469. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  5470. DXASSERT_NOMSG(memberText != nullptr);
  5471. DXASSERT_NOMSG(value != nullptr);
  5472. rgbaStyle = false;
  5473. switch (*memberText) {
  5474. case 'r':
  5475. rgbaStyle = true;
  5476. case 'x':
  5477. *value = 0;
  5478. break;
  5479. case 'g':
  5480. rgbaStyle = true;
  5481. case 'y':
  5482. *value = 1;
  5483. break;
  5484. case 'b':
  5485. rgbaStyle = true;
  5486. case 'z':
  5487. *value = 2;
  5488. break;
  5489. case 'a':
  5490. rgbaStyle = true;
  5491. case 'w':
  5492. *value = 3;
  5493. break;
  5494. default:
  5495. return VectorMemberAccessError_BadFormat;
  5496. }
  5497. memberText++;
  5498. return VectorMemberAccessError_None;
  5499. }
  5500. static
  5501. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  5502. DXASSERT_NOMSG(memberText != nullptr);
  5503. DXASSERT_NOMSG(value != nullptr);
  5504. VectorMemberAccessPositions result;
  5505. bool rgbaStyleDecided = false;
  5506. bool rgbaStyle = false;
  5507. // Set the output value to invalid to allow early exits when errors are found.
  5508. value->IsValid = 0;
  5509. // Assume this is true until proven otherwise.
  5510. result.IsValid = 1;
  5511. result.Count = 0;
  5512. while (*memberText) {
  5513. // Consume one character for the swizzle.
  5514. uint32_t colPosition;
  5515. VectorMemberAccessError digitError;
  5516. bool rgbaStyleTmp = false;
  5517. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  5518. return digitError;
  5519. }
  5520. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  5521. return VectorMemberAccessError_MixingStyles;
  5522. }
  5523. else {
  5524. rgbaStyleDecided = true;
  5525. rgbaStyle = rgbaStyleTmp;
  5526. }
  5527. if (result.Count == 4) {
  5528. return VectorMemberAccessError_TooManyPositions;
  5529. }
  5530. result.SetPosition(result.Count, colPosition);
  5531. result.Count++;
  5532. }
  5533. if (result.Count == 0) {
  5534. return VectorMemberAccessError_Empty;
  5535. }
  5536. *value = result;
  5537. return VectorMemberAccessError_None;
  5538. }
  5539. bool HLSLExternalSource::LookupVectorMemberExprForHLSL(
  5540. Expr& BaseExpr,
  5541. DeclarationName MemberName,
  5542. bool IsArrow,
  5543. SourceLocation OpLoc,
  5544. SourceLocation MemberLoc,
  5545. ExprResult* result) {
  5546. DXASSERT_NOMSG(result != nullptr);
  5547. QualType BaseType = BaseExpr.getType();
  5548. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  5549. // Assume failure.
  5550. *result = ExprError();
  5551. if (GetTypeObjectKind(BaseType) != AR_TOBJ_VECTOR) {
  5552. return false;
  5553. }
  5554. QualType elementType;
  5555. UINT colCount = GetHLSLVecSize(BaseType);
  5556. elementType = GetMatrixOrVectorElementType(BaseType);
  5557. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  5558. const char *memberText = member->getNameStart();
  5559. VectorMemberAccessPositions positions;
  5560. VectorMemberAccessError memberAccessError;
  5561. unsigned msg = 0;
  5562. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  5563. switch (memberAccessError) {
  5564. case VectorMemberAccessError_BadFormat:
  5565. msg = diag::err_hlsl_vector_member_bad_format;
  5566. break;
  5567. case VectorMemberAccessError_Empty:
  5568. msg = diag::err_hlsl_vector_member_empty;
  5569. break;
  5570. case VectorMemberAccessError_MixingStyles:
  5571. msg = diag::err_ext_vector_component_name_mixedsets;
  5572. break;
  5573. case VectorMemberAccessError_None:
  5574. msg = 0;
  5575. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5576. // Check the position with the type now.
  5577. for (unsigned int i = 0; i < positions.Count; i++) {
  5578. uint32_t colPos;
  5579. positions.GetPosition(i, &colPos);
  5580. if (colPos >= colCount) {
  5581. msg = diag::err_hlsl_vector_member_out_of_bounds;
  5582. break;
  5583. }
  5584. }
  5585. break;
  5586. case VectorMemberAccessError_TooManyPositions:
  5587. msg = diag::err_hlsl_vector_member_too_many_positions;
  5588. break;
  5589. default:
  5590. llvm_unreachable("Unknown VectorMemberAccessError value");
  5591. }
  5592. if (msg != 0) {
  5593. m_sema->Diag(MemberLoc, msg) << memberText;
  5594. // It's possible that it's a simple out-of-bounds condition. In this case,
  5595. // generate the member access expression with the correct arity and continue
  5596. // processing.
  5597. if (!positions.IsValid) {
  5598. return true;
  5599. }
  5600. }
  5601. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5602. // Consume elements
  5603. QualType resultType;
  5604. if (positions.Count == 1)
  5605. resultType = elementType;
  5606. else
  5607. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  5608. // Add qualifiers from BaseType.
  5609. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  5610. ExprValueKind VK =
  5611. positions.ContainsDuplicateElements() ? VK_RValue :
  5612. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  5613. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  5614. *result = vectorExpr;
  5615. return true;
  5616. }
  5617. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  5618. DXASSERT_NOMSG(E != nullptr);
  5619. ArBasicKind basic = GetTypeElementKind(E->getType());
  5620. if (!IS_BASIC_PRIMITIVE(basic)) {
  5621. return E;
  5622. }
  5623. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  5624. if (kind != AR_TOBJ_SCALAR) {
  5625. return E;
  5626. }
  5627. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  5628. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  5629. }
  5630. static clang::CastKind ImplicitConversionKindToCastKind(
  5631. clang::ImplicitConversionKind ICK,
  5632. ArBasicKind FromKind,
  5633. ArBasicKind ToKind) {
  5634. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  5635. // based on from/to kinds in order to determine CastKind?
  5636. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  5637. // problem.
  5638. switch (ICK) {
  5639. case ICK_Integral_Promotion:
  5640. case ICK_Integral_Conversion:
  5641. return CK_IntegralCast;
  5642. case ICK_Floating_Promotion:
  5643. case ICK_Floating_Conversion:
  5644. return CK_FloatingCast;
  5645. case ICK_Floating_Integral:
  5646. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  5647. return CK_FloatingToIntegral;
  5648. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  5649. return CK_IntegralToFloating;
  5650. break;
  5651. case ICK_Boolean_Conversion:
  5652. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  5653. return CK_FloatingToBoolean;
  5654. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  5655. return CK_IntegralToBoolean;
  5656. break;
  5657. }
  5658. return CK_Invalid;
  5659. }
  5660. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  5661. switch (CK) {
  5662. case CK_IntegralCast:
  5663. return CK_HLSLCC_IntegralCast;
  5664. case CK_FloatingCast:
  5665. return CK_HLSLCC_FloatingCast;
  5666. case CK_FloatingToIntegral:
  5667. return CK_HLSLCC_FloatingToIntegral;
  5668. case CK_IntegralToFloating:
  5669. return CK_HLSLCC_IntegralToFloating;
  5670. case CK_FloatingToBoolean:
  5671. return CK_HLSLCC_FloatingToBoolean;
  5672. case CK_IntegralToBoolean:
  5673. return CK_HLSLCC_IntegralToBoolean;
  5674. }
  5675. return CK_Invalid;
  5676. }
  5677. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  5678. _In_ clang::Sema* self,
  5679. _In_ clang::Expr* From,
  5680. ArTypeObjectKind FromShape,
  5681. ArBasicKind EltKind)
  5682. {
  5683. clang::CastKind CK = CK_Invalid;
  5684. if (AR_TOBJ_MATRIX == FromShape)
  5685. CK = CK_HLSLMatrixToScalarCast;
  5686. if (AR_TOBJ_VECTOR == FromShape)
  5687. CK = CK_HLSLVectorToScalarCast;
  5688. if (CK_Invalid != CK) {
  5689. return self->ImpCastExprToType(From,
  5690. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  5691. }
  5692. return From;
  5693. }
  5694. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  5695. _In_ clang::Expr* From,
  5696. _In_ clang::QualType targetType,
  5697. _In_ const clang::StandardConversionSequence &SCS,
  5698. _In_ clang::Sema::CheckedConversionKind CCK)
  5699. {
  5700. QualType sourceType = From->getType();
  5701. sourceType = GetStructuralForm(sourceType);
  5702. targetType = GetStructuralForm(targetType);
  5703. ArTypeInfo SourceInfo, TargetInfo;
  5704. CollectInfo(sourceType, &SourceInfo);
  5705. CollectInfo(targetType, &TargetInfo);
  5706. clang::CastKind CK = CK_Invalid;
  5707. QualType intermediateTarget;
  5708. // TODO: construct vector/matrix and component cast expressions
  5709. switch (SCS.Second) {
  5710. case ICK_Flat_Conversion: {
  5711. // TODO: determine how to handle individual component conversions:
  5712. // - have an array of conversions for ComponentConversion in SCS?
  5713. // convert that to an array of casts under a special kind of flat
  5714. // flat conversion node? What do component conversion casts cast
  5715. // from? We don't have a From expression for individiual components.
  5716. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5717. break;
  5718. }
  5719. case ICK_HLSLVector_Splat: {
  5720. // 1. optionally convert from vec1 or mat1x1 to scalar
  5721. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  5722. // 2. optionally convert component type
  5723. if (ICK_Identity != SCS.ComponentConversion) {
  5724. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  5725. if (CK_Invalid != CK) {
  5726. From = m_sema->ImpCastExprToType(From,
  5727. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5728. }
  5729. }
  5730. // 3. splat scalar to final vector or matrix
  5731. CK = CK_Invalid;
  5732. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  5733. CK = CK_HLSLVectorSplat;
  5734. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  5735. CK = CK_HLSLMatrixSplat;
  5736. if (CK_Invalid != CK) {
  5737. From = m_sema->ImpCastExprToType(From,
  5738. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5739. }
  5740. break;
  5741. }
  5742. case ICK_HLSLVector_Scalar: {
  5743. // 1. select vector or matrix component
  5744. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  5745. // 2. optionally convert component type
  5746. if (ICK_Identity != SCS.ComponentConversion) {
  5747. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  5748. if (CK_Invalid != CK) {
  5749. From = m_sema->ImpCastExprToType(From,
  5750. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5751. }
  5752. }
  5753. break;
  5754. }
  5755. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  5756. // can be done with case fall-through, since this is the order in which we want to
  5757. // do the conversion operations.
  5758. case ICK_HLSLVector_Truncation: {
  5759. // 1. dimension truncation
  5760. // vector truncation or matrix truncation?
  5761. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  5762. From = m_sema->ImpCastExprToType(From,
  5763. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  5764. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5765. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  5766. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  5767. // Handle the column to vector case
  5768. From = m_sema->ImpCastExprToType(From,
  5769. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  5770. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5771. } else {
  5772. From = m_sema->ImpCastExprToType(From,
  5773. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  5774. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5775. }
  5776. } else {
  5777. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  5778. }
  5779. }
  5780. __fallthrough;
  5781. case ICK_HLSLVector_Conversion: {
  5782. // 2. Do ShapeKind conversion if necessary
  5783. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  5784. switch (TargetInfo.ShapeKind) {
  5785. case AR_TOBJ_VECTOR:
  5786. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  5787. From = m_sema->ImpCastExprToType(From,
  5788. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  5789. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5790. break;
  5791. case AR_TOBJ_MATRIX:
  5792. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  5793. From = m_sema->ImpCastExprToType(From,
  5794. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  5795. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5796. break;
  5797. case AR_TOBJ_BASIC:
  5798. // Truncation may be followed by cast to scalar
  5799. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  5800. break;
  5801. default:
  5802. DXASSERT(false, "otherwise, invalid casting sequence");
  5803. break;
  5804. }
  5805. }
  5806. // 3. Do component type conversion
  5807. if (ICK_Identity != SCS.ComponentConversion) {
  5808. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  5809. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  5810. CK = ConvertToComponentCastKind(CK);
  5811. if (CK_Invalid != CK) {
  5812. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  5813. }
  5814. }
  5815. break;
  5816. }
  5817. case ICK_Identity:
  5818. // Nothing to do.
  5819. break;
  5820. default:
  5821. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  5822. }
  5823. return From;
  5824. }
  5825. void HLSLExternalSource::GetConversionForm(
  5826. QualType type,
  5827. bool explicitConversion,
  5828. ArTypeInfo* pTypeInfo)
  5829. {
  5830. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  5831. CollectInfo(type, pTypeInfo);
  5832. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  5833. // but that value is only used for pointer conversions.
  5834. // When explicitly converting types complex aggregates can be treated
  5835. // as vectors if they are entirely numeric.
  5836. switch (pTypeInfo->ShapeKind)
  5837. {
  5838. case AR_TOBJ_COMPOUND:
  5839. case AR_TOBJ_ARRAY:
  5840. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  5841. {
  5842. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  5843. }
  5844. else
  5845. {
  5846. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  5847. }
  5848. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  5849. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  5850. break;
  5851. case AR_TOBJ_VECTOR:
  5852. case AR_TOBJ_MATRIX:
  5853. // Convert 1x1 types to scalars.
  5854. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  5855. {
  5856. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  5857. }
  5858. break;
  5859. }
  5860. }
  5861. static
  5862. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  5863. {
  5864. DXASSERT_NOMSG(allowed != nullptr);
  5865. bool applicable = true;
  5866. *allowed = true;
  5867. if (explicitConversion) {
  5868. // (void) non-void
  5869. if (target->isVoidType()) {
  5870. DXASSERT_NOMSG(*allowed);
  5871. }
  5872. // (non-void) void
  5873. else if (source->isVoidType()) {
  5874. *allowed = false;
  5875. }
  5876. else {
  5877. applicable = false;
  5878. }
  5879. }
  5880. else {
  5881. // (void) void
  5882. if (source->isVoidType() && target->isVoidType()) {
  5883. DXASSERT_NOMSG(*allowed);
  5884. }
  5885. // (void) non-void, (non-void) void
  5886. else if (source->isVoidType() || target->isVoidType()) {
  5887. *allowed = false;
  5888. }
  5889. else {
  5890. applicable = false;
  5891. }
  5892. }
  5893. return applicable;
  5894. }
  5895. _Use_decl_annotations_
  5896. bool HLSLExternalSource::CanConvert(
  5897. SourceLocation loc,
  5898. Expr* sourceExpr,
  5899. QualType target,
  5900. bool explicitConversion,
  5901. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  5902. _Inout_opt_ StandardConversionSequence* standard)
  5903. {
  5904. DXASSERT_NOMSG(sourceExpr != nullptr);
  5905. DXASSERT_NOMSG(!target.isNull());
  5906. // Implements the semantics of ArType::CanConvertTo.
  5907. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  5908. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  5909. QualType source = sourceExpr->getType();
  5910. // Convert to an r-value to begin with.
  5911. bool needsLValueToRValue = sourceExpr->isLValue() &&
  5912. !target->isLValueReferenceType() &&
  5913. IsConversionToLessOrEqualElements(source, target, explicitConversion);
  5914. bool targetRef = target->isReferenceType();
  5915. // Initialize the output standard sequence if available.
  5916. if (standard != nullptr) {
  5917. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  5918. standard->setAsIdentityConversion();
  5919. if (needsLValueToRValue) {
  5920. standard->First = ICK_Lvalue_To_Rvalue;
  5921. }
  5922. standard->setFromType(source);
  5923. standard->setAllToTypes(target);
  5924. }
  5925. source = GetStructuralForm(source);
  5926. target = GetStructuralForm(target);
  5927. // Temporary conversion kind tracking which will be used/fixed up at the end
  5928. ImplicitConversionKind Second = ICK_Identity;
  5929. ImplicitConversionKind ComponentConversion = ICK_Identity;
  5930. // Identical types require no conversion.
  5931. if (source == target) {
  5932. Remarks = TYPE_CONVERSION_IDENTICAL;
  5933. goto lSuccess;
  5934. }
  5935. // Trivial cases for void.
  5936. bool allowed;
  5937. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  5938. if (allowed) {
  5939. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  5940. goto lSuccess;
  5941. }
  5942. else {
  5943. return false;
  5944. }
  5945. }
  5946. ArTypeInfo TargetInfo, SourceInfo;
  5947. CollectInfo(target, &TargetInfo);
  5948. CollectInfo(source, &SourceInfo);
  5949. UINT uTSize = TargetInfo.uTotalElts;
  5950. UINT uSSize = SourceInfo.uTotalElts;
  5951. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  5952. // are we missing cases?
  5953. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  5954. return false;
  5955. }
  5956. // Structure cast.
  5957. if (TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY ||
  5958. SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY) {
  5959. if (!explicitConversion && TargetInfo.ShapeKind != SourceInfo.ShapeKind)
  5960. {
  5961. return false;
  5962. }
  5963. const RecordType *targetRT = target->getAsStructureType();
  5964. if (!targetRT)
  5965. targetRT = dyn_cast<RecordType>(target);
  5966. const RecordType *sourceRT = source->getAsStructureType();
  5967. if (!sourceRT)
  5968. sourceRT = dyn_cast<RecordType>(source);
  5969. if (targetRT && sourceRT) {
  5970. RecordDecl *targetRD = targetRT->getDecl();
  5971. RecordDecl *sourceRD = sourceRT->getDecl();
  5972. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  5973. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  5974. if (targetCXXRD && sourceCXXRD) {
  5975. if (targetRD == sourceRD) {
  5976. Second = ICK_Flat_Conversion;
  5977. goto lSuccess;
  5978. }
  5979. if (sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  5980. Second = ICK_Flat_Conversion;
  5981. goto lSuccess;
  5982. }
  5983. } else {
  5984. if (targetRD == sourceRD) {
  5985. Second = ICK_Flat_Conversion;
  5986. goto lSuccess;
  5987. }
  5988. }
  5989. }
  5990. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  5991. BuiltinType::Kind kind = BT->getKind();
  5992. switch (kind) {
  5993. case BuiltinType::Kind::UInt:
  5994. case BuiltinType::Kind::Int:
  5995. case BuiltinType::Kind::Float:
  5996. case BuiltinType::Kind::LitFloat:
  5997. case BuiltinType::Kind::LitInt:
  5998. if (explicitConversion) {
  5999. Second = ICK_Flat_Conversion;
  6000. goto lSuccess;
  6001. }
  6002. break;
  6003. }
  6004. }
  6005. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6006. BuiltinType::Kind kind = BT->getKind();
  6007. switch (kind) {
  6008. case BuiltinType::Kind::UInt:
  6009. case BuiltinType::Kind::Int:
  6010. case BuiltinType::Kind::Float:
  6011. case BuiltinType::Kind::LitFloat:
  6012. case BuiltinType::Kind::LitInt:
  6013. if (explicitConversion) {
  6014. Second = ICK_Flat_Conversion;
  6015. goto lSuccess;
  6016. }
  6017. break;
  6018. }
  6019. }
  6020. FlattenedTypeIterator::ComparisonResult result =
  6021. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  6022. if (!result.CanConvertElements) {
  6023. return false;
  6024. }
  6025. // Only allow scalar to compound or array with explicit cast
  6026. if (result.IsConvertibleAndLeftLonger()) {
  6027. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  6028. return false;
  6029. }
  6030. }
  6031. // Assignment is valid if elements are exactly the same in type and size; if
  6032. // an explicit conversion is being done, we accept converted elements and a
  6033. // longer right-hand sequence.
  6034. if (!explicitConversion &&
  6035. (!result.AreElementsEqual || result.IsRightLonger()))
  6036. {
  6037. return false;
  6038. }
  6039. Second = ICK_Flat_Conversion;
  6040. goto lSuccess;
  6041. }
  6042. // Base type cast.
  6043. //
  6044. // The rules for aggregate conversions are:
  6045. // 1. A scalar can be replicated to any layout.
  6046. // 2. The result of two vectors is the smaller vector.
  6047. // 3. The result of two matrices is the smaller matrix.
  6048. // 4. The result of a vector and a matrix is:
  6049. // a. If the matrix has one row it's a vector-sized
  6050. // piece of the row.
  6051. // b. If the matrix has one column it's a vector-sized
  6052. // piece of the column.
  6053. // c. Otherwise the number of elements in the vector
  6054. // and matrix must match and the result is the vector.
  6055. // 5. The result of a matrix and a vector is similar to #4.
  6056. //
  6057. bool bCheckElt = false;
  6058. switch (TargetInfo.ShapeKind) {
  6059. case AR_TOBJ_BASIC:
  6060. switch (SourceInfo.ShapeKind)
  6061. {
  6062. case AR_TOBJ_BASIC:
  6063. Second = ICK_Identity;
  6064. break;
  6065. case AR_TOBJ_VECTOR:
  6066. if(1 < SourceInfo.uCols)
  6067. Second = ICK_HLSLVector_Truncation;
  6068. else
  6069. Second = ICK_HLSLVector_Scalar;
  6070. break;
  6071. case AR_TOBJ_MATRIX:
  6072. if(1 < SourceInfo.uRows * SourceInfo.uCols)
  6073. Second = ICK_HLSLVector_Truncation;
  6074. else
  6075. Second = ICK_HLSLVector_Scalar;
  6076. break;
  6077. case AR_TOBJ_OBJECT:
  6078. case AR_TOBJ_INTERFACE:
  6079. case AR_TOBJ_POINTER:
  6080. return false;
  6081. }
  6082. bCheckElt = true;
  6083. break;
  6084. case AR_TOBJ_VECTOR:
  6085. switch (SourceInfo.ShapeKind)
  6086. {
  6087. case AR_TOBJ_BASIC:
  6088. // Conversions between scalars and aggregates are always supported.
  6089. Second = ICK_HLSLVector_Splat;
  6090. break;
  6091. case AR_TOBJ_VECTOR:
  6092. if (TargetInfo.uCols > SourceInfo.uCols) {
  6093. if (SourceInfo.uCols == 1) {
  6094. Second = ICK_HLSLVector_Splat;
  6095. } else {
  6096. return false;
  6097. }
  6098. } else if (TargetInfo.uCols < SourceInfo.uCols) {
  6099. Second = ICK_HLSLVector_Truncation;
  6100. } else {
  6101. Second = ICK_Identity;
  6102. }
  6103. break;
  6104. case AR_TOBJ_MATRIX: {
  6105. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6106. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  6107. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  6108. Second = ICK_HLSLVector_Splat;
  6109. } else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  6110. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  6111. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  6112. return false;
  6113. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  6114. Second = ICK_HLSLVector_Truncation;
  6115. else // equalivalent: O == N*M
  6116. Second = ICK_HLSLVector_Conversion;
  6117. } else if (TargetInfo.uCols != SourceComponents) {
  6118. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  6119. return false;
  6120. } else {
  6121. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  6122. Second = ICK_HLSLVector_Conversion;
  6123. }
  6124. break;
  6125. }
  6126. case AR_TOBJ_OBJECT:
  6127. case AR_TOBJ_INTERFACE:
  6128. case AR_TOBJ_POINTER:
  6129. return false;
  6130. }
  6131. bCheckElt = true;
  6132. break;
  6133. case AR_TOBJ_MATRIX: {
  6134. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  6135. switch (SourceInfo.ShapeKind)
  6136. {
  6137. case AR_TOBJ_BASIC:
  6138. // Conversions between scalars and aggregates are always supported.
  6139. Second = ICK_HLSLVector_Splat;
  6140. break;
  6141. case AR_TOBJ_VECTOR: {
  6142. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  6143. // splat: vector<[..], 1> -> matrix<[..], M, N>
  6144. Second = ICK_HLSLVector_Splat;
  6145. } else if (1 == TargetInfo.uRows || 1 == TargetInfo.uCols) {
  6146. // cases for: vector<[..], O> -> matrix<[..], N, M>, where N == 1 or M == 1
  6147. if (TargetComponents > SourceInfo.uCols) // illegal: N*M > O
  6148. return false;
  6149. else if (TargetComponents < SourceInfo.uCols) // truncation: N*M < O
  6150. Second = ICK_HLSLVector_Truncation;
  6151. else // equalivalent: N*M == O
  6152. Second = ICK_HLSLVector_Conversion;
  6153. } else if (TargetComponents != SourceInfo.uCols) {
  6154. // illegal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O != N*M
  6155. return false;
  6156. } else {
  6157. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  6158. Second = ICK_HLSLVector_Conversion;
  6159. }
  6160. break;
  6161. }
  6162. case AR_TOBJ_MATRIX: {
  6163. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6164. if (1 == SourceComponents && TargetComponents != 1) {
  6165. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  6166. Second = ICK_HLSLVector_Splat;
  6167. } else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  6168. return false;
  6169. } else if(TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  6170. Second = ICK_HLSLVector_Truncation;
  6171. } else {
  6172. Second = ICK_Identity;
  6173. }
  6174. break;
  6175. }
  6176. case AR_TOBJ_OBJECT:
  6177. case AR_TOBJ_INTERFACE:
  6178. case AR_TOBJ_POINTER:
  6179. return false;
  6180. }
  6181. bCheckElt = true;
  6182. break;
  6183. }
  6184. case AR_TOBJ_OBJECT:
  6185. // There are no compatible object assignments that aren't
  6186. // from one type to itself, which is already covered.
  6187. DXASSERT(source != target, "otherwise trivial case was not checked by this function");
  6188. return false;
  6189. default:
  6190. DXASSERT_NOMSG(false);
  6191. return false;
  6192. }
  6193. if (bCheckElt)
  6194. {
  6195. bool precisionLoss = false;
  6196. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  6197. GET_BASIC_BITS(TargetInfo.EltKind) <
  6198. GET_BASIC_BITS(SourceInfo.EltKind))
  6199. {
  6200. precisionLoss = true;
  6201. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  6202. }
  6203. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  6204. {
  6205. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  6206. }
  6207. if (SourceInfo.EltKind != TargetInfo.EltKind)
  6208. {
  6209. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  6210. SourceInfo.EltKind == AR_BASIC_UNKNOWN)
  6211. {
  6212. Second = ICK_Flat_Conversion;
  6213. }
  6214. else if (IS_BASIC_BOOL(TargetInfo.EltKind))
  6215. {
  6216. ComponentConversion = ICK_Boolean_Conversion;
  6217. }
  6218. else
  6219. {
  6220. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  6221. if (IS_BASIC_AINT(SourceInfo.EltKind))
  6222. {
  6223. if (targetIsInt)
  6224. {
  6225. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  6226. }
  6227. else
  6228. {
  6229. ComponentConversion = ICK_Floating_Integral;
  6230. }
  6231. }
  6232. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  6233. {
  6234. DXASSERT(IS_BASIC_FLOAT(SourceInfo.EltKind), "otherwise should not be checking element types");
  6235. if (targetIsInt)
  6236. {
  6237. ComponentConversion = ICK_Floating_Integral;
  6238. }
  6239. else
  6240. {
  6241. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  6242. }
  6243. } else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  6244. if (targetIsInt)
  6245. ComponentConversion = ICK_Integral_Conversion;
  6246. else
  6247. ComponentConversion = ICK_Floating_Integral;
  6248. }
  6249. }
  6250. }
  6251. }
  6252. lSuccess:
  6253. if (standard)
  6254. {
  6255. if (sourceExpr->isLValue())
  6256. {
  6257. if (needsLValueToRValue) {
  6258. standard->First = ICK_Lvalue_To_Rvalue;
  6259. } else {
  6260. switch (Second)
  6261. {
  6262. case ICK_NoReturn_Adjustment:
  6263. case ICK_Vector_Conversion:
  6264. case ICK_Vector_Splat:
  6265. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  6266. case ICK_Flat_Conversion:
  6267. case ICK_HLSLVector_Splat:
  6268. standard->First = ICK_Lvalue_To_Rvalue;
  6269. break;
  6270. }
  6271. switch (ComponentConversion)
  6272. {
  6273. case ICK_Integral_Promotion:
  6274. case ICK_Integral_Conversion:
  6275. case ICK_Floating_Promotion:
  6276. case ICK_Floating_Conversion:
  6277. case ICK_Floating_Integral:
  6278. case ICK_Boolean_Conversion:
  6279. standard->First = ICK_Lvalue_To_Rvalue;
  6280. break;
  6281. }
  6282. }
  6283. }
  6284. // Finally fix up the cases for scalar->scalar component conversion, and
  6285. // identity vector/matrix component conversion
  6286. if (ICK_Identity != ComponentConversion) {
  6287. if (Second == ICK_Identity) {
  6288. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  6289. // Scalar to scalar type conversion, use normal mechanism (Second)
  6290. Second = ComponentConversion;
  6291. ComponentConversion = ICK_Identity;
  6292. } else {
  6293. // vector or matrix dimensions are not being changed, but component type
  6294. // is being converted, so change Second to signal the conversion
  6295. Second = ICK_HLSLVector_Conversion;
  6296. }
  6297. }
  6298. }
  6299. standard->Second = Second;
  6300. standard->ComponentConversion = ComponentConversion;
  6301. // For conversion which change to RValue but targeting reference type
  6302. // Hold the conversion to codeGen
  6303. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  6304. standard->First = ICK_Identity;
  6305. standard->Second = ICK_Identity;
  6306. }
  6307. }
  6308. AssignOpt(Remarks, remarks);
  6309. return true;
  6310. }
  6311. Expr* HLSLExternalSource::CastExprToTypeNumeric(Expr* expr, QualType type)
  6312. {
  6313. DXASSERT_NOMSG(expr != nullptr);
  6314. DXASSERT_NOMSG(!type.isNull());
  6315. if (expr->getType() != type) {
  6316. StandardConversionSequence standard;
  6317. if (CanConvert(SourceLocation(), expr, type, /*explicitConversion*/false, nullptr, &standard) &&
  6318. (standard.First != ICK_Identity || !standard.isIdentityConversion())) {
  6319. ExprResult result = m_sema->PerformImplicitConversion(expr, type, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  6320. if (result.isUsable()) {
  6321. return result.get();
  6322. }
  6323. }
  6324. }
  6325. return expr;
  6326. }
  6327. bool HLSLExternalSource::ValidateTypeRequirements(
  6328. SourceLocation loc,
  6329. ArBasicKind elementKind,
  6330. ArTypeObjectKind objectKind,
  6331. bool requiresIntegrals,
  6332. bool requiresNumerics)
  6333. {
  6334. if (requiresIntegrals || requiresNumerics)
  6335. {
  6336. if (!IsObjectKindPrimitiveAggregate(objectKind))
  6337. {
  6338. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  6339. return false;
  6340. }
  6341. }
  6342. if (requiresIntegrals)
  6343. {
  6344. if (!IsBasicKindIntegral(elementKind))
  6345. {
  6346. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  6347. return false;
  6348. }
  6349. }
  6350. else if (requiresNumerics)
  6351. {
  6352. if (!IsBasicKindNumeric(elementKind))
  6353. {
  6354. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  6355. return false;
  6356. }
  6357. }
  6358. return true;
  6359. }
  6360. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  6361. {
  6362. bool isValid = true;
  6363. if (IsBuiltInObjectType(type)) {
  6364. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  6365. isValid = false;
  6366. }
  6367. if (kind == AR_TOBJ_COMPOUND) {
  6368. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  6369. isValid = false;
  6370. }
  6371. return isValid;
  6372. }
  6373. HRESULT HLSLExternalSource::CombineDimensions(QualType leftType, QualType rightType, QualType *resultType)
  6374. {
  6375. UINT leftRows, leftCols;
  6376. UINT rightRows, rightCols;
  6377. GetRowsAndColsForAny(leftType, leftRows, leftCols);
  6378. GetRowsAndColsForAny(rightType, rightRows, rightCols);
  6379. UINT leftTotal = leftRows * leftCols;
  6380. UINT rightTotal = rightRows * rightCols;
  6381. if (rightTotal == 1) {
  6382. *resultType = leftType;
  6383. return S_OK;
  6384. } else if (leftTotal == 1) {
  6385. *resultType = rightType;
  6386. return S_OK;
  6387. } else if (leftRows <= rightRows && leftCols <= rightCols) {
  6388. *resultType = leftType;
  6389. return S_OK;
  6390. } else if (rightRows <= leftRows && rightCols <= leftCols) {
  6391. *resultType = rightType;
  6392. return S_OK;
  6393. } else if ( (1 == leftRows || 1 == leftCols) &&
  6394. (1 == rightRows || 1 == rightCols)) {
  6395. // Handles cases where 1xN or Nx1 matrices are involved possibly mixed with vectors
  6396. if (leftTotal <= rightTotal) {
  6397. *resultType = leftType;
  6398. return S_OK;
  6399. } else {
  6400. *resultType = rightType;
  6401. return S_OK;
  6402. }
  6403. }
  6404. return E_FAIL;
  6405. }
  6406. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  6407. /// <param name="OpLoc">Source location for operator.</param>
  6408. /// <param name="Opc">Kind of binary operator.</param>
  6409. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  6410. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  6411. /// <param name="ResultTy">Result type for operator expression.</param>
  6412. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  6413. /// <param name="CompResultTy">Type of computation result.</param>
  6414. void HLSLExternalSource::CheckBinOpForHLSL(
  6415. SourceLocation OpLoc,
  6416. BinaryOperatorKind Opc,
  6417. ExprResult& LHS,
  6418. ExprResult& RHS,
  6419. QualType& ResultTy,
  6420. QualType& CompLHSTy,
  6421. QualType& CompResultTy)
  6422. {
  6423. // At the start, none of the output types should be valid.
  6424. DXASSERT_NOMSG(ResultTy.isNull());
  6425. DXASSERT_NOMSG(CompLHSTy.isNull());
  6426. DXASSERT_NOMSG(CompResultTy.isNull());
  6427. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  6428. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  6429. // If either expression is invalid to begin with, propagate that.
  6430. if (LHS.isInvalid() || RHS.isInvalid()) {
  6431. return;
  6432. }
  6433. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  6434. // Handle Assign and Comma operators and return
  6435. switch (Opc)
  6436. {
  6437. case BO_AddAssign:
  6438. case BO_AndAssign:
  6439. case BO_DivAssign:
  6440. case BO_MulAssign:
  6441. case BO_RemAssign:
  6442. case BO_ShlAssign:
  6443. case BO_ShrAssign:
  6444. case BO_SubAssign:
  6445. case BO_XorAssign: {
  6446. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  6447. Sema & S);
  6448. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  6449. return;
  6450. }
  6451. } break;
  6452. case BO_Assign: {
  6453. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  6454. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  6455. return;
  6456. }
  6457. bool complained = false;
  6458. ResultTy = LHS.get()->getType();
  6459. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  6460. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  6461. Sema::AssignmentAction::AA_Assigning, &complained)) {
  6462. return;
  6463. }
  6464. StandardConversionSequence standard;
  6465. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  6466. ExplicitConversionFalse, complained, complained, &standard)) {
  6467. return;
  6468. }
  6469. if (RHS.get()->isLValue()) {
  6470. standard.First = ICK_Lvalue_To_Rvalue;
  6471. }
  6472. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  6473. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  6474. return;
  6475. }
  6476. break;
  6477. case BO_Comma:
  6478. // C performs conversions, C++ doesn't but still checks for type completeness.
  6479. // There are also diagnostics for improper comma use.
  6480. // In the HLSL case these cases don't apply or simply aren't surfaced.
  6481. ResultTy = RHS.get()->getType();
  6482. return;
  6483. }
  6484. // Leave this diagnostic for last to emulate fxc behavior.
  6485. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  6486. bool unsupportedBoolLvalue = isCompoundAssignment &&
  6487. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  6488. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  6489. // Turn operand inputs into r-values.
  6490. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  6491. if (!isCompoundAssignment) {
  6492. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  6493. }
  6494. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  6495. if (LHS.isInvalid() || RHS.isInvalid()) {
  6496. return;
  6497. }
  6498. // Promote bool to int now if necessary
  6499. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc) &&
  6500. !isCompoundAssignment) {
  6501. LHS = PromoteToIntIfBool(LHS);
  6502. }
  6503. // Gather type info
  6504. QualType leftType = GetStructuralForm(LHS.get()->getType());
  6505. QualType rightType = GetStructuralForm(RHS.get()->getType());
  6506. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  6507. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  6508. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  6509. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  6510. // Validate type requirements
  6511. {
  6512. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  6513. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  6514. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  6515. return;
  6516. }
  6517. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  6518. return;
  6519. }
  6520. }
  6521. // Promote rhs bool to int if necessary.
  6522. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  6523. RHS = PromoteToIntIfBool(RHS);
  6524. }
  6525. if (unsupportedBoolLvalue) {
  6526. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  6527. return;
  6528. }
  6529. // We don't support binary operators on built-in object types other than assignment or commas.
  6530. {
  6531. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  6532. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  6533. bool isValid;
  6534. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  6535. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  6536. isValid = false;
  6537. }
  6538. if (!isValid) {
  6539. return;
  6540. }
  6541. }
  6542. // We don't support equality comparisons on arrays.
  6543. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  6544. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  6545. return;
  6546. }
  6547. // Combine element types for computation.
  6548. ArBasicKind resultElementKind = leftElementKind;
  6549. {
  6550. if (BinaryOperatorKindIsLogical(Opc)) {
  6551. resultElementKind = AR_BASIC_BOOL;
  6552. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  6553. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  6554. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  6555. return;
  6556. }
  6557. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  6558. (resultElementKind == AR_BASIC_LITERAL_INT ||
  6559. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  6560. rightElementKind != AR_BASIC_LITERAL_INT &&
  6561. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  6562. // For case like 1<<x.
  6563. resultElementKind = AR_BASIC_UINT32;
  6564. }
  6565. // The following combines the selected/combined element kind above with
  6566. // the dimensions that are legal to implicitly cast. This means that
  6567. // element kind may be taken from one side and the dimensions from the
  6568. // other.
  6569. // Legal dimension combinations are identical, splat, and truncation.
  6570. // ResultTy will be set to whichever type can be converted to, if legal,
  6571. // with preference for leftType if both are possible.
  6572. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  6573. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  6574. return;
  6575. }
  6576. // Here, element kind is combined with dimensions for computation type.
  6577. UINT rowCount, colCount;
  6578. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  6579. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  6580. }
  6581. // Perform necessary conversion sequences for LHS and RHS
  6582. if (RHS.get()->getType() != ResultTy) {
  6583. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  6584. }
  6585. if (isCompoundAssignment) {
  6586. bool complained = false;
  6587. StandardConversionSequence standard;
  6588. if (!ValidateCast(OpLoc, RHS.get(), LHS.get()->getType(), ExplicitConversionFalse,
  6589. complained, complained, &standard)) {
  6590. ResultTy = QualType();
  6591. return;
  6592. }
  6593. CompResultTy = ResultTy;
  6594. CompLHSTy = CompResultTy;
  6595. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  6596. // then converts to the result type and then assigns.
  6597. //
  6598. // So int + float promotes the int to float, does a floating-point addition,
  6599. // then the result becomes and int and is assigned.
  6600. ResultTy = LHSTypeAsPossibleLValue;
  6601. } else if (LHS.get()->getType() != ResultTy) {
  6602. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  6603. }
  6604. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  6605. {
  6606. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  6607. // Return bool vector for vector types.
  6608. if (IsVectorType(m_sema, ResultTy)) {
  6609. UINT rowCount, colCount;
  6610. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  6611. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  6612. } else if (IsMatrixType(m_sema, ResultTy)) {
  6613. UINT rowCount, colCount;
  6614. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  6615. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  6616. } else
  6617. ResultTy = m_context->BoolTy.withConst();
  6618. }
  6619. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  6620. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  6621. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  6622. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  6623. return;
  6624. }
  6625. }
  6626. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  6627. if (resultElementKind == AR_BASIC_FLOAT64) {
  6628. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  6629. return;
  6630. }
  6631. }
  6632. }
  6633. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  6634. /// <param name="OpLoc">Source location for operator.</param>
  6635. /// <param name="Opc">Kind of operator.</param>
  6636. /// <param name="InputExpr">Input expression to the operator.</param>
  6637. /// <param name="VK">Value kind for resulting expression.</param>
  6638. /// <param name="OK">Object kind for resulting expression.</param>
  6639. /// <returns>The result type for the expression.</returns>
  6640. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  6641. SourceLocation OpLoc,
  6642. UnaryOperatorKind Opc,
  6643. ExprResult& InputExpr,
  6644. ExprValueKind& VK,
  6645. ExprObjectKind& OK)
  6646. {
  6647. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  6648. // Reject unsupported operators * and &
  6649. switch (Opc) {
  6650. case UO_AddrOf:
  6651. case UO_Deref:
  6652. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  6653. return QualType();
  6654. }
  6655. Expr* expr = InputExpr.get();
  6656. if (expr->isTypeDependent())
  6657. return m_context->DependentTy;
  6658. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  6659. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  6660. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  6661. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  6662. return QualType();
  6663. } else {
  6664. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  6665. if (InputExpr.isInvalid()) return QualType();
  6666. }
  6667. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  6668. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  6669. return QualType();
  6670. }
  6671. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  6672. InputExpr = PromoteToIntIfBool(InputExpr);
  6673. expr = InputExpr.get();
  6674. elementKind = GetTypeElementKind(expr->getType());
  6675. }
  6676. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  6677. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  6678. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  6679. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  6680. return QualType();
  6681. }
  6682. if (Opc == UnaryOperatorKind::UO_Minus) {
  6683. if (IS_BASIC_UINT(Opc)) {
  6684. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  6685. }
  6686. }
  6687. // By default, the result type is the operand type.
  6688. // Logical not however should cast to a bool.
  6689. QualType resultType = expr->getType();
  6690. if (Opc == UnaryOperatorKind::UO_LNot) {
  6691. UINT rowCount, colCount;
  6692. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  6693. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  6694. StandardConversionSequence standard;
  6695. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  6696. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  6697. return QualType();
  6698. }
  6699. // Cast argument.
  6700. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  6701. if (result.isUsable()) {
  6702. InputExpr = result.get();
  6703. }
  6704. }
  6705. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  6706. if (isPrefix) {
  6707. VK = VK_LValue;
  6708. return resultType;
  6709. }
  6710. else {
  6711. VK = VK_RValue;
  6712. return resultType.getUnqualifiedType();
  6713. }
  6714. }
  6715. clang::QualType HLSLExternalSource::CheckVectorConditional(
  6716. _In_ ExprResult &Cond,
  6717. _In_ ExprResult &LHS,
  6718. _In_ ExprResult &RHS,
  6719. _In_ SourceLocation QuestionLoc)
  6720. {
  6721. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  6722. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  6723. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  6724. // If either expression is invalid to begin with, propagate that.
  6725. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  6726. return QualType();
  6727. }
  6728. // Gather type info
  6729. QualType condType = GetStructuralForm(Cond.get()->getType());
  6730. QualType leftType = GetStructuralForm(LHS.get()->getType());
  6731. QualType rightType = GetStructuralForm(RHS.get()->getType());
  6732. ArBasicKind condElementKind = GetTypeElementKind(condType);
  6733. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  6734. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  6735. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  6736. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  6737. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  6738. QualType ResultTy = leftType;
  6739. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  6740. if (!condIsSimple) {
  6741. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  6742. return QualType();
  6743. }
  6744. UINT rowCountCond, colCountCond;
  6745. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  6746. bool leftIsSimple =
  6747. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  6748. leftObjectKind == AR_TOBJ_MATRIX;
  6749. bool rightIsSimple =
  6750. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  6751. rightObjectKind == AR_TOBJ_MATRIX;
  6752. UINT rowCount, colCount;
  6753. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  6754. if (!leftIsSimple || !rightIsSimple) {
  6755. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  6756. if (leftType == rightType) {
  6757. return leftType;
  6758. }
  6759. }
  6760. // NOTE: Limiting this operator to working only on basic numeric types.
  6761. // This is due to extremely limited (and even broken) support for any other case.
  6762. // In the future we may decide to support more cases.
  6763. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  6764. return QualType();
  6765. }
  6766. // Types should be only scalar, vector, or matrix after this point.
  6767. ArBasicKind resultElementKind = leftElementKind;
  6768. // Combine LHS and RHS element types for computation.
  6769. if (leftElementKind != rightElementKind) {
  6770. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  6771. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  6772. return QualType();
  6773. }
  6774. }
  6775. // Combine LHS and RHS dimensions
  6776. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  6777. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  6778. return QualType();
  6779. }
  6780. // If result is scalar, use condition dimensions.
  6781. // Otherwise, condition must either match or is scalar, then use result dimensions
  6782. if (rowCount * colCount == 1) {
  6783. rowCount = rowCountCond;
  6784. colCount = colCountCond;
  6785. }
  6786. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  6787. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  6788. return QualType();
  6789. }
  6790. // Here, element kind is combined with dimensions for result type.
  6791. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  6792. // Cast condition to RValue
  6793. if (Cond.get()->isLValue())
  6794. Cond.set(CreateLValueToRValueCast(Cond.get()));
  6795. // Convert condition component type to bool, using result component dimensions
  6796. if (condElementKind != AR_BASIC_BOOL) {
  6797. Cond = CastExprToTypeNumeric(Cond.get(),
  6798. NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal());
  6799. }
  6800. // Cast LHS/RHS to RValue
  6801. if (LHS.get()->isLValue())
  6802. LHS.set(CreateLValueToRValueCast(LHS.get()));
  6803. if (RHS.get()->isLValue())
  6804. RHS.set(CreateLValueToRValueCast(RHS.get()));
  6805. // TODO: Why isn't vector truncation being reported?
  6806. if (leftType != ResultTy) {
  6807. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  6808. }
  6809. if (rightType != ResultTy) {
  6810. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  6811. }
  6812. return ResultTy;
  6813. }
  6814. // Apply type specifier sign to the given QualType.
  6815. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  6816. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  6817. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  6818. _In_ clang::SourceLocation Loc) {
  6819. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  6820. return type;
  6821. }
  6822. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  6823. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  6824. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  6825. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  6826. return type;
  6827. }
  6828. // check if element type is unsigned and check if such vector exists
  6829. // If not create a new one, Make a QualType of the new kind
  6830. ArBasicKind elementKind = GetTypeElementKind(type);
  6831. // Only ints can have signed/unsigend ty
  6832. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  6833. return type;
  6834. }
  6835. else {
  6836. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  6837. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  6838. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  6839. // Get new vector types for a given TypeSpecifierSign.
  6840. if (objKind == AR_TOBJ_VECTOR) {
  6841. UINT colCount = GetHLSLVecSize(type);
  6842. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  6843. return m_context->getTypeDeclType(qts);
  6844. } else if (objKind == AR_TOBJ_MATRIX) {
  6845. UINT rowCount, colCount;
  6846. GetRowsAndCols(type, rowCount, colCount);
  6847. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  6848. return m_context->getTypeDeclType(qts);
  6849. } else {
  6850. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  6851. return m_scalarTypes[newScalarType];
  6852. }
  6853. }
  6854. }
  6855. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  6856. FunctionTemplateDecl *FunctionTemplate,
  6857. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  6858. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  6859. {
  6860. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  6861. DXASSERT(
  6862. ExplicitTemplateArgs == nullptr ||
  6863. ExplicitTemplateArgs->size() == 0, "otherwise parser failed to reject explicit template argument syntax");
  6864. // Get information about the function we have.
  6865. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  6866. DXASSERT(functionMethod != nullptr,
  6867. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  6868. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  6869. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  6870. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  6871. // Handle subscript overloads.
  6872. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  6873. {
  6874. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  6875. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  6876. if (!findResult.Found())
  6877. {
  6878. // This might be a nested type. Do a lookup on the parent.
  6879. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  6880. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  6881. {
  6882. return Sema::TemplateDeductionResult::TDK_Invalid;
  6883. }
  6884. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  6885. if (!findResult.Found())
  6886. {
  6887. return Sema::TemplateDeductionResult::TDK_Invalid;
  6888. }
  6889. DXASSERT(
  6890. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  6891. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  6892. "otherwise FindStructBasicType should have failed - no other types are allowed");
  6893. objectElement = GetFirstElementTypeFromDecl(
  6894. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  6895. }
  6896. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  6897. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  6898. FunctionTemplate->getCanonicalDecl());
  6899. return Sema::TemplateDeductionResult::TDK_Success;
  6900. }
  6901. // Reject overload lookups that aren't identifier-based.
  6902. if (!FunctionTemplate->getDeclName().isIdentifier())
  6903. {
  6904. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  6905. }
  6906. // Find the table of intrinsics based on the object type.
  6907. const HLSL_INTRINSIC* intrinsics;
  6908. size_t intrinsicCount;
  6909. const char* objectName;
  6910. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  6911. DXASSERT(intrinsics != nullptr,
  6912. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  6913. "or the parser let a user-defined template object through");
  6914. // Look for an intrinsic for which we can match arguments.
  6915. size_t argCount;
  6916. QualType argTypes[g_MaxIntrinsicParamCount + 1];
  6917. StringRef nameIdentifier = FunctionTemplate->getName();
  6918. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  6919. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  6920. while (cursor != end)
  6921. {
  6922. if (!MatchArguments(*cursor, objectElement, Args, argTypes, &argCount))
  6923. {
  6924. ++cursor;
  6925. continue;
  6926. }
  6927. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes, argCount);
  6928. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  6929. FunctionTemplate->getCanonicalDecl());
  6930. if (!IsValidateObjectElement(*cursor, objectElement)) {
  6931. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  6932. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  6933. }
  6934. return Sema::TemplateDeductionResult::TDK_Success;
  6935. }
  6936. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  6937. }
  6938. void HLSLExternalSource::DiagnoseAssignmentResultForHLSL(
  6939. Sema::AssignConvertType ConvTy,
  6940. SourceLocation Loc,
  6941. QualType DstType, QualType SrcType,
  6942. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  6943. _Out_opt_ bool *Complained)
  6944. {
  6945. if (Complained) *Complained = false;
  6946. // No work to do if there is not type change.
  6947. if (DstType == SrcType) {
  6948. return;
  6949. }
  6950. // Don't generate a warning if the user is casting explicitly
  6951. // or if initializing - our initialization handling already emits this.
  6952. if (Action == Sema::AssignmentAction::AA_Casting ||
  6953. Action == Sema::AssignmentAction::AA_Initializing) {
  6954. return;
  6955. }
  6956. ArBasicKind src = BasicTypeForScalarType(SrcType->getCanonicalTypeUnqualified());
  6957. if (src == AR_BASIC_UNKNOWN || src == AR_BASIC_BOOL) {
  6958. return;
  6959. }
  6960. ArBasicKind dst = BasicTypeForScalarType(DstType->getCanonicalTypeUnqualified());
  6961. if (dst == AR_BASIC_UNKNOWN) {
  6962. return;
  6963. }
  6964. bool warnAboutNarrowing = false;
  6965. switch (dst) {
  6966. case AR_BASIC_FLOAT32:
  6967. case AR_BASIC_INT32:
  6968. case AR_BASIC_UINT32:
  6969. case AR_BASIC_FLOAT16:
  6970. warnAboutNarrowing = src == AR_BASIC_FLOAT64;
  6971. break;
  6972. case AR_BASIC_MIN16FLOAT:
  6973. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  6974. break;
  6975. case AR_BASIC_MIN16INT:
  6976. case AR_BASIC_MIN16UINT:
  6977. case AR_BASIC_MIN12INT:
  6978. case AR_BASIC_MIN10FLOAT:
  6979. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  6980. break;
  6981. }
  6982. // fxc errors looked like this:
  6983. // warning X3205: conversion from larger type to smaller, possible loss of data
  6984. if (warnAboutNarrowing) {
  6985. m_sema->Diag(Loc, diag::warn_hlsl_narrowing) << SrcType << DstType;
  6986. AssignOpt(true, Complained);
  6987. }
  6988. }
  6989. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  6990. {
  6991. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  6992. }
  6993. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  6994. QualType DestType,
  6995. Sema::CheckedConversionKind CCK,
  6996. const SourceRange &OpRange, unsigned &msg,
  6997. CastKind &Kind, CXXCastPath &BasePath,
  6998. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  6999. _Inout_opt_ StandardConversionSequence* standard)
  7000. {
  7001. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  7002. bool explicitConversion
  7003. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  7004. QualType sourceType = SrcExpr.get()->getType();
  7005. bool suppressWarnings = explicitConversion || SuppressWarnings;
  7006. SourceLocation loc = OpRange.getBegin();
  7007. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  7008. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  7009. // so do this here until we figure out why this is needed.
  7010. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  7011. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  7012. }
  7013. return true;
  7014. }
  7015. // ValidateCast includes its own error messages.
  7016. msg = 0;
  7017. return false;
  7018. }
  7019. /// <summary>
  7020. /// Checks if a subscript index argument can be initialized from the given expression.
  7021. /// </summary>
  7022. /// <param name="SrcExpr">Source expression used as argument.</param>
  7023. /// <param name="DestType">Parameter type to initialize.</param>
  7024. /// <remarks>
  7025. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  7026. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  7027. /// </remarks>
  7028. ImplicitConversionSequence
  7029. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  7030. clang::QualType DestType) {
  7031. DXASSERT_NOMSG(SrcExpr != nullptr);
  7032. DXASSERT_NOMSG(!DestType.isNull());
  7033. unsigned int msg = 0;
  7034. CastKind kind;
  7035. CXXCastPath path;
  7036. ImplicitConversionSequence sequence;
  7037. sequence.setStandard();
  7038. ExprResult sourceExpr(SrcExpr);
  7039. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  7040. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7041. SrcExpr->getType(), DestType);
  7042. } else if (!TryStaticCastForHLSL(
  7043. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  7044. msg, kind, path, ListInitializationFalse,
  7045. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  7046. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7047. SrcExpr->getType(), DestType);
  7048. }
  7049. return sequence;
  7050. }
  7051. template <typename T>
  7052. static
  7053. bool IsValueInRange(T value, T minValue, T maxValue) {
  7054. return minValue <= value && value <= maxValue;
  7055. }
  7056. #define D3DX_16F_MAX 6.550400e+004 // max value
  7057. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  7058. static
  7059. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  7060. {
  7061. DXASSERT_NOMSG(minValue != nullptr);
  7062. DXASSERT_NOMSG(maxValue != nullptr);
  7063. switch (basicKind) {
  7064. case AR_BASIC_MIN10FLOAT:
  7065. case AR_BASIC_MIN16FLOAT:
  7066. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  7067. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7068. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  7069. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  7070. }
  7071. DXASSERT(false, "unreachable");
  7072. *minValue = 0; *maxValue = 0;
  7073. return;
  7074. }
  7075. static
  7076. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  7077. {
  7078. DXASSERT_NOMSG(maxValue != nullptr);
  7079. switch (basicKind) {
  7080. case AR_BASIC_BOOL: *maxValue = 1; return;
  7081. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  7082. case AR_BASIC_MIN16UINT:
  7083. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  7084. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  7085. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  7086. }
  7087. DXASSERT(false, "unreachable");
  7088. *maxValue = 0;
  7089. return;
  7090. }
  7091. static
  7092. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  7093. {
  7094. DXASSERT_NOMSG(minValue != nullptr);
  7095. DXASSERT_NOMSG(maxValue != nullptr);
  7096. switch (basicKind) {
  7097. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  7098. case AR_BASIC_MIN12INT:
  7099. case AR_BASIC_MIN16INT:
  7100. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  7101. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  7102. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  7103. }
  7104. DXASSERT(false, "unreachable");
  7105. *minValue = 0; *maxValue = 0;
  7106. return;
  7107. }
  7108. static
  7109. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  7110. {
  7111. if (IS_BASIC_FLOAT(basicKind)) {
  7112. double val;
  7113. if (value.isInt()) {
  7114. val = value.getInt().getLimitedValue();
  7115. } else if (value.isFloat()) {
  7116. llvm::APFloat floatValue = value.getFloat();
  7117. if (!floatValue.isFinite()) {
  7118. return false;
  7119. }
  7120. val = value.getFloat().convertToDouble();
  7121. } else {
  7122. return false;
  7123. }
  7124. double minValue, maxValue;
  7125. GetFloatLimits(basicKind, &minValue, &maxValue);
  7126. return IsValueInRange(val, minValue, maxValue);
  7127. }
  7128. else if (IS_BASIC_SINT(basicKind)) {
  7129. if (!value.isInt()) {
  7130. return false;
  7131. }
  7132. int64_t val = value.getInt().getSExtValue();
  7133. int64_t minValue, maxValue;
  7134. GetSignedLimits(basicKind, &minValue, &maxValue);
  7135. return IsValueInRange(val, minValue, maxValue);
  7136. }
  7137. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  7138. if (!value.isInt()) {
  7139. return false;
  7140. }
  7141. uint64_t val = value.getInt().getLimitedValue();
  7142. uint64_t maxValue;
  7143. GetUnsignedLimit(basicKind, &maxValue);
  7144. return IsValueInRange(val, (uint64_t)0, maxValue);
  7145. }
  7146. else {
  7147. return false;
  7148. }
  7149. }
  7150. static
  7151. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  7152. {
  7153. DXASSERT_NOMSG(!targetType.isNull());
  7154. DXASSERT_NOMSG(sourceExpr != nullptr);
  7155. Expr::EvalResult evalResult;
  7156. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  7157. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  7158. return IsValueInBasicRange(targetKind, evalResult.Val);
  7159. }
  7160. }
  7161. return false;
  7162. }
  7163. bool HLSLExternalSource::ValidateCast(
  7164. SourceLocation OpLoc,
  7165. _In_ Expr* sourceExpr,
  7166. QualType target,
  7167. bool explicitConversion,
  7168. bool suppressWarnings,
  7169. bool suppressErrors,
  7170. _Inout_opt_ StandardConversionSequence* standard)
  7171. {
  7172. DXASSERT_NOMSG(sourceExpr != nullptr);
  7173. QualType source = sourceExpr->getType();
  7174. TYPE_CONVERSION_REMARKS remarks;
  7175. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  7176. {
  7177. const bool IsOutputParameter = false;
  7178. //
  7179. // Check whether the lack of explicit-ness matters.
  7180. //
  7181. // Setting explicitForDiagnostics to true in that case will avoid the message
  7182. // saying anything about the implicit nature of the cast, when adding the
  7183. // explicit cast won't make a difference.
  7184. //
  7185. bool explicitForDiagnostics = explicitConversion;
  7186. if (explicitConversion == false)
  7187. {
  7188. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  7189. {
  7190. // Can't convert either way - implicit/explicit doesn't matter.
  7191. explicitForDiagnostics = true;
  7192. }
  7193. }
  7194. if (!suppressErrors)
  7195. {
  7196. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  7197. << explicitForDiagnostics << IsOutputParameter << source << target;
  7198. }
  7199. return false;
  7200. }
  7201. if (!suppressWarnings)
  7202. {
  7203. if (!explicitConversion)
  7204. {
  7205. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  7206. {
  7207. // This is a much more restricted version of the analysis does
  7208. // StandardConversionSequence::getNarrowingKind
  7209. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  7210. {
  7211. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  7212. }
  7213. }
  7214. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  7215. {
  7216. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  7217. }
  7218. }
  7219. }
  7220. return true;
  7221. }
  7222. ////////////////////////////////////////////////////////////////////////////////
  7223. // Functions exported from this translation unit. //
  7224. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  7225. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  7226. SourceLocation OpLoc,
  7227. UnaryOperatorKind Opc,
  7228. ExprResult& InputExpr,
  7229. ExprValueKind& VK,
  7230. ExprObjectKind& OK)
  7231. {
  7232. ExternalSemaSource* externalSource = self.getExternalSource();
  7233. if (externalSource == nullptr) {
  7234. return QualType();
  7235. }
  7236. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7237. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  7238. }
  7239. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  7240. void hlsl::CheckBinOpForHLSL(Sema& self,
  7241. SourceLocation OpLoc,
  7242. BinaryOperatorKind Opc,
  7243. ExprResult& LHS,
  7244. ExprResult& RHS,
  7245. QualType& ResultTy,
  7246. QualType& CompLHSTy,
  7247. QualType& CompResultTy)
  7248. {
  7249. ExternalSemaSource* externalSource = self.getExternalSource();
  7250. if (externalSource == nullptr) {
  7251. return;
  7252. }
  7253. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7254. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  7255. }
  7256. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  7257. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  7258. {
  7259. DXASSERT_NOMSG(Template != nullptr);
  7260. ExternalSemaSource* externalSource = self.getExternalSource();
  7261. if (externalSource == nullptr) {
  7262. return false;
  7263. }
  7264. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7265. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  7266. }
  7267. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  7268. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  7269. FunctionTemplateDecl *FunctionTemplate,
  7270. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7271. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7272. {
  7273. return HLSLExternalSource::FromSema(self)
  7274. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  7275. }
  7276. void hlsl::DiagnoseAssignmentResultForHLSL(Sema* self,
  7277. Sema::AssignConvertType ConvTy,
  7278. SourceLocation Loc,
  7279. QualType DstType, QualType SrcType,
  7280. Expr *SrcExpr, Sema::AssignmentAction Action,
  7281. bool *Complained)
  7282. {
  7283. return HLSLExternalSource::FromSema(self)
  7284. ->DiagnoseAssignmentResultForHLSL(ConvTy, Loc, DstType, SrcType, SrcExpr, Action, Complained);
  7285. }
  7286. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  7287. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  7288. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  7289. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  7290. self->Diag(condExpr->getLocStart(),
  7291. diag::err_hlsl_control_flow_cond_not_scalar)
  7292. << StmtName;
  7293. return;
  7294. }
  7295. condExpr = IC->getSubExpr();
  7296. }
  7297. }
  7298. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  7299. {
  7300. // TODO: handle shorthand cases.
  7301. return left.size() == 0 || right.size() == 0 || left.equals(right);
  7302. }
  7303. void hlsl::DiagnosePackingOffset(
  7304. clang::Sema* self,
  7305. SourceLocation loc,
  7306. clang::QualType type,
  7307. int componentOffset)
  7308. {
  7309. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  7310. if (componentOffset > 0) {
  7311. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  7312. ArBasicKind element = source->GetTypeElementKind(type);
  7313. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  7314. // Only perform some simple validation for now.
  7315. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  7316. int count = GetElementCount(type);
  7317. if (count > (4 - componentOffset)) {
  7318. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  7319. }
  7320. }
  7321. }
  7322. }
  7323. void hlsl::DiagnoseRegisterType(
  7324. clang::Sema* self,
  7325. clang::SourceLocation loc,
  7326. clang::QualType type,
  7327. char registerType)
  7328. {
  7329. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  7330. ArBasicKind element = source->GetTypeElementKind(type);
  7331. StringRef expected("none");
  7332. bool isValid = true;
  7333. bool isWarning = false;
  7334. switch (element)
  7335. {
  7336. case AR_BASIC_BOOL:
  7337. case AR_BASIC_LITERAL_FLOAT:
  7338. case AR_BASIC_FLOAT16:
  7339. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7340. case AR_BASIC_FLOAT32:
  7341. case AR_BASIC_FLOAT64:
  7342. case AR_BASIC_LITERAL_INT:
  7343. case AR_BASIC_INT8:
  7344. case AR_BASIC_UINT8:
  7345. case AR_BASIC_INT16:
  7346. case AR_BASIC_UINT16:
  7347. case AR_BASIC_INT32:
  7348. case AR_BASIC_UINT32:
  7349. case AR_BASIC_INT64:
  7350. case AR_BASIC_UINT64:
  7351. case AR_BASIC_MIN10FLOAT:
  7352. case AR_BASIC_MIN16FLOAT:
  7353. case AR_BASIC_MIN12INT:
  7354. case AR_BASIC_MIN16INT:
  7355. case AR_BASIC_MIN16UINT:
  7356. expected = "'b', 'c', or 'i'";
  7357. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i' ||
  7358. registerType == 'B' || registerType == 'C' || registerType == 'I';
  7359. break;
  7360. case AR_OBJECT_TEXTURE1D:
  7361. case AR_OBJECT_TEXTURE1D_ARRAY:
  7362. case AR_OBJECT_TEXTURE2D:
  7363. case AR_OBJECT_TEXTURE2D_ARRAY:
  7364. case AR_OBJECT_TEXTURE3D:
  7365. case AR_OBJECT_TEXTURECUBE:
  7366. case AR_OBJECT_TEXTURECUBE_ARRAY:
  7367. case AR_OBJECT_TEXTURE2DMS:
  7368. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  7369. expected = "'t' or 's'";
  7370. isValid = registerType == 't' || registerType == 's' ||
  7371. registerType == 'T' || registerType == 'S';
  7372. break;
  7373. case AR_OBJECT_SAMPLER:
  7374. case AR_OBJECT_SAMPLER1D:
  7375. case AR_OBJECT_SAMPLER2D:
  7376. case AR_OBJECT_SAMPLER3D:
  7377. case AR_OBJECT_SAMPLERCUBE:
  7378. case AR_OBJECT_SAMPLERCOMPARISON:
  7379. expected = "'s' or 't'";
  7380. isValid = registerType == 's' || registerType == 't' ||
  7381. registerType == 'S' || registerType == 'T';
  7382. break;
  7383. case AR_OBJECT_BUFFER:
  7384. expected = "'t'";
  7385. isValid = registerType == 't' || registerType == 'T';
  7386. break;
  7387. case AR_OBJECT_POINTSTREAM:
  7388. case AR_OBJECT_LINESTREAM:
  7389. case AR_OBJECT_TRIANGLESTREAM:
  7390. isValid = false;
  7391. isWarning = true;
  7392. break;
  7393. case AR_OBJECT_INPUTPATCH:
  7394. case AR_OBJECT_OUTPUTPATCH:
  7395. isValid = false;
  7396. isWarning = true;
  7397. break;
  7398. case AR_OBJECT_RWTEXTURE1D:
  7399. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  7400. case AR_OBJECT_RWTEXTURE2D:
  7401. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  7402. case AR_OBJECT_RWTEXTURE3D:
  7403. case AR_OBJECT_RWBUFFER:
  7404. expected = "'u'";
  7405. isValid = registerType == 'u' || registerType == 'U';
  7406. break;
  7407. case AR_OBJECT_BYTEADDRESS_BUFFER:
  7408. case AR_OBJECT_STRUCTURED_BUFFER:
  7409. expected = "'t'";
  7410. isValid = registerType == 't' || registerType == 'T';
  7411. break;
  7412. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  7413. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  7414. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  7415. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  7416. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  7417. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  7418. expected = "'u'";
  7419. isValid = registerType == 'u' || registerType == 'U';
  7420. break;
  7421. case AR_OBJECT_CONSTANT_BUFFER:
  7422. expected = "'b'";
  7423. isValid = registerType == 'b' || registerType == 'B';
  7424. break;
  7425. case AR_OBJECT_TEXTURE_BUFFER:
  7426. expected = "'t'";
  7427. isValid = registerType == 't' || registerType == 'T';
  7428. break;
  7429. case AR_OBJECT_ROVBUFFER:
  7430. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  7431. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  7432. case AR_OBJECT_ROVTEXTURE1D:
  7433. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  7434. case AR_OBJECT_ROVTEXTURE2D:
  7435. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  7436. case AR_OBJECT_ROVTEXTURE3D:
  7437. expected = "'u'";
  7438. isValid = registerType == 'u' || registerType == 'U';
  7439. break;
  7440. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  7441. isWarning = true;
  7442. break; // So we don't care what you tried to bind it to
  7443. };
  7444. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  7445. // a warning instead.
  7446. if (!isValid)
  7447. {
  7448. if (isWarning)
  7449. self->Diag(loc, diag::warn_hlsl_incorrect_bind_semantic) << expected;
  7450. else
  7451. self->Diag(loc, diag::err_hlsl_incorrect_bind_semantic) << expected;
  7452. }
  7453. }
  7454. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  7455. Sema& S,
  7456. std::vector<hlsl::UnusualAnnotation *>& annotations)
  7457. {
  7458. bool packoffsetOverriddenReported = false;
  7459. auto && iter = annotations.begin();
  7460. auto && end = annotations.end();
  7461. for (; iter != end; ++iter) {
  7462. switch ((*iter)->getKind()) {
  7463. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  7464. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  7465. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  7466. if (!packoffsetOverriddenReported) {
  7467. auto newIter = iter;
  7468. ++newIter;
  7469. while (newIter != end) {
  7470. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  7471. if (other != nullptr &&
  7472. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  7473. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  7474. packoffsetOverriddenReported = true;
  7475. break;
  7476. }
  7477. ++newIter;
  7478. }
  7479. }
  7480. break;
  7481. }
  7482. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  7483. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  7484. // Check whether this will conflict with other register assignments of the same type.
  7485. auto newIter = iter;
  7486. ++newIter;
  7487. while (newIter != end) {
  7488. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  7489. // Same register bank and profile, but different number.
  7490. if (other != nullptr &&
  7491. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  7492. other->RegisterType == registerAssignment->RegisterType &&
  7493. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  7494. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  7495. // Obvious conflict - report it up front.
  7496. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  7497. }
  7498. ++newIter;
  7499. }
  7500. break;
  7501. }
  7502. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  7503. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  7504. // No common validation to be performed.
  7505. break;
  7506. }
  7507. }
  7508. }
  7509. }
  7510. clang::OverloadingResult
  7511. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  7512. clang::OverloadCandidateSet &set,
  7513. clang::OverloadCandidateSet::iterator &Best) {
  7514. return HLSLExternalSource::FromSema(&S)
  7515. ->GetBestViableFunction(Loc, set, Best);
  7516. }
  7517. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  7518. const InitializedEntity &Entity,
  7519. const InitializationKind &Kind,
  7520. MultiExprArg Args,
  7521. bool TopLevelOfInitList,
  7522. InitializationSequence *initSequence) {
  7523. return HLSLExternalSource::FromSema(self)
  7524. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  7525. }
  7526. bool hlsl::IsConversionToLessOrEqualElements(
  7527. _In_ clang::Sema* self,
  7528. const clang::ExprResult& sourceExpr,
  7529. const clang::QualType& targetType,
  7530. bool explicitConversion)
  7531. {
  7532. return HLSLExternalSource::FromSema(self)
  7533. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  7534. }
  7535. bool hlsl::LookupMatrixMemberExprForHLSL(
  7536. Sema* self,
  7537. Expr& BaseExpr,
  7538. DeclarationName MemberName,
  7539. bool IsArrow,
  7540. SourceLocation OpLoc,
  7541. SourceLocation MemberLoc,
  7542. ExprResult* result)
  7543. {
  7544. return HLSLExternalSource::FromSema(self)
  7545. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  7546. }
  7547. bool hlsl::LookupVectorMemberExprForHLSL(
  7548. Sema* self,
  7549. Expr& BaseExpr,
  7550. DeclarationName MemberName,
  7551. bool IsArrow,
  7552. SourceLocation OpLoc,
  7553. SourceLocation MemberLoc,
  7554. ExprResult* result)
  7555. {
  7556. return HLSLExternalSource::FromSema(self)
  7557. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  7558. }
  7559. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  7560. _In_ clang::Sema* self,
  7561. _In_ clang::Expr* E)
  7562. {
  7563. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  7564. }
  7565. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  7566. QualType DestType,
  7567. Sema::CheckedConversionKind CCK,
  7568. const SourceRange &OpRange, unsigned &msg,
  7569. CastKind &Kind, CXXCastPath &BasePath,
  7570. bool ListInitialization,
  7571. bool SuppressDiagnostics,
  7572. _Inout_opt_ StandardConversionSequence* standard)
  7573. {
  7574. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  7575. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  7576. SuppressDiagnostics, SuppressDiagnostics, standard);
  7577. }
  7578. clang::ExprResult hlsl::PerformHLSLConversion(
  7579. _In_ clang::Sema* self,
  7580. _In_ clang::Expr* From,
  7581. _In_ clang::QualType targetType,
  7582. _In_ const clang::StandardConversionSequence &SCS,
  7583. _In_ clang::Sema::CheckedConversionKind CCK)
  7584. {
  7585. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  7586. }
  7587. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  7588. _In_ clang::Sema* self,
  7589. _In_ clang::Expr* SrcExpr,
  7590. clang::QualType DestType)
  7591. {
  7592. return HLSLExternalSource::FromSema(self)
  7593. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  7594. }
  7595. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  7596. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  7597. {
  7598. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  7599. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  7600. if (hlslSource->Initialize(context)) {
  7601. context.setExternalSource(externalSource);
  7602. }
  7603. }
  7604. ////////////////////////////////////////////////////////////////////////////////
  7605. // FlattenedTypeIterator implementation //
  7606. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  7607. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  7608. m_source(source), m_typeDepth(0), m_loc(loc), m_draining(false), m_springLoaded(false), m_incompleteCount(0)
  7609. {
  7610. if (pushTrackerForType(type, nullptr)) {
  7611. considerLeaf();
  7612. }
  7613. }
  7614. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  7615. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  7616. m_source(source), m_typeDepth(0), m_loc(loc), m_draining(false), m_springLoaded(false), m_incompleteCount(0)
  7617. {
  7618. if (!args.empty()) {
  7619. MultiExprArg::iterator ii = args.begin();
  7620. MultiExprArg::iterator ie = args.end();
  7621. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  7622. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  7623. if (!considerLeaf()) {
  7624. m_typeTrackers.clear();
  7625. }
  7626. }
  7627. }
  7628. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  7629. QualType FlattenedTypeIterator::getCurrentElement() const
  7630. {
  7631. return m_typeTrackers.back().Type;
  7632. }
  7633. /// <summary>Get the number of repeated current elements.</summary>
  7634. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  7635. {
  7636. const FlattenedTypeTracker& back = m_typeTrackers.back();
  7637. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  7638. }
  7639. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  7640. bool FlattenedTypeIterator::hasCurrentElement() const
  7641. {
  7642. return m_typeTrackers.size() > 0;
  7643. }
  7644. /// <summary>Consumes count elements on this iterator.</summary>
  7645. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  7646. {
  7647. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  7648. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  7649. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  7650. if (tracker.IterKind == FK_IncompleteArray)
  7651. {
  7652. tracker.Count += count;
  7653. m_springLoaded = true;
  7654. }
  7655. else
  7656. {
  7657. tracker.Count -= count;
  7658. m_springLoaded = false;
  7659. if (m_typeTrackers.back().Count == 0)
  7660. {
  7661. advanceLeafTracker();
  7662. }
  7663. }
  7664. }
  7665. unsigned int FlattenedTypeIterator::countRemaining()
  7666. {
  7667. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  7668. size_t result = 0;
  7669. while (hasCurrentElement() && !m_springLoaded)
  7670. {
  7671. size_t pending = getCurrentElementSize();
  7672. result += pending;
  7673. advanceCurrentElement(pending);
  7674. }
  7675. return result;
  7676. }
  7677. void FlattenedTypeIterator::advanceLeafTracker()
  7678. {
  7679. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  7680. for (;;)
  7681. {
  7682. consumeLeaf();
  7683. if (m_typeTrackers.empty()) {
  7684. return;
  7685. }
  7686. if (considerLeaf()) {
  7687. return;
  7688. }
  7689. }
  7690. }
  7691. bool FlattenedTypeIterator::considerLeaf()
  7692. {
  7693. if (m_typeTrackers.empty()) {
  7694. return false;
  7695. }
  7696. m_typeDepth++;
  7697. if (m_typeDepth > MaxTypeDepth) {
  7698. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  7699. m_typeTrackers.clear();
  7700. m_typeDepth--;
  7701. return false;
  7702. }
  7703. bool result = false;
  7704. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  7705. switch (tracker.IterKind) {
  7706. case FlattenedIterKind::FK_Expressions:
  7707. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  7708. result = considerLeaf();
  7709. }
  7710. break;
  7711. case FlattenedIterKind::FK_Fields:
  7712. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  7713. result = considerLeaf();
  7714. }
  7715. break;
  7716. case FlattenedIterKind::FK_IncompleteArray:
  7717. m_springLoaded = true; // fall through.
  7718. default:
  7719. case FlattenedIterKind::FK_Simple: {
  7720. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  7721. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  7722. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT) {
  7723. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  7724. result = considerLeaf();
  7725. }
  7726. } else {
  7727. result = true;
  7728. }
  7729. }
  7730. }
  7731. m_typeDepth--;
  7732. return result;
  7733. }
  7734. void FlattenedTypeIterator::consumeLeaf()
  7735. {
  7736. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  7737. for (;;) {
  7738. if (m_typeTrackers.empty()) {
  7739. return;
  7740. }
  7741. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  7742. switch (tracker.IterKind) {
  7743. case FlattenedIterKind::FK_Expressions:
  7744. ++tracker.CurrentExpr;
  7745. if (tracker.CurrentExpr == tracker.EndExpr) {
  7746. m_typeTrackers.pop_back();
  7747. topConsumed = false;
  7748. } else {
  7749. return;
  7750. }
  7751. break;
  7752. case FlattenedIterKind::FK_Fields:
  7753. ++tracker.CurrentField;
  7754. if (tracker.CurrentField == tracker.EndField) {
  7755. m_typeTrackers.pop_back();
  7756. topConsumed = false;
  7757. } else {
  7758. return;
  7759. }
  7760. break;
  7761. case FlattenedIterKind::FK_IncompleteArray:
  7762. if (m_draining) {
  7763. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  7764. m_incompleteCount = tracker.Count;
  7765. m_typeTrackers.pop_back();
  7766. }
  7767. return;
  7768. default:
  7769. case FlattenedIterKind::FK_Simple: {
  7770. m_springLoaded = false;
  7771. if (!topConsumed) {
  7772. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  7773. --tracker.Count;
  7774. }
  7775. else {
  7776. topConsumed = false;
  7777. }
  7778. if (tracker.Count == 0) {
  7779. m_typeTrackers.pop_back();
  7780. } else {
  7781. return;
  7782. }
  7783. }
  7784. }
  7785. }
  7786. }
  7787. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  7788. {
  7789. Expr* e = *expression;
  7790. Stmt::StmtClass expressionClass = e->getStmtClass();
  7791. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  7792. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  7793. if (initExpr->getNumInits() == 0) {
  7794. return false;
  7795. }
  7796. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  7797. MultiExprArg::iterator ii = inits.begin();
  7798. MultiExprArg::iterator ie = inits.end();
  7799. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  7800. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  7801. return true;
  7802. }
  7803. return pushTrackerForType(e->getType(), expression);
  7804. }
  7805. // TODO: improve this to provide a 'peek' at intermediate types,
  7806. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  7807. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  7808. {
  7809. if (type->isVoidType()) {
  7810. return false;
  7811. }
  7812. if (m_firstType.isNull()) {
  7813. m_firstType = type;
  7814. }
  7815. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  7816. QualType elementType;
  7817. unsigned int elementCount;
  7818. const RecordType* recordType;
  7819. RecordDecl::field_iterator fi, fe;
  7820. switch (objectKind)
  7821. {
  7822. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  7823. // TODO: handle multi-dimensional arrays
  7824. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  7825. elementCount = GetArraySize(type);
  7826. if (elementCount == 0) {
  7827. if (type->isIncompleteArrayType()) {
  7828. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  7829. return true;
  7830. }
  7831. return false;
  7832. }
  7833. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  7834. elementType, elementCount, nullptr));
  7835. return true;
  7836. case ArTypeObjectKind::AR_TOBJ_BASIC:
  7837. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  7838. return true;
  7839. case ArTypeObjectKind::AR_TOBJ_COMPOUND:
  7840. recordType = type->getAsStructureType();
  7841. if (recordType == nullptr)
  7842. recordType = dyn_cast<RecordType>(type.getTypePtr());
  7843. fi = recordType->getDecl()->field_begin();
  7844. fe = recordType->getDecl()->field_end();
  7845. // Skip empty struct.
  7846. if (fi == fe)
  7847. return false;
  7848. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  7849. type = (*fi)->getType();
  7850. return true;
  7851. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  7852. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  7853. m_source.GetMatrixOrVectorElementType(type),
  7854. GetElementCount(type), nullptr));
  7855. return true;
  7856. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  7857. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  7858. m_source.GetMatrixOrVectorElementType(type),
  7859. GetHLSLVecSize(type), nullptr));
  7860. return true;
  7861. case ArTypeObjectKind::AR_TOBJ_OBJECT:
  7862. // Object have no sub-types.
  7863. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type.getCanonicalType(), 1, expression));
  7864. return true;
  7865. default:
  7866. DXASSERT(false, "unreachable");
  7867. return false;
  7868. }
  7869. }
  7870. FlattenedTypeIterator::ComparisonResult
  7871. FlattenedTypeIterator::CompareIterators(
  7872. HLSLExternalSource& source,
  7873. SourceLocation loc,
  7874. FlattenedTypeIterator& leftIter,
  7875. FlattenedTypeIterator& rightIter)
  7876. {
  7877. FlattenedTypeIterator::ComparisonResult result;
  7878. result.LeftCount = 0;
  7879. result.RightCount = 0;
  7880. result.AreElementsEqual = true; // Until proven otherwise.
  7881. result.CanConvertElements = true; // Until proven otherwise.
  7882. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  7883. {
  7884. Expr* actualExpr = rightIter.getExprOrNull();
  7885. bool hasExpr = actualExpr != nullptr;
  7886. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  7887. StandardConversionSequence standard;
  7888. ExprResult convertedExpr;
  7889. if (!source.CanConvert(loc,
  7890. hasExpr ? actualExpr : &scratchExpr,
  7891. leftIter.getCurrentElement(),
  7892. ExplicitConversionFalse,
  7893. nullptr,
  7894. &standard)) {
  7895. result.AreElementsEqual = false;
  7896. result.CanConvertElements = false;
  7897. break;
  7898. }
  7899. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  7900. {
  7901. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  7902. leftIter.getCurrentElement(),
  7903. standard,
  7904. Sema::AA_Casting,
  7905. Sema::CCK_ImplicitConversion);
  7906. }
  7907. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  7908. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  7909. {
  7910. result.AreElementsEqual = false;
  7911. }
  7912. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  7913. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  7914. // If we need to apply conversions to the expressions, then advance a single element.
  7915. if (hasExpr && convertedExpr.isUsable()) {
  7916. rightIter.replaceExpr(convertedExpr.get());
  7917. advance = 1;
  7918. }
  7919. leftIter.advanceCurrentElement(advance);
  7920. rightIter.advanceCurrentElement(advance);
  7921. result.LeftCount += advance;
  7922. result.RightCount += advance;
  7923. }
  7924. result.LeftCount += leftIter.countRemaining();
  7925. result.RightCount += rightIter.countRemaining();
  7926. return result;
  7927. }
  7928. FlattenedTypeIterator::ComparisonResult
  7929. FlattenedTypeIterator::CompareTypes(
  7930. HLSLExternalSource& source,
  7931. SourceLocation leftLoc, SourceLocation rightLoc,
  7932. QualType left, QualType right)
  7933. {
  7934. FlattenedTypeIterator leftIter(leftLoc, left, source);
  7935. FlattenedTypeIterator rightIter(rightLoc, right, source);
  7936. return CompareIterators(source, leftLoc, leftIter, rightIter);
  7937. }
  7938. FlattenedTypeIterator::ComparisonResult
  7939. FlattenedTypeIterator::CompareTypesForInit(
  7940. HLSLExternalSource& source, QualType left, MultiExprArg args,
  7941. SourceLocation leftLoc, SourceLocation rightLoc)
  7942. {
  7943. FlattenedTypeIterator leftIter(leftLoc, left, source);
  7944. FlattenedTypeIterator rightIter(rightLoc, args, source);
  7945. return CompareIterators(source, leftLoc, leftIter, rightIter);
  7946. }
  7947. ////////////////////////////////////////////////////////////////////////////////
  7948. // Attribute processing support. //
  7949. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  7950. {
  7951. int64_t value = 0;
  7952. if (Attr.getNumArgs() > index)
  7953. {
  7954. Expr *E = nullptr;
  7955. if (!Attr.isArgExpr(index)) {
  7956. // For case arg is constant variable.
  7957. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  7958. VarDecl *decl = dyn_cast<VarDecl>(S.LookupSingleName(S.TUScope, loc->Ident, loc->Loc, Sema::LookupNameKind::LookupOrdinaryName));
  7959. if (!decl) {
  7960. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  7961. return value;
  7962. }
  7963. Expr *init = decl->getInit();
  7964. if (!init) {
  7965. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  7966. return value;
  7967. }
  7968. E = init;
  7969. } else
  7970. E = Attr.getArgAsExpr(index);
  7971. clang::APValue ArgNum;
  7972. bool displayError = false;
  7973. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  7974. {
  7975. displayError = true;
  7976. }
  7977. else
  7978. {
  7979. if (ArgNum.isInt())
  7980. {
  7981. value = ArgNum.getInt().getSExtValue();
  7982. }
  7983. else if (ArgNum.isFloat())
  7984. {
  7985. llvm::APSInt floatInt;
  7986. bool isPrecise;
  7987. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  7988. {
  7989. value = floatInt.getSExtValue();
  7990. }
  7991. else
  7992. {
  7993. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  7994. }
  7995. }
  7996. else
  7997. {
  7998. displayError = true;
  7999. }
  8000. if (value < 0)
  8001. {
  8002. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8003. }
  8004. }
  8005. if (displayError)
  8006. {
  8007. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  8008. << Attr.getName() << AANT_ArgumentIntegerConstant
  8009. << E->getSourceRange();
  8010. }
  8011. }
  8012. return (int)value;
  8013. }
  8014. // TODO: support float arg directly.
  8015. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  8016. unsigned index = 0) {
  8017. int value = 0;
  8018. if (Attr.getNumArgs() > index) {
  8019. Expr *E = Attr.getArgAsExpr(index);
  8020. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  8021. llvm::APFloat flV = FL->getValue();
  8022. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  8023. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  8024. value = intV.getLimitedValue();
  8025. } else {
  8026. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  8027. value = intV.getLimitedValue();
  8028. }
  8029. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  8030. llvm::APInt intV =
  8031. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  8032. value = intV.getLimitedValue();
  8033. } else {
  8034. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  8035. << Attr.getName();
  8036. }
  8037. }
  8038. return value;
  8039. }
  8040. static Stmt* IgnoreParensAndDecay(Stmt* S)
  8041. {
  8042. for (;;)
  8043. {
  8044. switch (S->getStmtClass())
  8045. {
  8046. case Stmt::ParenExprClass:
  8047. S = cast<ParenExpr>(S)->getSubExpr();
  8048. break;
  8049. case Stmt::ImplicitCastExprClass:
  8050. {
  8051. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  8052. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  8053. castExpr->getCastKind() != CK_NoOp &&
  8054. castExpr->getCastKind() != CK_LValueToRValue)
  8055. {
  8056. return S;
  8057. }
  8058. S = castExpr->getSubExpr();
  8059. }
  8060. break;
  8061. default:
  8062. return S;
  8063. }
  8064. }
  8065. }
  8066. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  8067. {
  8068. DXASSERT_NOMSG(E != nullptr);
  8069. Expr* subscriptExpr = E->getIdx();
  8070. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  8071. if (subscriptExpr == nullptr ||
  8072. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  8073. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  8074. {
  8075. S.Diag(
  8076. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  8077. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  8078. return nullptr;
  8079. }
  8080. return E->getBase();
  8081. }
  8082. static bool IsValidClipPlaneDecl(Decl* D)
  8083. {
  8084. Decl::Kind kind = D->getKind();
  8085. if (kind == Decl::Var)
  8086. {
  8087. VarDecl* varDecl = cast<VarDecl>(D);
  8088. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  8089. varDecl->getType().isConstQualified())
  8090. {
  8091. return false;
  8092. }
  8093. return true;
  8094. }
  8095. else if (kind == Decl::Field)
  8096. {
  8097. return true;
  8098. }
  8099. return false;
  8100. }
  8101. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  8102. {
  8103. Stmt* cursor = E;
  8104. // clip plane expressions are a linear path, so no need to traverse the tree here.
  8105. while (cursor != nullptr)
  8106. {
  8107. bool supported = true;
  8108. cursor = IgnoreParensAndDecay(cursor);
  8109. switch (cursor->getStmtClass())
  8110. {
  8111. case Stmt::ArraySubscriptExprClass:
  8112. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  8113. if (cursor == nullptr)
  8114. {
  8115. // nullptr indicates failure, and the error message has already been printed out
  8116. return nullptr;
  8117. }
  8118. break;
  8119. case Stmt::DeclRefExprClass:
  8120. {
  8121. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  8122. Decl* decl = declRef->getDecl();
  8123. supported = IsValidClipPlaneDecl(decl);
  8124. cursor = supported ? nullptr : cursor;
  8125. }
  8126. break;
  8127. case Stmt::MemberExprClass:
  8128. {
  8129. MemberExpr* member = cast<MemberExpr>(cursor);
  8130. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  8131. cursor = supported ? member->getBase() : cursor;
  8132. }
  8133. break;
  8134. default:
  8135. supported = false;
  8136. break;
  8137. }
  8138. if (!supported)
  8139. {
  8140. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  8141. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  8142. return nullptr;
  8143. }
  8144. }
  8145. // Validate that the type is a float4.
  8146. QualType expressionType = E->getType();
  8147. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  8148. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  8149. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  8150. {
  8151. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  8152. return nullptr;
  8153. }
  8154. return E;
  8155. }
  8156. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  8157. {
  8158. Expr* clipExprs[6];
  8159. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  8160. {
  8161. if (A.getNumArgs() <= index)
  8162. {
  8163. clipExprs[index] = nullptr;
  8164. continue;
  8165. }
  8166. Expr *E = A.getArgAsExpr(index);
  8167. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  8168. }
  8169. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  8170. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  8171. A.getAttributeSpellingListIndex());
  8172. }
  8173. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  8174. {
  8175. int argValue = ValidateAttributeIntArg(S, Attr);
  8176. // Default value is 1.
  8177. if (Attr.getNumArgs() == 0) argValue = 1;
  8178. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  8179. argValue, Attr.getAttributeSpellingListIndex());
  8180. }
  8181. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  8182. {
  8183. Stmt::StmtClass stClass = St->getStmtClass();
  8184. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  8185. {
  8186. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  8187. << Attr.getName();
  8188. }
  8189. }
  8190. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  8191. {
  8192. Stmt::StmtClass stClass = St->getStmtClass();
  8193. if (stClass != Stmt::SwitchStmtClass)
  8194. {
  8195. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  8196. << Attr.getName();
  8197. }
  8198. }
  8199. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  8200. {
  8201. Stmt::StmtClass stClass = St->getStmtClass();
  8202. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  8203. {
  8204. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  8205. << Attr.getName();
  8206. }
  8207. }
  8208. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values)
  8209. {
  8210. // values is an optional comma-separated list of potential values.
  8211. Expr* E = A.getArgAsExpr(0);
  8212. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  8213. {
  8214. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  8215. << A.getName();
  8216. return StringRef();
  8217. }
  8218. StringLiteral* sl = cast<StringLiteral>(E);
  8219. StringRef result = sl->getString();
  8220. // Return result with no additional validation.
  8221. if (values == nullptr)
  8222. {
  8223. return result;
  8224. }
  8225. const char* value = values;
  8226. while (*value != '\0')
  8227. {
  8228. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  8229. // Look for a match.
  8230. const char* argData = result.data();
  8231. size_t argDataLen = result.size();
  8232. while (argDataLen != 0 && *argData == *value && *value)
  8233. {
  8234. ++argData;
  8235. ++value;
  8236. --argDataLen;
  8237. }
  8238. // Match found if every input character matched.
  8239. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  8240. {
  8241. return result;
  8242. }
  8243. // Move to next separator.
  8244. while (*value != '\0' && *value != ',')
  8245. {
  8246. ++value;
  8247. }
  8248. // Move to the start of the next item if any.
  8249. if (*value == ',') value++;
  8250. }
  8251. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  8252. // No match found.
  8253. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  8254. << A.getName() << values;
  8255. return StringRef();
  8256. }
  8257. static
  8258. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  8259. {
  8260. if (D->isFunctionOrFunctionTemplate())
  8261. {
  8262. return true;
  8263. }
  8264. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  8265. return false;
  8266. }
  8267. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  8268. {
  8269. DXASSERT_NOMSG(D != nullptr);
  8270. DXASSERT_NOMSG(!A.isInvalid());
  8271. Attr* declAttr = nullptr;
  8272. Handled = true;
  8273. switch (A.getKind())
  8274. {
  8275. case AttributeList::AT_HLSLIn:
  8276. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  8277. A.getAttributeSpellingListIndex());
  8278. break;
  8279. case AttributeList::AT_HLSLOut:
  8280. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  8281. A.getAttributeSpellingListIndex());
  8282. break;
  8283. case AttributeList::AT_HLSLInOut:
  8284. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  8285. A.getAttributeSpellingListIndex());
  8286. break;
  8287. case AttributeList::AT_HLSLNoInterpolation:
  8288. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  8289. A.getAttributeSpellingListIndex());
  8290. break;
  8291. case AttributeList::AT_HLSLLinear:
  8292. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  8293. A.getAttributeSpellingListIndex());
  8294. break;
  8295. case AttributeList::AT_HLSLNoPerspective:
  8296. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  8297. A.getAttributeSpellingListIndex());
  8298. break;
  8299. case AttributeList::AT_HLSLSample:
  8300. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  8301. A.getAttributeSpellingListIndex());
  8302. break;
  8303. case AttributeList::AT_HLSLCentroid:
  8304. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  8305. A.getAttributeSpellingListIndex());
  8306. break;
  8307. case AttributeList::AT_HLSLPrecise:
  8308. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  8309. A.getAttributeSpellingListIndex());
  8310. break;
  8311. case AttributeList::AT_HLSLShared:
  8312. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  8313. A.getAttributeSpellingListIndex());
  8314. break;
  8315. case AttributeList::AT_HLSLGroupShared:
  8316. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  8317. A.getAttributeSpellingListIndex());
  8318. break;
  8319. case AttributeList::AT_HLSLUniform:
  8320. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  8321. A.getAttributeSpellingListIndex());
  8322. break;
  8323. case AttributeList::AT_HLSLColumnMajor:
  8324. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  8325. A.getAttributeSpellingListIndex());
  8326. break;
  8327. case AttributeList::AT_HLSLRowMajor:
  8328. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  8329. A.getAttributeSpellingListIndex());
  8330. break;
  8331. case AttributeList::AT_HLSLUnorm:
  8332. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  8333. A.getAttributeSpellingListIndex());
  8334. break;
  8335. case AttributeList::AT_HLSLSnorm:
  8336. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  8337. A.getAttributeSpellingListIndex());
  8338. break;
  8339. case AttributeList::AT_HLSLPoint:
  8340. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  8341. A.getAttributeSpellingListIndex());
  8342. break;
  8343. case AttributeList::AT_HLSLLine:
  8344. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  8345. A.getAttributeSpellingListIndex());
  8346. break;
  8347. case AttributeList::AT_HLSLLineAdj:
  8348. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  8349. A.getAttributeSpellingListIndex());
  8350. break;
  8351. case AttributeList::AT_HLSLTriangle:
  8352. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  8353. A.getAttributeSpellingListIndex());
  8354. break;
  8355. case AttributeList::AT_HLSLTriangleAdj:
  8356. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  8357. A.getAttributeSpellingListIndex());
  8358. break;
  8359. case AttributeList::AT_HLSLGloballyCoherent:
  8360. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  8361. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8362. break;
  8363. default:
  8364. Handled = false;
  8365. break;
  8366. }
  8367. if (declAttr != nullptr)
  8368. {
  8369. DXASSERT_NOMSG(Handled);
  8370. D->addAttr(declAttr);
  8371. return;
  8372. }
  8373. Handled = true;
  8374. switch (A.getKind())
  8375. {
  8376. // These apply to statements, not declarations. The warning messages clarify this properly.
  8377. case AttributeList::AT_HLSLUnroll:
  8378. case AttributeList::AT_HLSLAllowUAVCondition:
  8379. case AttributeList::AT_HLSLLoop:
  8380. case AttributeList::AT_HLSLFastOpt:
  8381. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  8382. << A.getName();
  8383. return;
  8384. case AttributeList::AT_HLSLBranch:
  8385. case AttributeList::AT_HLSLFlatten:
  8386. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  8387. << A.getName();
  8388. return;
  8389. case AttributeList::AT_HLSLForceCase:
  8390. case AttributeList::AT_HLSLCall:
  8391. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  8392. << A.getName();
  8393. return;
  8394. // These are the cases that actually apply to declarations.
  8395. case AttributeList::AT_HLSLClipPlanes:
  8396. declAttr = HandleClipPlanes(S, A);
  8397. break;
  8398. case AttributeList::AT_HLSLDomain:
  8399. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  8400. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  8401. break;
  8402. case AttributeList::AT_HLSLEarlyDepthStencil:
  8403. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8404. break;
  8405. case AttributeList::AT_HLSLInstance:
  8406. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  8407. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  8408. break;
  8409. case AttributeList::AT_HLSLMaxTessFactor:
  8410. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  8411. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  8412. break;
  8413. case AttributeList::AT_HLSLNumThreads:
  8414. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  8415. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  8416. A.getAttributeSpellingListIndex());
  8417. break;
  8418. case AttributeList::AT_HLSLRootSignature:
  8419. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  8420. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  8421. A.getAttributeSpellingListIndex());
  8422. break;
  8423. case AttributeList::AT_HLSLOutputControlPoints:
  8424. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  8425. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  8426. break;
  8427. case AttributeList::AT_HLSLOutputTopology:
  8428. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  8429. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  8430. break;
  8431. case AttributeList::AT_HLSLPartitioning:
  8432. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  8433. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  8434. break;
  8435. case AttributeList::AT_HLSLPatchConstantFunc:
  8436. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  8437. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  8438. break;
  8439. case AttributeList::AT_HLSLMaxVertexCount:
  8440. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  8441. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  8442. break;
  8443. default:
  8444. Handled = false;
  8445. return;
  8446. }
  8447. if (declAttr != nullptr)
  8448. {
  8449. DXASSERT_NOMSG(Handled);
  8450. D->addAttr(declAttr);
  8451. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  8452. // and prevent code generation.
  8453. ValidateAttributeTargetIsFunction(S, D, A);
  8454. }
  8455. }
  8456. /// <summary>Processes an attribute for a statement.</summary>
  8457. /// <param name="S">Sema with context.</param>
  8458. /// <param name="St">Statement annotated.</param>
  8459. /// <param name="A">Single parsed attribute to process.</param>
  8460. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  8461. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  8462. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  8463. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  8464. {
  8465. // | Construct | Allowed Attributes |
  8466. // +------------------+--------------------------------------------+
  8467. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  8468. // | if | branch, flatten |
  8469. // | switch | branch, flatten, forcecase, call |
  8470. Attr * result = nullptr;
  8471. Handled = true;
  8472. switch (A.getKind())
  8473. {
  8474. case AttributeList::AT_HLSLUnroll:
  8475. ValidateAttributeOnLoop(S, St, A);
  8476. result = HandleUnrollAttribute(S, A);
  8477. break;
  8478. case AttributeList::AT_HLSLAllowUAVCondition:
  8479. ValidateAttributeOnLoop(S, St, A);
  8480. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  8481. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8482. break;
  8483. case AttributeList::AT_HLSLLoop:
  8484. ValidateAttributeOnLoop(S, St, A);
  8485. result = ::new (S.Context) HLSLLoopAttr(
  8486. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8487. break;
  8488. case AttributeList::AT_HLSLFastOpt:
  8489. ValidateAttributeOnLoop(S, St, A);
  8490. result = ::new (S.Context) HLSLFastOptAttr(
  8491. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8492. break;
  8493. case AttributeList::AT_HLSLBranch:
  8494. ValidateAttributeOnSwitchOrIf(S, St, A);
  8495. result = ::new (S.Context) HLSLBranchAttr(
  8496. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8497. break;
  8498. case AttributeList::AT_HLSLFlatten:
  8499. ValidateAttributeOnSwitchOrIf(S, St, A);
  8500. result = ::new (S.Context) HLSLFlattenAttr(
  8501. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8502. break;
  8503. case AttributeList::AT_HLSLForceCase:
  8504. ValidateAttributeOnSwitch(S, St, A);
  8505. result = ::new (S.Context) HLSLForceCaseAttr(
  8506. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8507. break;
  8508. case AttributeList::AT_HLSLCall:
  8509. ValidateAttributeOnSwitch(S, St, A);
  8510. result = ::new (S.Context) HLSLCallAttr(
  8511. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  8512. break;
  8513. default:
  8514. Handled = false;
  8515. break;
  8516. }
  8517. return result;
  8518. }
  8519. ////////////////////////////////////////////////////////////////////////////////
  8520. // Implementation of Sema members. //
  8521. Decl* Sema::ActOnStartHLSLBuffer(
  8522. Scope* bufferScope,
  8523. bool cbuffer, SourceLocation KwLoc,
  8524. IdentifierInfo *Ident, SourceLocation IdentLoc,
  8525. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  8526. SourceLocation LBrace)
  8527. {
  8528. // For anonymous namespace, take the location of the left brace.
  8529. SourceLocation Loc = Ident ? IdentLoc : LBrace;
  8530. DeclContext* lexicalParent = getCurLexicalContext();
  8531. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  8532. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  8533. Ident, IdentLoc, BufferAttributes, LBrace);
  8534. // Keep track of the currently active buffer.
  8535. HLSLBuffers.push_back(result);
  8536. // Validate unusual annotations and emit diagnostics.
  8537. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  8538. auto && unusualIter = BufferAttributes.begin();
  8539. auto && unusualEnd = BufferAttributes.end();
  8540. char expectedRegisterType = cbuffer ? 'b' : 't';
  8541. for (; unusualIter != unusualEnd; ++unusualIter) {
  8542. switch ((*unusualIter)->getKind()) {
  8543. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8544. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  8545. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  8546. break;
  8547. }
  8548. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8549. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  8550. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  8551. Diag(registerAssignment->Loc, cbuffer ? diag::err_hlsl_unsupported_cbuffer_register :
  8552. diag::err_hlsl_unsupported_tbuffer_register);
  8553. } else if (registerAssignment->ShaderProfile.size() > 0) {
  8554. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  8555. }
  8556. break;
  8557. }
  8558. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8559. // Ignore semantic declarations.
  8560. break;
  8561. }
  8562. }
  8563. }
  8564. PushOnScopeChains(result, bufferScope);
  8565. PushDeclContext(bufferScope, result);
  8566. ActOnDocumentableDecl(result);
  8567. return result;
  8568. }
  8569. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  8570. {
  8571. DXASSERT_NOMSG(Dcl != nullptr);
  8572. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  8573. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  8574. HLSLBuffers.pop_back();
  8575. PopDeclContext();
  8576. }
  8577. Decl* Sema::getActiveHLSLBuffer() const
  8578. {
  8579. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  8580. }
  8581. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  8582. DeclGroupPtrTy &dcl, bool iscbuf) {
  8583. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  8584. HLSLBuffers.pop_back();
  8585. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  8586. Decl *decl = dcl.get().getSingleDecl();
  8587. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  8588. IdentifierInfo *Ident = namedDecl->getIdentifier();
  8589. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  8590. SourceLocation Loc = decl->getLocation();
  8591. // Prevent array type in template. The only way to specify an array in the template type
  8592. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  8593. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  8594. QualType declType = cast<VarDecl>(namedDecl)->getType();
  8595. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  8596. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  8597. declType = arrayType->getElementType();
  8598. }
  8599. if (declType->isArrayType()) {
  8600. Diag(Loc, diag::err_hlsl_typeintemplateargument) << "array";
  8601. return nullptr;
  8602. }
  8603. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  8604. DeclContext *lexicalParent = getCurLexicalContext();
  8605. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  8606. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  8607. KwLoc, Ident, Loc, hlslAttrs, Loc);
  8608. // set relation
  8609. namedDecl->setDeclContext(result);
  8610. result->addDecl(namedDecl);
  8611. // move attribute from constant to constant buffer
  8612. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  8613. namedDecl->setUnusualAnnotations(hlslAttrs);
  8614. return result;
  8615. }
  8616. bool Sema::IsOnHLSLBufferView() {
  8617. // nullptr will not pushed for cbuffer.
  8618. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  8619. }
  8620. void Sema::ActOnStartHLSLBufferView() {
  8621. // Push nullptr to mark HLSLBufferView.
  8622. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  8623. HLSLBuffers.emplace_back(nullptr);
  8624. }
  8625. HLSLBufferDecl::HLSLBufferDecl(
  8626. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  8627. IdentifierInfo *Id, SourceLocation IdLoc,
  8628. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  8629. SourceLocation LBrace)
  8630. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  8631. DeclContext(Decl::HLSLBuffer), IsCBuffer(cbuffer),
  8632. IsConstantBufferView(cbufferView), KwLoc(KwLoc), LBraceLoc(LBrace) {
  8633. if (!BufferAttributes.empty()) {
  8634. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  8635. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  8636. }
  8637. }
  8638. HLSLBufferDecl *
  8639. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  8640. bool constantbuffer, SourceLocation KwLoc,
  8641. IdentifierInfo *Id, SourceLocation IdLoc,
  8642. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  8643. SourceLocation LBrace) {
  8644. DeclContext *DC = C.getTranslationUnitDecl();
  8645. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  8646. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  8647. if (DC != lexicalParent) {
  8648. result->setLexicalDeclContext(lexicalParent);
  8649. }
  8650. return result;
  8651. }
  8652. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  8653. assert(NewDecl != nullptr);
  8654. if (!getLangOpts().HLSL) {
  8655. return;
  8656. }
  8657. if (!D.UnusualAnnotations.empty()) {
  8658. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  8659. getASTContext(), D.UnusualAnnotations.data(),
  8660. D.UnusualAnnotations.size()));
  8661. D.UnusualAnnotations.clear();
  8662. }
  8663. }
  8664. /// Checks whether a usage attribute is compatible with those seen so far and
  8665. /// maintains history.
  8666. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  8667. bool &usageOut) {
  8668. switch (kind) {
  8669. case AttributeList::AT_HLSLIn:
  8670. if (usageIn)
  8671. return false;
  8672. usageIn = true;
  8673. break;
  8674. case AttributeList::AT_HLSLOut:
  8675. if (usageOut)
  8676. return false;
  8677. usageOut = true;
  8678. break;
  8679. default:
  8680. assert(kind == AttributeList::AT_HLSLInOut);
  8681. if (usageOut || usageIn)
  8682. return false;
  8683. usageIn = usageOut = true;
  8684. break;
  8685. }
  8686. return true;
  8687. }
  8688. // Diagnose valid/invalid modifiers for HLSL.
  8689. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC,
  8690. TypeSourceInfo *TInfo, bool isParameter) {
  8691. assert(getLangOpts().HLSL &&
  8692. "otherwise this is called without checking language first");
  8693. // NOTE: some tests may declare templates.
  8694. if (DC->isNamespace() || DC->isDependentContext()) return true;
  8695. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  8696. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  8697. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  8698. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  8699. bool result = true;
  8700. bool isTypedef = storage == DeclSpec::SCS_typedef;
  8701. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  8702. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  8703. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  8704. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  8705. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  8706. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  8707. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  8708. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  8709. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  8710. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  8711. assert(
  8712. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  8713. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  8714. (isParameter ? 1 : 0))
  8715. && "exactly one type of declarator is being processed");
  8716. // qt/pType captures either the type being modified, or the return type in the
  8717. // case of a function (or method).
  8718. QualType qt = TInfo->getType();
  8719. const Type* pType = qt.getTypePtrOrNull();
  8720. // Early checks - these are not simple attribution errors, but constructs that
  8721. // are fundamentally unsupported,
  8722. // and so we avoid errors that might indicate they can be repaired.
  8723. if (DC->isRecord()) {
  8724. unsigned int nestedDiagId = 0;
  8725. if (isTypedef) {
  8726. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  8727. }
  8728. if (nestedDiagId) {
  8729. Diag(D.getLocStart(), nestedDiagId);
  8730. D.setInvalidType();
  8731. return false;
  8732. }
  8733. }
  8734. const char* declarationType =
  8735. (isLocalVar) ? "local variable" :
  8736. (isTypedef) ? "typedef" :
  8737. (isFunction) ? "function" :
  8738. (isMethod) ? "method" :
  8739. (isGlobal) ? "global variable" :
  8740. (isParameter) ? "parameter" :
  8741. (isField) ? "field" : "<unknown>";
  8742. if (pType && D.isFunctionDeclarator()) {
  8743. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  8744. if (pFP) {
  8745. qt = pFP->getReturnType();
  8746. pType = qt.getTypePtrOrNull();
  8747. }
  8748. }
  8749. // Check for deprecated effect object type here, warn, and invalidate decl
  8750. bool bDeprecatedEffectObject = false;
  8751. bool bIsObject = false;
  8752. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  8753. bIsObject = true;
  8754. if (bDeprecatedEffectObject) {
  8755. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  8756. D.setInvalidType();
  8757. return false;
  8758. }
  8759. // Add methods if not ready.
  8760. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  8761. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  8762. } else if (qt->isArrayType()) {
  8763. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  8764. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  8765. // Add methods if not ready.
  8766. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  8767. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  8768. }
  8769. }
  8770. if (isExtern) {
  8771. if (!(isFunction || isGlobal)) {
  8772. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  8773. << declarationType;
  8774. result = false;
  8775. }
  8776. }
  8777. if (isStatic) {
  8778. if (!(isLocalVar || isGlobal || isFunction || isMethod)) {
  8779. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  8780. << declarationType;
  8781. result = false;
  8782. }
  8783. }
  8784. if (isVolatile) {
  8785. if (!(isLocalVar || isTypedef)) {
  8786. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  8787. << declarationType;
  8788. result = false;
  8789. }
  8790. }
  8791. if (isConst) {
  8792. if (isField) {
  8793. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  8794. << declarationType;
  8795. result = false;
  8796. }
  8797. }
  8798. if (hasSignSpec) {
  8799. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  8800. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  8801. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  8802. // vectors or matrices can only have unsigned integer types.
  8803. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  8804. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  8805. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  8806. << g_ArBasicTypeNames[basicKind];
  8807. result = false;
  8808. }
  8809. }
  8810. else {
  8811. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  8812. result = false;
  8813. }
  8814. }
  8815. // Validate attributes
  8816. clang::AttributeList
  8817. *pPrecise = nullptr,
  8818. *pShared = nullptr,
  8819. *pGroupShared = nullptr,
  8820. *pUniform = nullptr,
  8821. *pUsage = nullptr,
  8822. *pNoInterpolation = nullptr,
  8823. *pLinear = nullptr,
  8824. *pNoPerspective = nullptr,
  8825. *pSample = nullptr,
  8826. *pCentroid = nullptr,
  8827. *pAnyLinear = nullptr, // first linear attribute found
  8828. *pTopology = nullptr;
  8829. bool usageIn = false;
  8830. bool usageOut = false;
  8831. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  8832. pAttr != NULL; pAttr = pAttr->getNext()) {
  8833. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  8834. continue;
  8835. switch (pAttr->getKind()) {
  8836. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  8837. pPrecise = pAttr;
  8838. break;
  8839. case AttributeList::AT_HLSLShared:
  8840. if (!isGlobal) {
  8841. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8842. << pAttr->getName() << declarationType << pAttr->getRange();
  8843. result = false;
  8844. }
  8845. if (isStatic) {
  8846. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  8847. << "'static'" << pAttr->getName() << declarationType
  8848. << pAttr->getRange();
  8849. result = false;
  8850. }
  8851. pShared = pAttr;
  8852. break;
  8853. case AttributeList::AT_HLSLGroupShared:
  8854. if (!isGlobal) {
  8855. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8856. << pAttr->getName() << declarationType << pAttr->getRange();
  8857. result = false;
  8858. }
  8859. if (isExtern) {
  8860. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  8861. << "'extern'" << pAttr->getName() << declarationType
  8862. << pAttr->getRange();
  8863. result = false;
  8864. }
  8865. pGroupShared = pAttr;
  8866. break;
  8867. case AttributeList::AT_HLSLGloballyCoherent:
  8868. if (!bIsObject) {
  8869. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8870. << pAttr->getName() << "non-UAV type";
  8871. result = false;
  8872. }
  8873. break;
  8874. case AttributeList::AT_HLSLUniform:
  8875. if (!(isGlobal || isParameter)) {
  8876. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8877. << pAttr->getName() << declarationType << pAttr->getRange();
  8878. result = false;
  8879. }
  8880. if (isStatic) {
  8881. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  8882. << "'static'" << pAttr->getName() << declarationType
  8883. << pAttr->getRange();
  8884. result = false;
  8885. }
  8886. pUniform = pAttr;
  8887. break;
  8888. case AttributeList::AT_HLSLIn:
  8889. case AttributeList::AT_HLSLOut:
  8890. case AttributeList::AT_HLSLInOut:
  8891. if (!isParameter) {
  8892. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  8893. << pAttr->getName() << pAttr->getRange();
  8894. result = false;
  8895. }
  8896. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  8897. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  8898. << pAttr->getName() << pAttr->getRange();
  8899. result = false;
  8900. }
  8901. pUsage = pAttr;
  8902. break;
  8903. case AttributeList::AT_HLSLNoInterpolation:
  8904. if (!(isParameter || isField || isFunction)) {
  8905. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8906. << pAttr->getName() << declarationType << pAttr->getRange();
  8907. result = false;
  8908. }
  8909. if (pNoInterpolation) {
  8910. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  8911. << pAttr->getName() << pAttr->getRange();
  8912. }
  8913. pNoInterpolation = pAttr;
  8914. break;
  8915. case AttributeList::AT_HLSLLinear:
  8916. case AttributeList::AT_HLSLNoPerspective:
  8917. case AttributeList::AT_HLSLSample:
  8918. case AttributeList::AT_HLSLCentroid:
  8919. if (!(isParameter || isField || isFunction)) {
  8920. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8921. << pAttr->getName() << declarationType << pAttr->getRange();
  8922. result = false;
  8923. }
  8924. if (nullptr == pAnyLinear)
  8925. pAnyLinear = pAttr;
  8926. switch (pAttr->getKind()) {
  8927. case AttributeList::AT_HLSLLinear:
  8928. if (pLinear) {
  8929. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  8930. << pAttr->getName() << pAttr->getRange();
  8931. }
  8932. pLinear = pAttr;
  8933. break;
  8934. case AttributeList::AT_HLSLNoPerspective:
  8935. if (pNoPerspective) {
  8936. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  8937. << pAttr->getName() << pAttr->getRange();
  8938. }
  8939. pNoPerspective = pAttr;
  8940. break;
  8941. case AttributeList::AT_HLSLSample:
  8942. if (pSample) {
  8943. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  8944. << pAttr->getName() << pAttr->getRange();
  8945. }
  8946. pSample = pAttr;
  8947. break;
  8948. case AttributeList::AT_HLSLCentroid:
  8949. if (pCentroid) {
  8950. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  8951. << pAttr->getName() << pAttr->getRange();
  8952. }
  8953. pCentroid = pAttr;
  8954. break;
  8955. }
  8956. break;
  8957. case AttributeList::AT_HLSLPoint:
  8958. case AttributeList::AT_HLSLLine:
  8959. case AttributeList::AT_HLSLLineAdj:
  8960. case AttributeList::AT_HLSLTriangle:
  8961. case AttributeList::AT_HLSLTriangleAdj:
  8962. if (!(isParameter)) {
  8963. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  8964. << pAttr->getName() << declarationType << pAttr->getRange();
  8965. result = false;
  8966. }
  8967. if (pTopology) {
  8968. if (pTopology->getKind() == pAttr->getKind()) {
  8969. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  8970. << pAttr->getName() << pAttr->getRange();
  8971. } else {
  8972. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  8973. << pAttr->getName() << pTopology->getName()
  8974. << declarationType << pAttr->getRange();
  8975. result = false;
  8976. }
  8977. }
  8978. pTopology = pAttr;
  8979. break;
  8980. default:
  8981. break;
  8982. }
  8983. }
  8984. if (pNoInterpolation && pAnyLinear) {
  8985. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  8986. << pNoInterpolation->getName() << pAnyLinear->getName()
  8987. << declarationType << pNoInterpolation->getRange();
  8988. result = false;
  8989. }
  8990. if (pSample && pCentroid) {
  8991. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  8992. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  8993. }
  8994. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  8995. pNoInterpolation ? pNoInterpolation : pTopology);
  8996. if (pUniform && pNonUniformAttr) {
  8997. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  8998. << pNonUniformAttr->getName()
  8999. << pUniform->getName() << declarationType << pUniform->getRange();
  9000. result = false;
  9001. }
  9002. if (pAnyLinear && pTopology) {
  9003. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  9004. << pTopology->getName()
  9005. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  9006. result = false;
  9007. }
  9008. if (pNoInterpolation && pTopology) {
  9009. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  9010. << pTopology->getName()
  9011. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  9012. result = false;
  9013. }
  9014. if (pUniform && pUsage) {
  9015. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  9016. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  9017. << pUsage->getName() << pUniform->getName() << declarationType
  9018. << pUniform->getRange();
  9019. result = false;
  9020. }
  9021. }
  9022. // Validate unusual annotations.
  9023. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  9024. auto && unusualIter = D.UnusualAnnotations.begin();
  9025. auto && unusualEnd = D.UnusualAnnotations.end();
  9026. for (; unusualIter != unusualEnd; ++unusualIter) {
  9027. switch ((*unusualIter)->getKind()) {
  9028. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9029. hlsl::ConstantPacking *constantPacking =
  9030. cast<hlsl::ConstantPacking>(*unusualIter);
  9031. if (!isGlobal || HLSLBuffers.size() == 0) {
  9032. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  9033. continue;
  9034. }
  9035. if (constantPacking->ComponentOffset > 0) {
  9036. // Validate that this will fit.
  9037. if (!qt.isNull()) {
  9038. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  9039. constantPacking->ComponentOffset);
  9040. }
  9041. }
  9042. break;
  9043. }
  9044. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9045. hlsl::RegisterAssignment *registerAssignment =
  9046. cast<hlsl::RegisterAssignment>(*unusualIter);
  9047. if (registerAssignment->IsValid) {
  9048. if (!qt.isNull()) {
  9049. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  9050. registerAssignment->RegisterType);
  9051. }
  9052. }
  9053. break;
  9054. }
  9055. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9056. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  9057. if (isTypedef || isLocalVar) {
  9058. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  9059. << "semantic" << declarationType;
  9060. }
  9061. break;
  9062. }
  9063. }
  9064. }
  9065. if (!result) {
  9066. D.setInvalidType();
  9067. }
  9068. return result;
  9069. }
  9070. static QualType getUnderlyingType(QualType Type)
  9071. {
  9072. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  9073. {
  9074. if (const TypedefNameDecl* pDecl = TD->getDecl())
  9075. Type = pDecl->getUnderlyingType();
  9076. else
  9077. break;
  9078. }
  9079. return Type;
  9080. }
  9081. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  9082. /// <param name="self">Sema with context.</param>
  9083. /// <param name="type">QualType to inspect.</param>
  9084. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  9085. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  9086. void hlsl::GetHLSLAttributedTypes(
  9087. _In_ clang::Sema* self,
  9088. clang::QualType type,
  9089. _Inout_opt_ const clang::AttributedType** ppMatrixOrientation,
  9090. _Inout_opt_ const clang::AttributedType** ppNorm)
  9091. {
  9092. if (ppMatrixOrientation)
  9093. *ppMatrixOrientation = nullptr;
  9094. if (ppNorm)
  9095. *ppNorm = nullptr;
  9096. // Note: we clear output pointers once set so we can stop searching
  9097. QualType Desugared = getUnderlyingType(type);
  9098. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  9099. while (AT && (ppMatrixOrientation || ppNorm)) {
  9100. AttributedType::Kind Kind = AT->getAttrKind();
  9101. if (Kind == AttributedType::attr_hlsl_row_major ||
  9102. Kind == AttributedType::attr_hlsl_column_major)
  9103. {
  9104. if (ppMatrixOrientation)
  9105. {
  9106. *ppMatrixOrientation = AT;
  9107. ppMatrixOrientation = nullptr;
  9108. }
  9109. }
  9110. else if (Kind == AttributedType::attr_hlsl_unorm ||
  9111. Kind == AttributedType::attr_hlsl_snorm)
  9112. {
  9113. if (ppNorm)
  9114. {
  9115. *ppNorm = AT;
  9116. ppNorm = nullptr;
  9117. }
  9118. }
  9119. Desugared = getUnderlyingType(AT->getEquivalentType());
  9120. AT = dyn_cast<AttributedType>(Desugared);
  9121. }
  9122. // Unwrap component type on vector or matrix and check snorm/unorm
  9123. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  9124. AT = dyn_cast<AttributedType>(Desugared);
  9125. while (AT && ppNorm) {
  9126. AttributedType::Kind Kind = AT->getAttrKind();
  9127. if (Kind == AttributedType::attr_hlsl_unorm ||
  9128. Kind == AttributedType::attr_hlsl_snorm)
  9129. {
  9130. *ppNorm = AT;
  9131. ppNorm = nullptr;
  9132. }
  9133. Desugared = getUnderlyingType(AT->getEquivalentType());
  9134. AT = dyn_cast<AttributedType>(Desugared);
  9135. }
  9136. }
  9137. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  9138. /// <param name="self">Sema with context.</param>
  9139. /// <param name="type">QualType to check.</param>
  9140. bool hlsl::IsMatrixType(
  9141. _In_ clang::Sema* self,
  9142. _In_ clang::QualType type)
  9143. {
  9144. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  9145. }
  9146. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  9147. /// <param name="self">Sema with context.</param>
  9148. /// <param name="type">QualType to check.</param>
  9149. bool hlsl::IsVectorType(
  9150. _In_ clang::Sema* self,
  9151. _In_ clang::QualType type)
  9152. {
  9153. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  9154. }
  9155. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  9156. /// <param name="self">Sema with context.</param>
  9157. /// <param name="type">Matrix or Vector type.</param>
  9158. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  9159. _In_ clang::QualType type)
  9160. {
  9161. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  9162. // without losing the AttributedType on the template parameter
  9163. if (const Type* pType = type.getTypePtrOrNull()) {
  9164. // A non-dependent template specialization type is always "sugar",
  9165. // typically for a RecordType. For example, a class template
  9166. // specialization type of @c vector<int> will refer to a tag type for
  9167. // the instantiation @c std::vector<int, std::allocator<int>>.
  9168. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  9169. // If we have enough arguments, pull them from the template directly, rather than doing
  9170. // the extra lookups.
  9171. if (pTemplate->getNumArgs() > 0)
  9172. return pTemplate->getArg(0).getAsType();
  9173. QualType templateRecord = pTemplate->desugar();
  9174. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  9175. if (pTemplateRecordType) {
  9176. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  9177. if (pTemplateTagType) {
  9178. const ClassTemplateSpecializationDecl *specializationDecl =
  9179. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  9180. pTemplateTagType->getDecl());
  9181. if (specializationDecl) {
  9182. return specializationDecl->getTemplateArgs()[0].getAsType();
  9183. }
  9184. }
  9185. }
  9186. }
  9187. }
  9188. return QualType();
  9189. }
  9190. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  9191. /// <param name="self">Sema with context.</param>
  9192. /// <param name="type">Input type.</param>
  9193. clang::QualType hlsl::GetOriginalElementType(
  9194. _In_ clang::Sema* self,
  9195. _In_ clang::QualType type)
  9196. {
  9197. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  9198. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  9199. return GetOriginalMatrixOrVectorElementType(type);
  9200. }
  9201. return type;
  9202. }
  9203. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  9204. switch (A->getKind()) {
  9205. // Parameter modifiers
  9206. case clang::attr::HLSLIn:
  9207. Out << "in ";
  9208. break;
  9209. case clang::attr::HLSLInOut:
  9210. Out << "inout ";
  9211. break;
  9212. case clang::attr::HLSLOut:
  9213. Out << "out ";
  9214. break;
  9215. // Interpolation modifiers
  9216. case clang::attr::HLSLLinear:
  9217. Out << "linear ";
  9218. break;
  9219. case clang::attr::HLSLCentroid:
  9220. Out << "centroid ";
  9221. break;
  9222. case clang::attr::HLSLNoInterpolation:
  9223. Out << "nointerpolation ";
  9224. break;
  9225. case clang::attr::HLSLNoPerspective:
  9226. Out << "noperspective ";
  9227. break;
  9228. case clang::attr::HLSLSample:
  9229. Out << "sample ";
  9230. break;
  9231. // Function attributes
  9232. case clang::attr::HLSLClipPlanes:
  9233. {
  9234. Attr * noconst = const_cast<Attr*>(A);
  9235. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  9236. if (!ACast->getClipPlane1())
  9237. break;
  9238. Indent(Indentation, Out);
  9239. Out << "[clipplanes(";
  9240. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  9241. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  9242. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  9243. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  9244. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  9245. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  9246. Out << ")]\n";
  9247. break;
  9248. }
  9249. case clang::attr::HLSLDomain:
  9250. {
  9251. Attr * noconst = const_cast<Attr*>(A);
  9252. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  9253. Indent(Indentation, Out);
  9254. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  9255. break;
  9256. }
  9257. case clang::attr::HLSLEarlyDepthStencil:
  9258. Indent(Indentation, Out);
  9259. Out << "[earlydepthstencil]\n";
  9260. break;
  9261. case clang::attr::HLSLInstance: //TODO - test
  9262. {
  9263. Attr * noconst = const_cast<Attr*>(A);
  9264. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  9265. Indent(Indentation, Out);
  9266. Out << "[instance(" << ACast->getCount() << ")]\n";
  9267. break;
  9268. }
  9269. case clang::attr::HLSLMaxTessFactor: //TODO - test
  9270. {
  9271. Attr * noconst = const_cast<Attr*>(A);
  9272. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  9273. Indent(Indentation, Out);
  9274. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  9275. break;
  9276. }
  9277. case clang::attr::HLSLNumThreads: //TODO - test
  9278. {
  9279. Attr * noconst = const_cast<Attr*>(A);
  9280. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  9281. Indent(Indentation, Out);
  9282. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  9283. break;
  9284. }
  9285. case clang::attr::HLSLRootSignature:
  9286. {
  9287. Attr * noconst = const_cast<Attr*>(A);
  9288. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  9289. Indent(Indentation, Out);
  9290. Out << "[RootSignature(" << ACast->getSignatureName() << ")]\n";
  9291. break;
  9292. }
  9293. case clang::attr::HLSLOutputControlPoints:
  9294. {
  9295. Attr * noconst = const_cast<Attr*>(A);
  9296. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  9297. Indent(Indentation, Out);
  9298. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  9299. break;
  9300. }
  9301. case clang::attr::HLSLOutputTopology:
  9302. {
  9303. Attr * noconst = const_cast<Attr*>(A);
  9304. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  9305. Indent(Indentation, Out);
  9306. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  9307. break;
  9308. }
  9309. case clang::attr::HLSLPartitioning:
  9310. {
  9311. Attr * noconst = const_cast<Attr*>(A);
  9312. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  9313. Indent(Indentation, Out);
  9314. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  9315. break;
  9316. }
  9317. case clang::attr::HLSLPatchConstantFunc:
  9318. {
  9319. Attr * noconst = const_cast<Attr*>(A);
  9320. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  9321. Indent(Indentation, Out);
  9322. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  9323. break;
  9324. }
  9325. case clang::attr::HLSLMaxVertexCount:
  9326. {
  9327. Attr * noconst = const_cast<Attr*>(A);
  9328. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  9329. Indent(Indentation, Out);
  9330. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  9331. break;
  9332. }
  9333. // Statement attributes
  9334. case clang::attr::HLSLAllowUAVCondition:
  9335. Indent(Indentation, Out);
  9336. Out << "[allow_uav_condition]\n";
  9337. break;
  9338. case clang::attr::HLSLBranch:
  9339. Indent(Indentation, Out);
  9340. Out << "[branch]\n";
  9341. break;
  9342. case clang::attr::HLSLCall:
  9343. Indent(Indentation, Out);
  9344. Out << "[call]\n";
  9345. break;
  9346. case clang::attr::HLSLFastOpt:
  9347. Indent(Indentation, Out);
  9348. Out << "[fastopt]\n";
  9349. break;
  9350. case clang::attr::HLSLFlatten:
  9351. Indent(Indentation, Out);
  9352. Out << "[flatten]\n";
  9353. break;
  9354. case clang::attr::HLSLForceCase:
  9355. Indent(Indentation, Out);
  9356. Out << "[forcecase]\n";
  9357. break;
  9358. case clang::attr::HLSLLoop:
  9359. Indent(Indentation, Out);
  9360. Out << "[loop]\n";
  9361. break;
  9362. case clang::attr::HLSLUnroll:
  9363. {
  9364. Attr * noconst = const_cast<Attr*>(A);
  9365. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  9366. Indent(Indentation, Out);
  9367. Out << "[unroll(" << ACast->getCount() << ")]\n";
  9368. break;
  9369. }
  9370. // Variable modifiers
  9371. case clang::attr::HLSLGroupShared:
  9372. Out << "groupshared ";
  9373. break;
  9374. case clang::attr::HLSLPrecise:
  9375. Out << "precise ";
  9376. break;
  9377. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  9378. break;
  9379. case clang::attr::HLSLShared:
  9380. Out << "shared ";
  9381. break;
  9382. case clang::attr::HLSLUniform:
  9383. Out << "uniform ";
  9384. break;
  9385. // These four cases are printed in TypePrinter::printAttributedBefore
  9386. case clang::attr::HLSLColumnMajor:
  9387. case clang::attr::HLSLRowMajor:
  9388. case clang::attr::HLSLSnorm:
  9389. case clang::attr::HLSLUnorm:
  9390. break;
  9391. case clang::attr::HLSLPoint:
  9392. Out << "point ";
  9393. break;
  9394. case clang::attr::HLSLLine:
  9395. Out << "line ";
  9396. break;
  9397. case clang::attr::HLSLLineAdj:
  9398. Out << "lineadj ";
  9399. break;
  9400. case clang::attr::HLSLTriangle:
  9401. Out << "triangle ";
  9402. break;
  9403. case clang::attr::HLSLTriangleAdj:
  9404. Out << "triangleadj ";
  9405. break;
  9406. case clang::attr::HLSLGloballyCoherent:
  9407. Out << "globallycoherent ";
  9408. break;
  9409. default:
  9410. A->printPretty(Out, Policy);
  9411. break;
  9412. }
  9413. }
  9414. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  9415. switch (AttrKind){
  9416. case clang::attr::HLSLAllowUAVCondition:
  9417. case clang::attr::HLSLBranch:
  9418. case clang::attr::HLSLCall:
  9419. case clang::attr::HLSLCentroid:
  9420. case clang::attr::HLSLClipPlanes:
  9421. case clang::attr::HLSLColumnMajor:
  9422. case clang::attr::HLSLDomain:
  9423. case clang::attr::HLSLEarlyDepthStencil:
  9424. case clang::attr::HLSLFastOpt:
  9425. case clang::attr::HLSLFlatten:
  9426. case clang::attr::HLSLForceCase:
  9427. case clang::attr::HLSLGroupShared:
  9428. case clang::attr::HLSLIn:
  9429. case clang::attr::HLSLInOut:
  9430. case clang::attr::HLSLInstance:
  9431. case clang::attr::HLSLLinear:
  9432. case clang::attr::HLSLLoop:
  9433. case clang::attr::HLSLMaxTessFactor:
  9434. case clang::attr::HLSLNoInterpolation:
  9435. case clang::attr::HLSLNoPerspective:
  9436. case clang::attr::HLSLNumThreads:
  9437. case clang::attr::HLSLRootSignature:
  9438. case clang::attr::HLSLOut:
  9439. case clang::attr::HLSLOutputControlPoints:
  9440. case clang::attr::HLSLOutputTopology:
  9441. case clang::attr::HLSLPartitioning:
  9442. case clang::attr::HLSLPatchConstantFunc:
  9443. case clang::attr::HLSLMaxVertexCount:
  9444. case clang::attr::HLSLPrecise:
  9445. case clang::attr::HLSLRowMajor:
  9446. case clang::attr::HLSLSample:
  9447. case clang::attr::HLSLSemantic:
  9448. case clang::attr::HLSLShared:
  9449. case clang::attr::HLSLSnorm:
  9450. case clang::attr::HLSLUniform:
  9451. case clang::attr::HLSLUnorm:
  9452. case clang::attr::HLSLUnroll:
  9453. case clang::attr::HLSLPoint:
  9454. case clang::attr::HLSLLine:
  9455. case clang::attr::HLSLLineAdj:
  9456. case clang::attr::HLSLTriangle:
  9457. case clang::attr::HLSLTriangleAdj:
  9458. case clang::attr::HLSLGloballyCoherent:
  9459. return true;
  9460. }
  9461. return false;
  9462. }
  9463. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  9464. if (ClipPlane) {
  9465. Out << ", ";
  9466. ClipPlane->printPretty(Out, 0, Policy);
  9467. }
  9468. }
  9469. bool hlsl::IsObjectType(
  9470. _In_ clang::Sema* self,
  9471. _In_ clang::QualType type,
  9472. _Inout_opt_ bool *isDeprecatedEffectObject)
  9473. {
  9474. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  9475. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  9476. if (isDeprecatedEffectObject)
  9477. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  9478. return true;
  9479. }
  9480. if (isDeprecatedEffectObject)
  9481. *isDeprecatedEffectObject = false;
  9482. return false;
  9483. }
  9484. bool hlsl::CanConvert(
  9485. _In_ clang::Sema* self,
  9486. clang::SourceLocation loc,
  9487. _In_ clang::Expr* sourceExpr,
  9488. clang::QualType target,
  9489. bool explicitConversion,
  9490. _Inout_opt_ clang::StandardConversionSequence* standard)
  9491. {
  9492. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  9493. }
  9494. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  9495. {
  9496. for (unsigned i = 0; i != Indentation; ++i)
  9497. Out << " ";
  9498. }
  9499. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  9500. {
  9501. DXASSERT_NOMSG(self != nullptr);
  9502. DXASSERT_NOMSG(table != nullptr);
  9503. HLSLExternalSource* source = (HLSLExternalSource*)self;
  9504. source->RegisterIntrinsicTable(table);
  9505. }
  9506. clang::QualType hlsl::CheckVectorConditional(
  9507. _In_ clang::Sema* self,
  9508. _In_ clang::ExprResult &Cond,
  9509. _In_ clang::ExprResult &LHS,
  9510. _In_ clang::ExprResult &RHS,
  9511. _In_ clang::SourceLocation QuestionLoc)
  9512. {
  9513. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  9514. }
  9515. clang::QualType ApplyTypeSpecSignToParsedType(
  9516. _In_ clang::Sema* self,
  9517. _In_ clang::QualType &type,
  9518. _In_ clang::TypeSpecifierSign TSS,
  9519. _In_ clang::SourceLocation Loc
  9520. )
  9521. {
  9522. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  9523. }