SemaHLSL.cpp 468 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509
  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 "llvm/ADT/SmallPtrSet.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExternalASTSource.h"
  21. #include "clang/AST/RecursiveASTVisitor.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/AST/HlslTypes.h"
  24. #include "clang/Sema/Overload.h"
  25. #include "clang/Sema/SemaDiagnostic.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/ExternalSemaSource.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/Template.h"
  30. #include "clang/Sema/TemplateDeduction.h"
  31. #include "clang/Sema/SemaHLSL.h"
  32. #include "dxc/Support/Global.h"
  33. #include "dxc/Support/WinIncludes.h"
  34. #include "dxc/Support/WinAdapter.h"
  35. #include "dxc/dxcapi.internal.h"
  36. #include "dxc/HlslIntrinsicOp.h"
  37. #include "gen_intrin_main_tables_15.h"
  38. #include "VkConstantsTables.h"
  39. #include "dxc/HLSL/HLOperations.h"
  40. #include "dxc/DXIL/DxilShaderModel.h"
  41. #include <array>
  42. #include <algorithm>
  43. #include <float.h>
  44. enum ArBasicKind {
  45. AR_BASIC_BOOL,
  46. AR_BASIC_LITERAL_FLOAT,
  47. AR_BASIC_FLOAT16,
  48. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  49. AR_BASIC_FLOAT32,
  50. AR_BASIC_FLOAT64,
  51. AR_BASIC_LITERAL_INT,
  52. AR_BASIC_INT8,
  53. AR_BASIC_UINT8,
  54. AR_BASIC_INT16,
  55. AR_BASIC_UINT16,
  56. AR_BASIC_INT32,
  57. AR_BASIC_UINT32,
  58. AR_BASIC_INT64,
  59. AR_BASIC_UINT64,
  60. AR_BASIC_MIN10FLOAT,
  61. AR_BASIC_MIN16FLOAT,
  62. AR_BASIC_MIN12INT,
  63. AR_BASIC_MIN16INT,
  64. AR_BASIC_MIN16UINT,
  65. AR_BASIC_INT8_4PACKED,
  66. AR_BASIC_UINT8_4PACKED,
  67. AR_BASIC_ENUM,
  68. AR_BASIC_COUNT,
  69. //
  70. // Pseudo-entries for intrinsic tables and such.
  71. //
  72. AR_BASIC_NONE,
  73. AR_BASIC_UNKNOWN,
  74. AR_BASIC_NOCAST,
  75. AR_BASIC_DEPENDENT,
  76. //
  77. // The following pseudo-entries represent higher-level
  78. // object types that are treated as units.
  79. //
  80. AR_BASIC_POINTER,
  81. AR_BASIC_ENUM_CLASS,
  82. AR_OBJECT_NULL,
  83. AR_OBJECT_STRING_LITERAL,
  84. AR_OBJECT_STRING,
  85. // AR_OBJECT_TEXTURE,
  86. AR_OBJECT_TEXTURE1D,
  87. AR_OBJECT_TEXTURE1D_ARRAY,
  88. AR_OBJECT_TEXTURE2D,
  89. AR_OBJECT_TEXTURE2D_ARRAY,
  90. AR_OBJECT_TEXTURE3D,
  91. AR_OBJECT_TEXTURECUBE,
  92. AR_OBJECT_TEXTURECUBE_ARRAY,
  93. AR_OBJECT_TEXTURE2DMS,
  94. AR_OBJECT_TEXTURE2DMS_ARRAY,
  95. AR_OBJECT_SAMPLER,
  96. AR_OBJECT_SAMPLER1D,
  97. AR_OBJECT_SAMPLER2D,
  98. AR_OBJECT_SAMPLER3D,
  99. AR_OBJECT_SAMPLERCUBE,
  100. AR_OBJECT_SAMPLERCOMPARISON,
  101. AR_OBJECT_BUFFER,
  102. //
  103. // View objects are only used as variable/types within the Effects
  104. // framework, for example in calls to OMSetRenderTargets.
  105. //
  106. AR_OBJECT_RENDERTARGETVIEW,
  107. AR_OBJECT_DEPTHSTENCILVIEW,
  108. //
  109. // Shader objects are only used as variable/types within the Effects
  110. // framework, for example as a result of CompileShader().
  111. //
  112. AR_OBJECT_COMPUTESHADER,
  113. AR_OBJECT_DOMAINSHADER,
  114. AR_OBJECT_GEOMETRYSHADER,
  115. AR_OBJECT_HULLSHADER,
  116. AR_OBJECT_PIXELSHADER,
  117. AR_OBJECT_VERTEXSHADER,
  118. AR_OBJECT_PIXELFRAGMENT,
  119. AR_OBJECT_VERTEXFRAGMENT,
  120. AR_OBJECT_STATEBLOCK,
  121. AR_OBJECT_RASTERIZER,
  122. AR_OBJECT_DEPTHSTENCIL,
  123. AR_OBJECT_BLEND,
  124. AR_OBJECT_POINTSTREAM,
  125. AR_OBJECT_LINESTREAM,
  126. AR_OBJECT_TRIANGLESTREAM,
  127. AR_OBJECT_INPUTPATCH,
  128. AR_OBJECT_OUTPUTPATCH,
  129. AR_OBJECT_RWTEXTURE1D,
  130. AR_OBJECT_RWTEXTURE1D_ARRAY,
  131. AR_OBJECT_RWTEXTURE2D,
  132. AR_OBJECT_RWTEXTURE2D_ARRAY,
  133. AR_OBJECT_RWTEXTURE3D,
  134. AR_OBJECT_RWBUFFER,
  135. AR_OBJECT_BYTEADDRESS_BUFFER,
  136. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  137. AR_OBJECT_STRUCTURED_BUFFER,
  138. AR_OBJECT_RWSTRUCTURED_BUFFER,
  139. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  140. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  141. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  142. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  143. AR_OBJECT_CONSTANT_BUFFER,
  144. AR_OBJECT_TEXTURE_BUFFER,
  145. AR_OBJECT_ROVBUFFER,
  146. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  147. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  148. AR_OBJECT_ROVTEXTURE1D,
  149. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  150. AR_OBJECT_ROVTEXTURE2D,
  151. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  152. AR_OBJECT_ROVTEXTURE3D,
  153. AR_OBJECT_FEEDBACKTEXTURE2D,
  154. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  155. // SPIRV change starts
  156. #ifdef ENABLE_SPIRV_CODEGEN
  157. AR_OBJECT_VK_SUBPASS_INPUT,
  158. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  159. #endif // ENABLE_SPIRV_CODEGEN
  160. // SPIRV change ends
  161. AR_OBJECT_INNER, // Used for internal type object
  162. AR_OBJECT_LEGACY_EFFECT,
  163. AR_OBJECT_WAVE,
  164. AR_OBJECT_RAY_DESC,
  165. AR_OBJECT_ACCELERATION_STRUCT,
  166. AR_OBJECT_USER_DEFINED_TYPE,
  167. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  168. // subobjects
  169. AR_OBJECT_STATE_OBJECT_CONFIG,
  170. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  171. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  172. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  173. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  174. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  175. AR_OBJECT_TRIANGLE_HIT_GROUP,
  176. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  177. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  178. // RayQuery
  179. AR_OBJECT_RAY_QUERY,
  180. // Heap Resource
  181. AR_OBJECT_HEAP_RESOURCE,
  182. AR_OBJECT_HEAP_SAMPLER,
  183. AR_BASIC_MAXIMUM_COUNT
  184. };
  185. #define AR_BASIC_TEXTURE_MS_CASES \
  186. case AR_OBJECT_TEXTURE2DMS: \
  187. case AR_OBJECT_TEXTURE2DMS_ARRAY
  188. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  189. case AR_OBJECT_TEXTURE1D: \
  190. case AR_OBJECT_TEXTURE1D_ARRAY: \
  191. case AR_OBJECT_TEXTURE2D: \
  192. case AR_OBJECT_TEXTURE2D_ARRAY: \
  193. case AR_OBJECT_TEXTURE3D: \
  194. case AR_OBJECT_TEXTURECUBE: \
  195. case AR_OBJECT_TEXTURECUBE_ARRAY
  196. #define AR_BASIC_TEXTURE_CASES \
  197. AR_BASIC_TEXTURE_MS_CASES: \
  198. AR_BASIC_NON_TEXTURE_MS_CASES
  199. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  200. case AR_OBJECT_SAMPLER: \
  201. case AR_OBJECT_SAMPLER1D: \
  202. case AR_OBJECT_SAMPLER2D: \
  203. case AR_OBJECT_SAMPLER3D: \
  204. case AR_OBJECT_SAMPLERCUBE
  205. #define AR_BASIC_ROBJECT_CASES \
  206. case AR_OBJECT_BLEND: \
  207. case AR_OBJECT_RASTERIZER: \
  208. case AR_OBJECT_DEPTHSTENCIL: \
  209. case AR_OBJECT_STATEBLOCK
  210. //
  211. // Properties of entries in the ArBasicKind enumeration.
  212. // These properties are intended to allow easy identification
  213. // of classes of basic kinds. More specific checks on the
  214. // actual kind values could then be done.
  215. //
  216. // The first four bits are used as a subtype indicator,
  217. // such as bit count for primitive kinds or specific
  218. // types for non-primitive-data kinds.
  219. #define BPROP_SUBTYPE_MASK 0x0000000f
  220. // Bit counts must be ordered from smaller to larger.
  221. #define BPROP_BITS0 0x00000000
  222. #define BPROP_BITS8 0x00000001
  223. #define BPROP_BITS10 0x00000002
  224. #define BPROP_BITS12 0x00000003
  225. #define BPROP_BITS16 0x00000004
  226. #define BPROP_BITS32 0x00000005
  227. #define BPROP_BITS64 0x00000006
  228. #define BPROP_BITS_NON_PRIM 0x00000007
  229. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  230. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  231. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  232. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  233. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  234. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  235. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  236. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  237. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  238. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  239. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  240. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  241. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  242. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  243. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  244. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  245. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  246. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  247. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  248. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  249. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  250. #define BPROP_FEEDBACKTEXTURE 0x00800000 // Whether the type is a feedback texture.
  251. #define BPROP_ENUM 0x01000000 // Whether the type is a enum
  252. #define GET_BPROP_PRIM_KIND(_Props) \
  253. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  254. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  255. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  256. #define IS_BPROP_PRIMITIVE(_Props) \
  257. (((_Props) & BPROP_PRIMITIVE) != 0)
  258. #define IS_BPROP_BOOL(_Props) \
  259. (((_Props) & BPROP_BOOLEAN) != 0)
  260. #define IS_BPROP_FLOAT(_Props) \
  261. (((_Props) & BPROP_FLOATING) != 0)
  262. #define IS_BPROP_SINT(_Props) \
  263. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  264. BPROP_INTEGER)
  265. #define IS_BPROP_UINT(_Props) \
  266. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  267. (BPROP_INTEGER | BPROP_UNSIGNED))
  268. #define IS_BPROP_AINT(_Props) \
  269. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  270. #define IS_BPROP_STREAM(_Props) \
  271. (((_Props) & BPROP_STREAM) != 0)
  272. #define IS_BPROP_SAMPLER(_Props) \
  273. (((_Props) & BPROP_SAMPLER) != 0)
  274. #define IS_BPROP_TEXTURE(_Props) \
  275. (((_Props) & BPROP_TEXTURE) != 0)
  276. #define IS_BPROP_OBJECT(_Props) \
  277. (((_Props) & BPROP_OBJECT) != 0)
  278. #define IS_BPROP_MIN_PRECISION(_Props) \
  279. (((_Props) & BPROP_MIN_PRECISION) != 0)
  280. #define IS_BPROP_UNSIGNABLE(_Props) \
  281. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  282. #define IS_BPROP_ENUM(_Props) \
  283. (((_Props) & BPROP_ENUM) != 0)
  284. const UINT g_uBasicKindProps[] =
  285. {
  286. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  287. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  288. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  289. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  290. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  291. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  292. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  293. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  294. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  295. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  296. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  297. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  298. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  299. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  300. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  301. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  302. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  303. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  304. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  305. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  306. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_INT8_4PACKED
  307. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT8_4PACKED
  308. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  309. BPROP_OTHER, // AR_BASIC_COUNT
  310. //
  311. // Pseudo-entries for intrinsic tables and such.
  312. //
  313. 0, // AR_BASIC_NONE
  314. BPROP_OTHER, // AR_BASIC_UNKNOWN
  315. BPROP_OTHER, // AR_BASIC_NOCAST
  316. 0, // AR_BASIC_DEPENDENT
  317. //
  318. // The following pseudo-entries represent higher-level
  319. // object types that are treated as units.
  320. //
  321. BPROP_POINTER, // AR_BASIC_POINTER
  322. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  323. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  324. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING_LITERAL
  325. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  326. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  327. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  328. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  329. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  330. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  331. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  332. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  333. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  334. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  335. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  336. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  337. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  338. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  339. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  340. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  341. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  342. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  343. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  344. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  345. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  346. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  347. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  348. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  349. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  350. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  351. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  352. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  353. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  354. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  355. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  356. BPROP_OBJECT, // AR_OBJECT_BLEND
  357. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  358. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  359. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  360. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  361. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  362. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  363. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  364. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  365. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  366. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  367. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  368. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  369. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  370. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  371. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  372. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  373. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  374. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  375. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  376. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  377. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  378. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  379. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  380. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  381. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  382. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  383. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  384. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  385. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  386. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D
  387. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  388. // SPIRV change starts
  389. #ifdef ENABLE_SPIRV_CODEGEN
  390. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  391. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  392. #endif // ENABLE_SPIRV_CODEGEN
  393. // SPIRV change ends
  394. BPROP_OBJECT, // AR_OBJECT_INNER
  395. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  396. BPROP_OBJECT, // AR_OBJECT_WAVE
  397. LICOMPTYPE_RAYDESC, // AR_OBJECT_RAY_DESC
  398. LICOMPTYPE_ACCELERATION_STRUCT, // AR_OBJECT_ACCELERATION_STRUCT
  399. LICOMPTYPE_USER_DEFINED_TYPE, // AR_OBJECT_USER_DEFINED_TYPE
  400. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  401. // subobjects
  402. 0, //AR_OBJECT_STATE_OBJECT_CONFIG,
  403. 0, //AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  404. 0, //AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  405. 0, //AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  406. 0, //AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  407. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  408. 0, //AR_OBJECT_TRIANGLE_HIT_GROUP,
  409. 0, //AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  410. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  411. 0, //AR_OBJECT_RAY_QUERY,
  412. 0, //AR_OBJECT_HEAP_RESOURCE,
  413. 0, //AR_OBJECT_HEAP_SAMPLER,
  414. // AR_BASIC_MAXIMUM_COUNT
  415. };
  416. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  417. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  418. #define GET_BASIC_BITS(_Kind) \
  419. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  420. #define GET_BASIC_PRIM_KIND(_Kind) \
  421. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  422. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  423. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  424. #define IS_BASIC_PRIMITIVE(_Kind) \
  425. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  426. #define IS_BASIC_BOOL(_Kind) \
  427. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  428. #define IS_BASIC_FLOAT(_Kind) \
  429. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  430. #define IS_BASIC_SINT(_Kind) \
  431. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  432. #define IS_BASIC_UINT(_Kind) \
  433. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  434. #define IS_BASIC_AINT(_Kind) \
  435. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  436. #define IS_BASIC_STREAM(_Kind) \
  437. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  438. #define IS_BASIC_SAMPLER(_Kind) \
  439. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  440. #define IS_BASIC_TEXTURE(_Kind) \
  441. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  442. #define IS_BASIC_OBJECT(_Kind) \
  443. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  444. #define IS_BASIC_MIN_PRECISION(_Kind) \
  445. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  446. #define IS_BASIC_UNSIGNABLE(_Kind) \
  447. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  448. #define IS_BASIC_ENUM(_Kind) \
  449. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  450. #define BITWISE_ENUM_OPS(_Type) \
  451. inline _Type operator|(_Type F1, _Type F2) \
  452. { \
  453. return (_Type)((UINT)F1 | (UINT)F2); \
  454. } \
  455. inline _Type operator&(_Type F1, _Type F2) \
  456. { \
  457. return (_Type)((UINT)F1 & (UINT)F2); \
  458. } \
  459. inline _Type& operator|=(_Type& F1, _Type F2) \
  460. { \
  461. F1 = F1 | F2; \
  462. return F1; \
  463. } \
  464. inline _Type& operator&=(_Type& F1, _Type F2) \
  465. { \
  466. F1 = F1 & F2; \
  467. return F1; \
  468. } \
  469. inline _Type& operator&=(_Type& F1, UINT F2) \
  470. { \
  471. F1 = (_Type)((UINT)F1 & F2); \
  472. return F1; \
  473. }
  474. enum ArTypeObjectKind {
  475. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  476. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  477. AR_TOBJ_BASIC, // Represents a primitive type.
  478. AR_TOBJ_COMPOUND, // Represents a struct or class.
  479. AR_TOBJ_INTERFACE, // Represents an interface.
  480. AR_TOBJ_POINTER, // Represents a pointer to another type.
  481. AR_TOBJ_OBJECT, // Represents a built-in object.
  482. AR_TOBJ_ARRAY, // Represents an array of other types.
  483. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  484. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  485. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  486. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  487. // indexer object used to implement .mips[1].
  488. AR_TOBJ_STRING, // Represents a string
  489. AR_TOBJ_DEPENDENT, // Dependent type for template.
  490. };
  491. enum TYPE_CONVERSION_FLAGS
  492. {
  493. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  494. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  495. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  496. };
  497. enum TYPE_CONVERSION_REMARKS
  498. {
  499. TYPE_CONVERSION_NONE = 0x00000000,
  500. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  501. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  502. TYPE_CONVERSION_TO_VOID = 0x00000004,
  503. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  504. };
  505. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  506. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  507. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  508. #define AR_TPROP_VOID 0x0000000000000001
  509. #define AR_TPROP_CONST 0x0000000000000002
  510. #define AR_TPROP_IMP_CONST 0x0000000000000004
  511. #define AR_TPROP_OBJECT 0x0000000000000008
  512. #define AR_TPROP_SCALAR 0x0000000000000010
  513. #define AR_TPROP_UNSIGNED 0x0000000000000020
  514. #define AR_TPROP_NUMERIC 0x0000000000000040
  515. #define AR_TPROP_INTEGRAL 0x0000000000000080
  516. #define AR_TPROP_FLOATING 0x0000000000000100
  517. #define AR_TPROP_LITERAL 0x0000000000000200
  518. #define AR_TPROP_POINTER 0x0000000000000400
  519. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  520. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  521. #define AR_TPROP_INH_IFACE 0x0000000000002000
  522. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  523. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  524. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  525. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  526. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  527. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  528. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  529. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  530. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  531. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  532. #define AR_TPROP_INDEXABLE 0x0000000001000000
  533. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  534. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  535. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  536. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  537. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  538. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  539. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  540. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  541. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  542. #define AR_TPROP_ALL 0xffffffffffffffff
  543. #define AR_TPROP_HAS_OBJECTS \
  544. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  545. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  546. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  547. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  548. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  549. #define AR_TPROP_HAS_BASIC_RESOURCES \
  550. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  551. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  552. AR_TPROP_HAS_UAVS)
  553. #define AR_TPROP_UNION_BITS \
  554. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  555. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  556. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  557. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  558. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  559. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  560. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  561. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  562. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  563. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  564. #define AR_TINFO_PACK_SCALAR 0x00000010
  565. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  566. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  567. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  568. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  569. #define AR_TINFO_PACK_CBUFFER 0
  570. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  571. #define AR_TINFO_SIMPLE_OBJECTS \
  572. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  573. struct ArTypeInfo {
  574. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  575. ArBasicKind EltKind; // The primitive type of elements in this type.
  576. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  577. UINT uRows;
  578. UINT uCols;
  579. UINT uTotalElts;
  580. };
  581. using namespace clang;
  582. using namespace clang::sema;
  583. using namespace hlsl;
  584. extern const char *HLSLScalarTypeNames[];
  585. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  586. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  587. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  588. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  589. static const SourceLocation NoLoc; // no source location attribution available
  590. static const SourceRange NoRange; // no source range attribution available
  591. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  592. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  593. static const bool IsConstexprFalse = false; // function is not constexpr
  594. static const bool ListInitializationFalse = false;// not performing a list initialization
  595. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  596. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  597. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  598. static const int OneRow = 1; // a single row for a type
  599. static const bool MipsFalse = false; // a type does not support the .mips member
  600. static const bool MipsTrue = true; // a type supports the .mips member
  601. static const bool SampleFalse = false; // a type does not support the .sample member
  602. static const bool SampleTrue = true; // a type supports the .sample member
  603. static const size_t MaxVectorSize = 4; // maximum size for a vector
  604. static
  605. QualType GetOrCreateTemplateSpecialization(
  606. ASTContext& context,
  607. Sema& sema,
  608. _In_ ClassTemplateDecl* templateDecl,
  609. ArrayRef<TemplateArgument> templateArgs
  610. )
  611. {
  612. DXASSERT_NOMSG(templateDecl);
  613. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  614. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  615. for (const TemplateArgument& Arg : templateArgs) {
  616. if (Arg.getKind() == TemplateArgument::Type) {
  617. // the class template need to use CanonicalType
  618. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  619. }else
  620. templateArgsForDecl.emplace_back(Arg);
  621. }
  622. // First, try looking up existing specialization
  623. void* InsertPos = nullptr;
  624. ClassTemplateSpecializationDecl* specializationDecl =
  625. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  626. if (specializationDecl) {
  627. // Instantiate the class template if not yet.
  628. if (specializationDecl->getInstantiatedFrom().isNull()) {
  629. // InstantiateClassTemplateSpecialization returns true if it finds an
  630. // error.
  631. DXVERIFY_NOMSG(false ==
  632. sema.InstantiateClassTemplateSpecialization(
  633. NoLoc, specializationDecl,
  634. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  635. true));
  636. }
  637. return context.getTemplateSpecializationType(
  638. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  639. context.getTypeDeclType(specializationDecl));
  640. }
  641. specializationDecl = ClassTemplateSpecializationDecl::Create(
  642. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  643. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  644. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  645. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  646. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  647. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  648. specializationDecl->setImplicit(true);
  649. QualType canonType = context.getTypeDeclType(specializationDecl);
  650. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  651. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  652. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  653. for (unsigned i = 0; i < templateArgs.size(); i++) {
  654. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  655. }
  656. return context.getTemplateSpecializationType(
  657. TemplateName(templateDecl), templateArgumentList, canonType);
  658. }
  659. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  660. static
  661. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  662. _In_ ClassTemplateDecl* matrixTemplateDecl,
  663. QualType elementType, uint64_t rowCount, uint64_t colCount)
  664. {
  665. DXASSERT_NOMSG(sema);
  666. TemplateArgument templateArgs[3] = {
  667. TemplateArgument(elementType),
  668. TemplateArgument(
  669. context,
  670. llvm::APSInt(
  671. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  672. context.IntTy),
  673. TemplateArgument(
  674. context,
  675. llvm::APSInt(
  676. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  677. context.IntTy)};
  678. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  679. #ifdef DBG
  680. // Verify that we can read the field member from the template record.
  681. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  682. "type of non-dependent specialization is not a RecordType");
  683. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  684. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  685. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  686. #endif
  687. return matrixSpecializationType;
  688. }
  689. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  690. static
  691. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  692. _In_ ClassTemplateDecl* vectorTemplateDecl,
  693. QualType elementType, uint64_t colCount)
  694. {
  695. DXASSERT_NOMSG(sema);
  696. DXASSERT_NOMSG(vectorTemplateDecl);
  697. TemplateArgument templateArgs[2] = {
  698. TemplateArgument(elementType),
  699. TemplateArgument(
  700. context,
  701. llvm::APSInt(
  702. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  703. context.IntTy)};
  704. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  705. #ifdef DBG
  706. // Verify that we can read the field member from the template record.
  707. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  708. "type of non-dependent specialization is not a RecordType");
  709. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  710. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  711. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  712. #endif
  713. return vectorSpecializationType;
  714. }
  715. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  716. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  717. static const unsigned kAtomicDstOperandIdx = 1;
  718. static const ArTypeObjectKind g_ScalarTT[] =
  719. {
  720. AR_TOBJ_SCALAR,
  721. AR_TOBJ_UNKNOWN
  722. };
  723. static const ArTypeObjectKind g_VectorTT[] =
  724. {
  725. AR_TOBJ_VECTOR,
  726. AR_TOBJ_UNKNOWN
  727. };
  728. static const ArTypeObjectKind g_MatrixTT[] =
  729. {
  730. AR_TOBJ_MATRIX,
  731. AR_TOBJ_UNKNOWN
  732. };
  733. static const ArTypeObjectKind g_AnyTT[] =
  734. {
  735. AR_TOBJ_SCALAR,
  736. AR_TOBJ_VECTOR,
  737. AR_TOBJ_MATRIX,
  738. AR_TOBJ_UNKNOWN
  739. };
  740. static const ArTypeObjectKind g_ObjectTT[] =
  741. {
  742. AR_TOBJ_OBJECT,
  743. AR_TOBJ_UNKNOWN
  744. };
  745. static const ArTypeObjectKind g_NullTT[] =
  746. {
  747. AR_TOBJ_VOID,
  748. AR_TOBJ_UNKNOWN
  749. };
  750. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  751. {
  752. g_NullTT,
  753. g_ScalarTT,
  754. g_VectorTT,
  755. g_MatrixTT,
  756. g_AnyTT,
  757. g_ObjectTT,
  758. };
  759. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  760. //
  761. // The first one is used to name the representative group, so make
  762. // sure its name will make sense in error messages.
  763. //
  764. static const ArBasicKind g_BoolCT[] =
  765. {
  766. AR_BASIC_BOOL,
  767. AR_BASIC_UNKNOWN
  768. };
  769. static const ArBasicKind g_IntCT[] =
  770. {
  771. AR_BASIC_INT32,
  772. AR_BASIC_LITERAL_INT,
  773. AR_BASIC_UNKNOWN
  774. };
  775. static const ArBasicKind g_UIntCT[] =
  776. {
  777. AR_BASIC_UINT32,
  778. AR_BASIC_LITERAL_INT,
  779. AR_BASIC_UNKNOWN
  780. };
  781. // We use the first element for default if matching kind is missing in the list.
  782. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  783. static const ArBasicKind g_AnyIntCT[] =
  784. {
  785. AR_BASIC_INT32,
  786. AR_BASIC_INT16,
  787. AR_BASIC_UINT32,
  788. AR_BASIC_UINT16,
  789. AR_BASIC_INT64,
  790. AR_BASIC_UINT64,
  791. AR_BASIC_LITERAL_INT,
  792. AR_BASIC_UNKNOWN
  793. };
  794. static const ArBasicKind g_AnyInt32CT[] =
  795. {
  796. AR_BASIC_INT32,
  797. AR_BASIC_UINT32,
  798. AR_BASIC_LITERAL_INT,
  799. AR_BASIC_UNKNOWN
  800. };
  801. static const ArBasicKind g_UIntOnlyCT[] =
  802. {
  803. AR_BASIC_UINT32,
  804. AR_BASIC_UINT64,
  805. AR_BASIC_LITERAL_INT,
  806. AR_BASIC_NOCAST,
  807. AR_BASIC_UNKNOWN
  808. };
  809. static const ArBasicKind g_FloatCT[] =
  810. {
  811. AR_BASIC_FLOAT32,
  812. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  813. AR_BASIC_LITERAL_FLOAT,
  814. AR_BASIC_UNKNOWN
  815. };
  816. static const ArBasicKind g_AnyFloatCT[] =
  817. {
  818. AR_BASIC_FLOAT32,
  819. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  820. AR_BASIC_FLOAT16,
  821. AR_BASIC_FLOAT64,
  822. AR_BASIC_LITERAL_FLOAT,
  823. AR_BASIC_MIN10FLOAT,
  824. AR_BASIC_MIN16FLOAT,
  825. AR_BASIC_UNKNOWN
  826. };
  827. static const ArBasicKind g_FloatLikeCT[] =
  828. {
  829. AR_BASIC_FLOAT32,
  830. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  831. AR_BASIC_FLOAT16,
  832. AR_BASIC_LITERAL_FLOAT,
  833. AR_BASIC_MIN10FLOAT,
  834. AR_BASIC_MIN16FLOAT,
  835. AR_BASIC_UNKNOWN
  836. };
  837. static const ArBasicKind g_FloatDoubleCT[] =
  838. {
  839. AR_BASIC_FLOAT32,
  840. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  841. AR_BASIC_FLOAT64,
  842. AR_BASIC_LITERAL_FLOAT,
  843. AR_BASIC_UNKNOWN
  844. };
  845. static const ArBasicKind g_DoubleCT[] =
  846. {
  847. AR_BASIC_FLOAT64,
  848. AR_BASIC_LITERAL_FLOAT,
  849. AR_BASIC_UNKNOWN
  850. };
  851. static const ArBasicKind g_DoubleOnlyCT[] =
  852. {
  853. AR_BASIC_FLOAT64,
  854. AR_BASIC_LITERAL_FLOAT,
  855. AR_BASIC_NOCAST,
  856. AR_BASIC_UNKNOWN
  857. };
  858. static const ArBasicKind g_NumericCT[] =
  859. {
  860. AR_BASIC_FLOAT32,
  861. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  862. AR_BASIC_FLOAT16,
  863. AR_BASIC_FLOAT64,
  864. AR_BASIC_LITERAL_FLOAT,
  865. AR_BASIC_MIN10FLOAT,
  866. AR_BASIC_MIN16FLOAT,
  867. AR_BASIC_LITERAL_INT,
  868. AR_BASIC_INT16,
  869. AR_BASIC_INT32,
  870. AR_BASIC_UINT16,
  871. AR_BASIC_UINT32,
  872. AR_BASIC_MIN12INT,
  873. AR_BASIC_MIN16INT,
  874. AR_BASIC_MIN16UINT,
  875. AR_BASIC_INT64,
  876. AR_BASIC_UINT64,
  877. AR_BASIC_UNKNOWN
  878. };
  879. static const ArBasicKind g_Numeric32CT[] =
  880. {
  881. AR_BASIC_FLOAT32,
  882. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  883. AR_BASIC_LITERAL_FLOAT,
  884. AR_BASIC_LITERAL_INT,
  885. AR_BASIC_INT32,
  886. AR_BASIC_UINT32,
  887. AR_BASIC_UNKNOWN
  888. };
  889. static const ArBasicKind g_Numeric32OnlyCT[] =
  890. {
  891. AR_BASIC_FLOAT32,
  892. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  893. AR_BASIC_LITERAL_FLOAT,
  894. AR_BASIC_LITERAL_INT,
  895. AR_BASIC_INT32,
  896. AR_BASIC_UINT32,
  897. AR_BASIC_NOCAST,
  898. AR_BASIC_UNKNOWN
  899. };
  900. static const ArBasicKind g_AnyCT[] =
  901. {
  902. AR_BASIC_FLOAT32,
  903. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  904. AR_BASIC_FLOAT16,
  905. AR_BASIC_FLOAT64,
  906. AR_BASIC_LITERAL_FLOAT,
  907. AR_BASIC_MIN10FLOAT,
  908. AR_BASIC_MIN16FLOAT,
  909. AR_BASIC_INT16,
  910. AR_BASIC_UINT16,
  911. AR_BASIC_LITERAL_INT,
  912. AR_BASIC_INT32,
  913. AR_BASIC_UINT32,
  914. AR_BASIC_MIN12INT,
  915. AR_BASIC_MIN16INT,
  916. AR_BASIC_MIN16UINT,
  917. AR_BASIC_BOOL,
  918. AR_BASIC_INT64,
  919. AR_BASIC_UINT64,
  920. AR_BASIC_UNKNOWN
  921. };
  922. static const ArBasicKind g_Sampler1DCT[] =
  923. {
  924. AR_OBJECT_SAMPLER1D,
  925. AR_BASIC_UNKNOWN
  926. };
  927. static const ArBasicKind g_Sampler2DCT[] =
  928. {
  929. AR_OBJECT_SAMPLER2D,
  930. AR_BASIC_UNKNOWN
  931. };
  932. static const ArBasicKind g_Sampler3DCT[] =
  933. {
  934. AR_OBJECT_SAMPLER3D,
  935. AR_BASIC_UNKNOWN
  936. };
  937. static const ArBasicKind g_SamplerCUBECT[] =
  938. {
  939. AR_OBJECT_SAMPLERCUBE,
  940. AR_BASIC_UNKNOWN
  941. };
  942. static const ArBasicKind g_SamplerCmpCT[] =
  943. {
  944. AR_OBJECT_SAMPLERCOMPARISON,
  945. AR_BASIC_UNKNOWN
  946. };
  947. static const ArBasicKind g_SamplerCT[] =
  948. {
  949. AR_OBJECT_SAMPLER,
  950. AR_BASIC_UNKNOWN
  951. };
  952. static const ArBasicKind g_Texture2DCT[] =
  953. {
  954. AR_OBJECT_TEXTURE2D,
  955. AR_BASIC_UNKNOWN
  956. };
  957. static const ArBasicKind g_Texture2DArrayCT[] =
  958. {
  959. AR_OBJECT_TEXTURE2D_ARRAY,
  960. AR_BASIC_UNKNOWN
  961. };
  962. static const ArBasicKind g_ResourceCT[] = {AR_OBJECT_HEAP_RESOURCE,
  963. AR_BASIC_UNKNOWN};
  964. static const ArBasicKind g_RayDescCT[] =
  965. {
  966. AR_OBJECT_RAY_DESC,
  967. AR_BASIC_UNKNOWN
  968. };
  969. static const ArBasicKind g_AccelerationStructCT[] =
  970. {
  971. AR_OBJECT_ACCELERATION_STRUCT,
  972. AR_BASIC_UNKNOWN
  973. };
  974. static const ArBasicKind g_UDTCT[] =
  975. {
  976. AR_OBJECT_USER_DEFINED_TYPE,
  977. AR_BASIC_UNKNOWN
  978. };
  979. static const ArBasicKind g_StringCT[] =
  980. {
  981. AR_OBJECT_STRING_LITERAL,
  982. AR_OBJECT_STRING,
  983. AR_BASIC_UNKNOWN
  984. };
  985. static const ArBasicKind g_NullCT[] =
  986. {
  987. AR_OBJECT_NULL,
  988. AR_BASIC_UNKNOWN
  989. };
  990. static const ArBasicKind g_WaveCT[] =
  991. {
  992. AR_OBJECT_WAVE,
  993. AR_BASIC_UNKNOWN
  994. };
  995. static const ArBasicKind g_UInt64CT[] =
  996. {
  997. AR_BASIC_UINT64,
  998. AR_BASIC_UNKNOWN
  999. };
  1000. static const ArBasicKind g_Float16CT[] =
  1001. {
  1002. AR_BASIC_FLOAT16,
  1003. AR_BASIC_LITERAL_FLOAT,
  1004. AR_BASIC_UNKNOWN
  1005. };
  1006. static const ArBasicKind g_Int16CT[] =
  1007. {
  1008. AR_BASIC_INT16,
  1009. AR_BASIC_LITERAL_INT,
  1010. AR_BASIC_UNKNOWN
  1011. };
  1012. static const ArBasicKind g_UInt16CT[] =
  1013. {
  1014. AR_BASIC_UINT16,
  1015. AR_BASIC_LITERAL_INT,
  1016. AR_BASIC_UNKNOWN
  1017. };
  1018. static const ArBasicKind g_Numeric16OnlyCT[] =
  1019. {
  1020. AR_BASIC_FLOAT16,
  1021. AR_BASIC_INT16,
  1022. AR_BASIC_UINT16,
  1023. AR_BASIC_LITERAL_FLOAT,
  1024. AR_BASIC_LITERAL_INT,
  1025. AR_BASIC_NOCAST,
  1026. AR_BASIC_UNKNOWN
  1027. };
  1028. static const ArBasicKind g_Int32OnlyCT[] =
  1029. {
  1030. AR_BASIC_INT32,
  1031. AR_BASIC_UINT32,
  1032. AR_BASIC_LITERAL_INT,
  1033. AR_BASIC_NOCAST,
  1034. AR_BASIC_UNKNOWN
  1035. };
  1036. static const ArBasicKind g_Float32OnlyCT[] =
  1037. {
  1038. AR_BASIC_FLOAT32,
  1039. AR_BASIC_LITERAL_FLOAT,
  1040. AR_BASIC_NOCAST,
  1041. AR_BASIC_UNKNOWN
  1042. };
  1043. static const ArBasicKind g_Int64OnlyCT[] =
  1044. {
  1045. AR_BASIC_UINT64,
  1046. AR_BASIC_INT64,
  1047. AR_BASIC_LITERAL_INT,
  1048. AR_BASIC_NOCAST,
  1049. AR_BASIC_UNKNOWN
  1050. };
  1051. static const ArBasicKind g_AnyInt64CT[] =
  1052. {
  1053. AR_BASIC_INT64,
  1054. AR_BASIC_UINT64,
  1055. AR_BASIC_LITERAL_INT,
  1056. AR_BASIC_UNKNOWN
  1057. };
  1058. static const ArBasicKind g_Int8_4PackedCT[] =
  1059. {
  1060. AR_BASIC_INT8_4PACKED,
  1061. AR_BASIC_UINT32,
  1062. AR_BASIC_LITERAL_INT,
  1063. AR_BASIC_UNKNOWN
  1064. };
  1065. static const ArBasicKind g_UInt8_4PackedCT[] =
  1066. {
  1067. AR_BASIC_UINT8_4PACKED,
  1068. AR_BASIC_UINT32,
  1069. AR_BASIC_LITERAL_INT,
  1070. AR_BASIC_UNKNOWN
  1071. };
  1072. static const ArBasicKind g_AnyInt16Or32CT[] = {
  1073. AR_BASIC_INT32,
  1074. AR_BASIC_UINT32,
  1075. AR_BASIC_INT16,
  1076. AR_BASIC_UINT16,
  1077. AR_BASIC_LITERAL_INT,
  1078. AR_BASIC_UNKNOWN
  1079. };
  1080. static const ArBasicKind g_SInt16Or32OnlyCT[] =
  1081. {
  1082. AR_BASIC_INT32,
  1083. AR_BASIC_INT16,
  1084. AR_BASIC_LITERAL_INT,
  1085. AR_BASIC_NOCAST,
  1086. AR_BASIC_UNKNOWN
  1087. };
  1088. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  1089. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  1090. {
  1091. g_NullCT, // LICOMPTYPE_VOID
  1092. g_BoolCT, // LICOMPTYPE_BOOL
  1093. g_IntCT, // LICOMPTYPE_INT
  1094. g_UIntCT, // LICOMPTYPE_UINT
  1095. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  1096. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  1097. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  1098. g_FloatCT, // LICOMPTYPE_FLOAT
  1099. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  1100. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  1101. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  1102. g_DoubleCT, // LICOMPTYPE_DOUBLE
  1103. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  1104. g_NumericCT, // LICOMPTYPE_NUMERIC
  1105. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  1106. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  1107. g_AnyCT, // LICOMPTYPE_ANY
  1108. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  1109. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  1110. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  1111. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  1112. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  1113. g_SamplerCT, // LICOMPTYPE_SAMPLER
  1114. g_StringCT, // LICOMPTYPE_STRING
  1115. g_WaveCT, // LICOMPTYPE_WAVE
  1116. g_UInt64CT, // LICOMPTYPE_UINT64
  1117. g_Float16CT, // LICOMPTYPE_FLOAT16
  1118. g_Int16CT, // LICOMPTYPE_INT16
  1119. g_UInt16CT, // LICOMPTYPE_UINT16
  1120. g_Numeric16OnlyCT, // LICOMPTYPE_NUMERIC16_ONLY
  1121. g_RayDescCT, // LICOMPTYPE_RAYDESC
  1122. g_AccelerationStructCT, // LICOMPTYPE_ACCELERATION_STRUCT,
  1123. g_UDTCT, // LICOMPTYPE_USER_DEFINED_TYPE
  1124. g_Texture2DCT, // LICOMPTYPE_TEXTURE2D
  1125. g_Texture2DArrayCT, // LICOMPTYPE_TEXTURE2DARRAY
  1126. g_ResourceCT, // LICOMPTYPE_RESOURCE
  1127. g_Int32OnlyCT, // LICOMPTYPE_INT32_ONLY
  1128. g_Int64OnlyCT, // LICOMPTYPE_INT64_ONLY
  1129. g_AnyInt64CT, // LICOMPTYPE_ANY_INT64
  1130. g_Float32OnlyCT, // LICOMPTYPE_FLOAT32_ONLY
  1131. g_Int8_4PackedCT, // LICOMPTYPE_INT8_4PACKED
  1132. g_UInt8_4PackedCT, // LICOMPTYPE_UINT8_4PACKED
  1133. g_AnyInt16Or32CT, // LICOMPTYPE_ANY_INT16_OR_32
  1134. g_SInt16Or32OnlyCT, // LICOMPTYPE_SINT16_OR_32_ONLY
  1135. };
  1136. static_assert(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT,
  1137. "Intrinsic comp type table must be updated when new enumerants are added.");
  1138. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  1139. // Basic kind objects that are represented as HLSL structures or templates.
  1140. static
  1141. const ArBasicKind g_ArBasicKindsAsTypes[] =
  1142. {
  1143. AR_OBJECT_BUFFER, // Buffer
  1144. // AR_OBJECT_TEXTURE,
  1145. AR_OBJECT_TEXTURE1D, // Texture1D
  1146. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1147. AR_OBJECT_TEXTURE2D, // Texture2D
  1148. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1149. AR_OBJECT_TEXTURE3D, // Texture3D
  1150. AR_OBJECT_TEXTURECUBE, // TextureCube
  1151. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1152. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1153. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1154. AR_OBJECT_SAMPLER,
  1155. //AR_OBJECT_SAMPLER1D,
  1156. //AR_OBJECT_SAMPLER2D,
  1157. //AR_OBJECT_SAMPLER3D,
  1158. //AR_OBJECT_SAMPLERCUBE,
  1159. AR_OBJECT_SAMPLERCOMPARISON,
  1160. AR_OBJECT_CONSTANT_BUFFER,
  1161. AR_OBJECT_TEXTURE_BUFFER,
  1162. AR_OBJECT_POINTSTREAM,
  1163. AR_OBJECT_LINESTREAM,
  1164. AR_OBJECT_TRIANGLESTREAM,
  1165. AR_OBJECT_INPUTPATCH,
  1166. AR_OBJECT_OUTPUTPATCH,
  1167. AR_OBJECT_RWTEXTURE1D,
  1168. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1169. AR_OBJECT_RWTEXTURE2D,
  1170. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1171. AR_OBJECT_RWTEXTURE3D,
  1172. AR_OBJECT_RWBUFFER,
  1173. AR_OBJECT_BYTEADDRESS_BUFFER,
  1174. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1175. AR_OBJECT_STRUCTURED_BUFFER,
  1176. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1177. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1178. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1179. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1180. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1181. AR_OBJECT_ROVBUFFER,
  1182. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1183. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1184. AR_OBJECT_ROVTEXTURE1D,
  1185. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1186. AR_OBJECT_ROVTEXTURE2D,
  1187. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1188. AR_OBJECT_ROVTEXTURE3D,
  1189. AR_OBJECT_FEEDBACKTEXTURE2D,
  1190. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  1191. // SPIRV change starts
  1192. #ifdef ENABLE_SPIRV_CODEGEN
  1193. AR_OBJECT_VK_SUBPASS_INPUT,
  1194. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1195. #endif // ENABLE_SPIRV_CODEGEN
  1196. // SPIRV change ends
  1197. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1198. AR_OBJECT_WAVE,
  1199. AR_OBJECT_RAY_DESC,
  1200. AR_OBJECT_ACCELERATION_STRUCT,
  1201. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  1202. // subobjects
  1203. AR_OBJECT_STATE_OBJECT_CONFIG,
  1204. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1205. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1206. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1207. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1208. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1209. AR_OBJECT_TRIANGLE_HIT_GROUP,
  1210. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1211. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1212. AR_OBJECT_RAY_QUERY,
  1213. AR_OBJECT_HEAP_RESOURCE,
  1214. AR_OBJECT_HEAP_SAMPLER,
  1215. };
  1216. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1217. static
  1218. const uint8_t g_ArBasicKindsTemplateCount[] =
  1219. {
  1220. 1, // AR_OBJECT_BUFFER
  1221. // AR_OBJECT_TEXTURE,
  1222. 1, // AR_OBJECT_TEXTURE1D
  1223. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1224. 1, // AR_OBJECT_TEXTURE2D
  1225. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1226. 1, // AR_OBJECT_TEXTURE3D
  1227. 1, // AR_OBJECT_TEXTURECUBE
  1228. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1229. 2, // AR_OBJECT_TEXTURE2DMS
  1230. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1231. 0, // AR_OBJECT_SAMPLER
  1232. //AR_OBJECT_SAMPLER1D,
  1233. //AR_OBJECT_SAMPLER2D,
  1234. //AR_OBJECT_SAMPLER3D,
  1235. //AR_OBJECT_SAMPLERCUBE,
  1236. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1237. 1, //AR_OBJECT_CONSTANT_BUFFER,
  1238. 1, //AR_OBJECT_TEXTURE_BUFFER,
  1239. 1, // AR_OBJECT_POINTSTREAM
  1240. 1, // AR_OBJECT_LINESTREAM
  1241. 1, // AR_OBJECT_TRIANGLESTREAM
  1242. 2, // AR_OBJECT_INPUTPATCH
  1243. 2, // AR_OBJECT_OUTPUTPATCH
  1244. 1, // AR_OBJECT_RWTEXTURE1D
  1245. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1246. 1, // AR_OBJECT_RWTEXTURE2D
  1247. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1248. 1, // AR_OBJECT_RWTEXTURE3D
  1249. 1, // AR_OBJECT_RWBUFFER
  1250. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1251. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1252. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1253. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1254. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1255. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1256. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1257. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1258. 1, // AR_OBJECT_ROVBUFFER
  1259. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1260. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1261. 1, // AR_OBJECT_ROVTEXTURE1D
  1262. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1263. 1, // AR_OBJECT_ROVTEXTURE2D
  1264. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1265. 1, // AR_OBJECT_ROVTEXTURE3D
  1266. 1, // AR_OBJECT_FEEDBACKTEXTURE2D
  1267. 1, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1268. // SPIRV change starts
  1269. #ifdef ENABLE_SPIRV_CODEGEN
  1270. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1271. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1272. #endif // ENABLE_SPIRV_CODEGEN
  1273. // SPIRV change ends
  1274. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1275. 0, // AR_OBJECT_WAVE
  1276. 0, // AR_OBJECT_RAY_DESC
  1277. 0, // AR_OBJECT_ACCELERATION_STRUCT
  1278. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1279. 0, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1280. 0, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1281. 0, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1282. 0, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1283. 0, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1284. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1285. 0, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1286. 0, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1287. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1288. 1, // AR_OBJECT_RAY_QUERY,
  1289. 0, // AR_OBJECT_HEAP_RESOURCE,
  1290. 0, // AR_OBJECT_HEAP_SAMPLER,
  1291. };
  1292. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1293. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1294. struct SubscriptOperatorRecord
  1295. {
  1296. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1297. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1298. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1299. };
  1300. // Subscript operators for objects that are represented as HLSL structures or templates.
  1301. static
  1302. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1303. {
  1304. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1305. // AR_OBJECT_TEXTURE,
  1306. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1307. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1308. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1309. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1310. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1311. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1312. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1313. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1314. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1315. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1316. //AR_OBJECT_SAMPLER1D,
  1317. //AR_OBJECT_SAMPLER2D,
  1318. //AR_OBJECT_SAMPLER3D,
  1319. //AR_OBJECT_SAMPLERCUBE,
  1320. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1321. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSTANT_BUFFER
  1322. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURE_BUFFER
  1323. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1324. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1325. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1326. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1327. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1328. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1329. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1330. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1331. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1332. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1333. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1334. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1335. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1336. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1337. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1338. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1339. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1340. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1341. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1342. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1343. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1344. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1345. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1346. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1347. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1348. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1349. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1350. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D
  1351. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1352. // SPIRV change starts
  1353. #ifdef ENABLE_SPIRV_CODEGEN
  1354. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1355. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1356. #endif // ENABLE_SPIRV_CODEGEN
  1357. // SPIRV change ends
  1358. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1359. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_WAVE
  1360. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_DESC
  1361. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ACCELERATION_STRUCT
  1362. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1363. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1364. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1365. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1366. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1367. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1368. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1369. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1370. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1371. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1372. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_QUERY,
  1373. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_HEAP_RESOURCE,
  1374. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_HEAP_SAMPLER,
  1375. };
  1376. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1377. // Type names for ArBasicKind values.
  1378. static
  1379. const char* g_ArBasicTypeNames[] =
  1380. {
  1381. "bool", "float", "half", "half", "float", "double",
  1382. "int", "sbyte", "byte", "short", "ushort",
  1383. "int", "uint", "long", "ulong",
  1384. "min10float", "min16float",
  1385. "min12int", "min16int", "min16uint",
  1386. "int8_t4_packed", "uint8_t4_packed",
  1387. "enum",
  1388. "<count>",
  1389. "<none>",
  1390. "<unknown>",
  1391. "<nocast>",
  1392. "<dependent>",
  1393. "<pointer>",
  1394. "enum class",
  1395. "null",
  1396. "literal string",
  1397. "string",
  1398. // "texture",
  1399. "Texture1D",
  1400. "Texture1DArray",
  1401. "Texture2D",
  1402. "Texture2DArray",
  1403. "Texture3D",
  1404. "TextureCube",
  1405. "TextureCubeArray",
  1406. "Texture2DMS",
  1407. "Texture2DMSArray",
  1408. "SamplerState",
  1409. "sampler1D",
  1410. "sampler2D",
  1411. "sampler3D",
  1412. "samplerCUBE",
  1413. "SamplerComparisonState",
  1414. "Buffer",
  1415. "RenderTargetView",
  1416. "DepthStencilView",
  1417. "ComputeShader",
  1418. "DomainShader",
  1419. "GeometryShader",
  1420. "HullShader",
  1421. "PixelShader",
  1422. "VertexShader",
  1423. "pixelfragment",
  1424. "vertexfragment",
  1425. "StateBlock",
  1426. "Rasterizer",
  1427. "DepthStencil",
  1428. "Blend",
  1429. "PointStream",
  1430. "LineStream",
  1431. "TriangleStream",
  1432. "InputPatch",
  1433. "OutputPatch",
  1434. "RWTexture1D",
  1435. "RWTexture1DArray",
  1436. "RWTexture2D",
  1437. "RWTexture2DArray",
  1438. "RWTexture3D",
  1439. "RWBuffer",
  1440. "ByteAddressBuffer",
  1441. "RWByteAddressBuffer",
  1442. "StructuredBuffer",
  1443. "RWStructuredBuffer",
  1444. "RWStructuredBuffer(Incrementable)",
  1445. "RWStructuredBuffer(Decrementable)",
  1446. "AppendStructuredBuffer",
  1447. "ConsumeStructuredBuffer",
  1448. "ConstantBuffer",
  1449. "TextureBuffer",
  1450. "RasterizerOrderedBuffer",
  1451. "RasterizerOrderedByteAddressBuffer",
  1452. "RasterizerOrderedStructuredBuffer",
  1453. "RasterizerOrderedTexture1D",
  1454. "RasterizerOrderedTexture1DArray",
  1455. "RasterizerOrderedTexture2D",
  1456. "RasterizerOrderedTexture2DArray",
  1457. "RasterizerOrderedTexture3D",
  1458. "FeedbackTexture2D",
  1459. "FeedbackTexture2DArray",
  1460. // SPIRV change starts
  1461. #ifdef ENABLE_SPIRV_CODEGEN
  1462. "SubpassInput",
  1463. "SubpassInputMS",
  1464. #endif // ENABLE_SPIRV_CODEGEN
  1465. // SPIRV change ends
  1466. "<internal inner type object>",
  1467. "deprecated effect object",
  1468. "wave_t",
  1469. "RayDesc",
  1470. "RaytracingAccelerationStructure",
  1471. "user defined type",
  1472. "BuiltInTriangleIntersectionAttributes",
  1473. // subobjects
  1474. "StateObjectConfig",
  1475. "GlobalRootSignature",
  1476. "LocalRootSignature",
  1477. "SubobjectToExportsAssociation",
  1478. "RaytracingShaderConfig",
  1479. "RaytracingPipelineConfig",
  1480. "TriangleHitGroup",
  1481. "ProceduralPrimitiveHitGroup",
  1482. "RaytracingPipelineConfig1",
  1483. "RayQuery",
  1484. "HEAP_Resource",
  1485. "HEAP_Sampler",
  1486. };
  1487. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1488. static bool IsValidBasicKind(ArBasicKind kind) {
  1489. return kind != AR_BASIC_COUNT &&
  1490. kind != AR_BASIC_NONE &&
  1491. kind != AR_BASIC_UNKNOWN &&
  1492. kind != AR_BASIC_NOCAST &&
  1493. kind != AR_BASIC_POINTER &&
  1494. kind != AR_OBJECT_RENDERTARGETVIEW &&
  1495. kind != AR_OBJECT_DEPTHSTENCILVIEW &&
  1496. kind != AR_OBJECT_COMPUTESHADER &&
  1497. kind != AR_OBJECT_DOMAINSHADER &&
  1498. kind != AR_OBJECT_GEOMETRYSHADER &&
  1499. kind != AR_OBJECT_HULLSHADER &&
  1500. kind != AR_OBJECT_PIXELSHADER &&
  1501. kind != AR_OBJECT_VERTEXSHADER &&
  1502. kind != AR_OBJECT_PIXELFRAGMENT &&
  1503. kind != AR_OBJECT_VERTEXFRAGMENT;
  1504. }
  1505. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1506. #define DXASSERT_VALIDBASICKIND(kind) \
  1507. DXASSERT(IsValidBasicKind(kind), "otherwise caller is using a special flag or an unsupported kind value");
  1508. static
  1509. const char* g_DeprecatedEffectObjectNames[] =
  1510. {
  1511. // These are case insensitive in fxc, but we'll just create two case aliases
  1512. // to capture the majority of cases
  1513. "texture", "Texture",
  1514. "pixelshader", "PixelShader",
  1515. "vertexshader", "VertexShader",
  1516. // These are case sensitive in fxc
  1517. "pixelfragment", // 13
  1518. "vertexfragment", // 14
  1519. "ComputeShader", // 13
  1520. "DomainShader", // 12
  1521. "GeometryShader", // 14
  1522. "HullShader", // 10
  1523. "BlendState", // 10
  1524. "DepthStencilState",// 17
  1525. "DepthStencilView", // 16
  1526. "RasterizerState", // 15
  1527. "RenderTargetView", // 16
  1528. };
  1529. static bool IsVariadicIntrinsicFunction(const HLSL_INTRINSIC *fn) {
  1530. return fn->pArgs[fn->uNumArgs - 1].uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1531. }
  1532. static bool IsVariadicArgument(const HLSL_INTRINSIC_ARGUMENT &arg) {
  1533. return arg.uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1534. }
  1535. static hlsl::ParameterModifier
  1536. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1537. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1538. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1539. }
  1540. if (pArg->qwUsage == AR_QUAL_OUT) {
  1541. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1542. }
  1543. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1544. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1545. }
  1546. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1547. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1548. // The first argument is the return value, which isn't included.
  1549. UINT i = 1, size = paramMods.size();
  1550. for (; i < pIntrinsic->uNumArgs; ++i) {
  1551. // Once we reach varargs we can break out of this loop.
  1552. if (IsVariadicArgument(pIntrinsic->pArgs[i]))
  1553. break;
  1554. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1555. }
  1556. // For variadic functions, any argument not explicitly specified will be
  1557. // considered an input argument.
  1558. if (IsVariadicIntrinsicFunction(pIntrinsic)) {
  1559. for (; i < size; ++i) {
  1560. paramMods.push_back(
  1561. hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In));
  1562. }
  1563. }
  1564. }
  1565. static bool IsAtomicOperation(IntrinsicOp op) {
  1566. switch (op) {
  1567. case IntrinsicOp::IOP_InterlockedAdd:
  1568. case IntrinsicOp::IOP_InterlockedAnd:
  1569. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1570. case IntrinsicOp::IOP_InterlockedCompareStore:
  1571. case IntrinsicOp::IOP_InterlockedCompareExchangeFloatBitwise:
  1572. case IntrinsicOp::IOP_InterlockedCompareStoreFloatBitwise:
  1573. case IntrinsicOp::IOP_InterlockedExchange:
  1574. case IntrinsicOp::IOP_InterlockedMax:
  1575. case IntrinsicOp::IOP_InterlockedMin:
  1576. case IntrinsicOp::IOP_InterlockedOr:
  1577. case IntrinsicOp::IOP_InterlockedXor:
  1578. case IntrinsicOp::MOP_InterlockedAdd:
  1579. case IntrinsicOp::MOP_InterlockedAnd:
  1580. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1581. case IntrinsicOp::MOP_InterlockedCompareStore:
  1582. case IntrinsicOp::MOP_InterlockedExchange:
  1583. case IntrinsicOp::MOP_InterlockedMax:
  1584. case IntrinsicOp::MOP_InterlockedMin:
  1585. case IntrinsicOp::MOP_InterlockedOr:
  1586. case IntrinsicOp::MOP_InterlockedXor:
  1587. case IntrinsicOp::MOP_InterlockedAdd64:
  1588. case IntrinsicOp::MOP_InterlockedAnd64:
  1589. case IntrinsicOp::MOP_InterlockedCompareExchange64:
  1590. case IntrinsicOp::MOP_InterlockedCompareStore64:
  1591. case IntrinsicOp::MOP_InterlockedExchange64:
  1592. case IntrinsicOp::MOP_InterlockedMax64:
  1593. case IntrinsicOp::MOP_InterlockedMin64:
  1594. case IntrinsicOp::MOP_InterlockedOr64:
  1595. case IntrinsicOp::MOP_InterlockedXor64:
  1596. case IntrinsicOp::MOP_InterlockedExchangeFloat:
  1597. case IntrinsicOp::MOP_InterlockedCompareExchangeFloatBitwise:
  1598. case IntrinsicOp::MOP_InterlockedCompareStoreFloatBitwise:
  1599. return true;
  1600. default:
  1601. return false;
  1602. }
  1603. }
  1604. static bool IsBuiltinTable(LPCSTR tableName) {
  1605. return tableName == kBuiltinIntrinsicTableName;
  1606. }
  1607. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1608. LPCSTR tableName, LPCSTR lowering,
  1609. const HLSL_INTRINSIC *pIntrinsic) {
  1610. unsigned opcode = (unsigned)pIntrinsic->Op;
  1611. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1612. QualType Ty = FD->getReturnType();
  1613. if (pIntrinsic->iOverloadParamIndex != -1) {
  1614. const FunctionProtoType *FT =
  1615. FD->getFunctionType()->getAs<FunctionProtoType>();
  1616. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1617. // To go thru reference type.
  1618. if (Ty->isReferenceType())
  1619. Ty = Ty.getNonReferenceType();
  1620. }
  1621. // TODO: refine the code for getting element type
  1622. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1623. Ty = VecTy->getElementType();
  1624. }
  1625. // Make sure to use unsigned op when return type is 'unsigned' matrix
  1626. bool isUnsignedMatOp =
  1627. IsHLSLMatType(Ty) && GetHLSLMatElementType(Ty)->isUnsignedIntegerType();
  1628. if (Ty->isUnsignedIntegerType() || isUnsignedMatOp) {
  1629. opcode = hlsl::GetUnsignedOpcode(opcode);
  1630. }
  1631. }
  1632. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1633. if (pIntrinsic->bReadNone)
  1634. FD->addAttr(ConstAttr::CreateImplicit(context));
  1635. if (pIntrinsic->bReadOnly)
  1636. FD->addAttr(PureAttr::CreateImplicit(context));
  1637. if (pIntrinsic->bIsWave)
  1638. FD->addAttr(HLSLWaveSensitiveAttr::CreateImplicit(context));
  1639. }
  1640. static
  1641. FunctionDecl *AddHLSLIntrinsicFunction(
  1642. ASTContext &context, _In_ NamespaceDecl *NS,
  1643. LPCSTR tableName, LPCSTR lowering,
  1644. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1645. std::vector<QualType> *functionArgQualTypesVector)
  1646. {
  1647. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1648. std::vector<QualType> &functionArgQualTypes = *functionArgQualTypesVector;
  1649. const size_t functionArgTypeCount = functionArgQualTypes.size();
  1650. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  1651. DXASSERT(isVariadic || functionArgTypeCount - 1 <= g_MaxIntrinsicParamCount,
  1652. "otherwise g_MaxIntrinsicParamCount should be larger");
  1653. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1654. if (isVariadic) {
  1655. // For variadic functions, the number of arguments is larger than the
  1656. // function declaration signature.
  1657. paramMods.resize(functionArgTypeCount);
  1658. }
  1659. InitParamMods(pIntrinsic, paramMods);
  1660. // Change dest address into reference type for atomic.
  1661. if (IsBuiltinTable(tableName)) {
  1662. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1663. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1664. "else operation was misrecognized");
  1665. functionArgQualTypes[kAtomicDstOperandIdx] =
  1666. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1667. }
  1668. }
  1669. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1670. // Change out/inout param to reference type.
  1671. if (paramMods[i-1].isAnyOut()) {
  1672. QualType Ty = functionArgQualTypes[i];
  1673. // Aggregate type will be indirect param convert to pointer type.
  1674. // Don't need add reference for it.
  1675. if ((!Ty->isArrayType() && !Ty->isRecordType()) ||
  1676. hlsl::IsHLSLVecMatType(Ty)) {
  1677. functionArgQualTypes[i] = context.getLValueReferenceType(Ty);
  1678. }
  1679. }
  1680. }
  1681. IdentifierInfo &functionId = context.Idents.get(
  1682. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1683. DeclarationName functionName(&functionId);
  1684. auto protoInfo = clang::FunctionProtoType::ExtProtoInfo();
  1685. protoInfo.Variadic = isVariadic;
  1686. // functionArgQualTypes first element is the function return type, and
  1687. // function argument types start at index 1.
  1688. const QualType fnReturnType = functionArgQualTypes[0];
  1689. std::vector<QualType> fnArgTypes(functionArgQualTypes.begin() + 1,
  1690. functionArgQualTypes.end());
  1691. QualType functionType =
  1692. context.getFunctionType(fnReturnType, fnArgTypes, protoInfo, paramMods);
  1693. FunctionDecl *functionDecl = FunctionDecl::Create(
  1694. context, currentDeclContext, NoLoc,
  1695. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1696. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1697. currentDeclContext->addDecl(functionDecl);
  1698. functionDecl->setLexicalDeclContext(currentDeclContext);
  1699. // put under hlsl namespace
  1700. functionDecl->setDeclContext(NS);
  1701. // Add intrinsic attribute
  1702. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1703. llvm::SmallVector<ParmVarDecl *, 4> paramDecls;
  1704. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1705. // For variadic functions all non-explicit arguments will have the same
  1706. // name: "..."
  1707. std::string name = i < pIntrinsic->uNumArgs - 1
  1708. ? pIntrinsic->pArgs[i].pName
  1709. : pIntrinsic->pArgs[pIntrinsic->uNumArgs - 1].pName;
  1710. IdentifierInfo &parameterId =
  1711. context.Idents.get(name, tok::TokenKind::identifier);
  1712. ParmVarDecl *paramDecl =
  1713. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1714. functionArgQualTypes[i], nullptr,
  1715. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1716. functionDecl->addDecl(paramDecl);
  1717. paramDecls.push_back(paramDecl);
  1718. }
  1719. functionDecl->setParams(paramDecls);
  1720. functionDecl->setImplicit(true);
  1721. return functionDecl;
  1722. }
  1723. /// <summary>
  1724. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1725. /// </summary>
  1726. static
  1727. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1728. {
  1729. DXASSERT_NOMSG(expr != nullptr);
  1730. expr = expr->IgnoreParens();
  1731. return
  1732. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1733. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1734. }
  1735. /// <summary>
  1736. /// Silences diagnostics for the initialization sequence, typically because they have already
  1737. /// been emitted.
  1738. /// </summary>
  1739. static
  1740. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1741. {
  1742. DXASSERT_NOMSG(initSequence != nullptr);
  1743. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1744. }
  1745. class UsedIntrinsic
  1746. {
  1747. public:
  1748. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1749. {
  1750. // The canonical representations are unique'd in an ASTContext, and so these
  1751. // should be stable.
  1752. return RHS.getTypePtr() - LHS.getTypePtr();
  1753. }
  1754. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1755. {
  1756. // The intrinsics are defined in a single static table, and so should be stable.
  1757. return RHS - LHS;
  1758. }
  1759. int compare(const UsedIntrinsic& other) const
  1760. {
  1761. // Check whether it's the same instance.
  1762. if (this == &other) return 0;
  1763. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1764. if (result != 0) return result;
  1765. // At this point, it's the exact same intrinsic name.
  1766. // Compare the arguments for ordering then.
  1767. DXASSERT(IsVariadicIntrinsicFunction(m_intrinsicSource) ||
  1768. m_args.size() == other.m_args.size(),
  1769. "only variadic intrinsics can be overloaded on argument count");
  1770. // For variadic functions with different number of args, order by number of
  1771. // arguments.
  1772. if (m_args.size() != other.m_args.size())
  1773. return m_args.size() - other.m_args.size();
  1774. for (size_t i = 0; i < m_args.size(); i++) {
  1775. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1776. if (argComparison != 0) return argComparison;
  1777. }
  1778. // Exactly the same.
  1779. return 0;
  1780. }
  1781. public:
  1782. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, llvm::ArrayRef<QualType> args)
  1783. : m_args(args.begin(), args.end()), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1784. {
  1785. }
  1786. void setFunctionDecl(FunctionDecl* value) const
  1787. {
  1788. DXASSERT(value != nullptr, "no reason to clear this out");
  1789. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1790. m_functionDecl = value;
  1791. }
  1792. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1793. bool operator==(const UsedIntrinsic& other) const
  1794. {
  1795. return compare(other) == 0;
  1796. }
  1797. bool operator<(const UsedIntrinsic& other) const
  1798. {
  1799. return compare(other) < 0;
  1800. }
  1801. private:
  1802. std::vector<QualType> m_args;
  1803. const HLSL_INTRINSIC* m_intrinsicSource;
  1804. mutable FunctionDecl* m_functionDecl;
  1805. };
  1806. template <typename T>
  1807. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1808. {
  1809. if (ptr != nullptr)
  1810. {
  1811. *ptr = value;
  1812. }
  1813. }
  1814. static bool CombineBasicTypes(ArBasicKind LeftKind,
  1815. ArBasicKind RightKind,
  1816. _Out_ ArBasicKind* pOutKind)
  1817. {
  1818. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1819. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1820. return false;
  1821. }
  1822. if (LeftKind == RightKind) {
  1823. *pOutKind = LeftKind;
  1824. return true;
  1825. }
  1826. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1827. UINT uRightProps = GetBasicKindProps(RightKind);
  1828. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1829. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1830. UINT uBothFlags = uLeftProps & uRightProps;
  1831. UINT uEitherFlags = uLeftProps | uRightProps;
  1832. // Notes: all numeric types have either BPROP_FLOATING or BPROP_INTEGER (even bool)
  1833. // unsigned only applies to non-literal ints, not bool or enum
  1834. // literals, bool, and enum are all BPROP_BITS0
  1835. if (uBothFlags & BPROP_BOOLEAN) {
  1836. *pOutKind = AR_BASIC_BOOL;
  1837. return true;
  1838. }
  1839. bool bFloatResult = 0 != (uEitherFlags & BPROP_FLOATING);
  1840. if (uBothFlags & BPROP_LITERAL) {
  1841. *pOutKind = bFloatResult ? AR_BASIC_LITERAL_FLOAT : AR_BASIC_LITERAL_INT;
  1842. return true;
  1843. }
  1844. // Starting approximation of result properties:
  1845. // - float if either are float, otherwise int (see Notes above)
  1846. // - min/partial precision if both have same flag
  1847. // - if not float, add unsigned if either is unsigned
  1848. UINT uResultFlags =
  1849. (uBothFlags & (BPROP_INTEGER | BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION)) |
  1850. (uEitherFlags & BPROP_FLOATING) |
  1851. (!bFloatResult ? (uEitherFlags & BPROP_UNSIGNED) : 0);
  1852. // If one is literal/bool/enum, use min/partial precision from the other
  1853. if (uEitherFlags & (BPROP_LITERAL | BPROP_BOOLEAN | BPROP_ENUM)) {
  1854. uResultFlags |= uEitherFlags & (BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION);
  1855. }
  1856. // Now if we have partial precision, we know the result must be half
  1857. if (uResultFlags & BPROP_PARTIAL_PRECISION) {
  1858. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1859. return true;
  1860. }
  1861. // uBits are already initialized to max of either side, so now:
  1862. // if only one is float, get result props from float side
  1863. // min16float + int -> min16float
  1864. // also take min precision from that side
  1865. if (bFloatResult && 0 == (uBothFlags & BPROP_FLOATING)) {
  1866. uResultFlags = (uLeftProps & BPROP_FLOATING) ? uLeftProps : uRightProps;
  1867. uBits = GET_BPROP_BITS(uResultFlags);
  1868. uResultFlags &= ~BPROP_LITERAL;
  1869. }
  1870. bool bMinPrecisionResult = uResultFlags & BPROP_MIN_PRECISION;
  1871. // if uBits is 0 here, upgrade to 32-bits
  1872. // this happens if bool, literal or enum on both sides,
  1873. // or if float came from literal side
  1874. if (uBits == BPROP_BITS0)
  1875. uBits = BPROP_BITS32;
  1876. DXASSERT(uBits != BPROP_BITS0, "CombineBasicTypes: uBits should not be zero at this point");
  1877. DXASSERT(uBits != BPROP_BITS8, "CombineBasicTypes: 8-bit types not supported at this time");
  1878. if (bMinPrecisionResult) {
  1879. DXASSERT(uBits < BPROP_BITS32, "CombineBasicTypes: min-precision result must be less than 32-bits");
  1880. } else {
  1881. DXASSERT(uBits > BPROP_BITS12, "CombineBasicTypes: 10 or 12 bit result must be min precision");
  1882. }
  1883. if (bFloatResult) {
  1884. DXASSERT(uBits != BPROP_BITS12, "CombineBasicTypes: 12-bit result must be int");
  1885. } else {
  1886. DXASSERT(uBits != BPROP_BITS10, "CombineBasicTypes: 10-bit result must be float");
  1887. }
  1888. if (uBits == BPROP_BITS12) {
  1889. DXASSERT(!(uResultFlags & BPROP_UNSIGNED), "CombineBasicTypes: 12-bit result must not be unsigned");
  1890. }
  1891. if (bFloatResult) {
  1892. switch (uBits) {
  1893. case BPROP_BITS10:
  1894. *pOutKind = AR_BASIC_MIN10FLOAT;
  1895. break;
  1896. case BPROP_BITS16:
  1897. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  1898. break;
  1899. case BPROP_BITS32:
  1900. *pOutKind = AR_BASIC_FLOAT32;
  1901. break;
  1902. case BPROP_BITS64:
  1903. *pOutKind = AR_BASIC_FLOAT64;
  1904. break;
  1905. default:
  1906. DXASSERT(false, "Unexpected bit count for float result");
  1907. break;
  1908. }
  1909. } else {
  1910. // int or unsigned int
  1911. switch (uBits) {
  1912. case BPROP_BITS12:
  1913. *pOutKind = AR_BASIC_MIN12INT;
  1914. break;
  1915. case BPROP_BITS16:
  1916. if (uResultFlags & BPROP_UNSIGNED)
  1917. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  1918. else
  1919. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  1920. break;
  1921. case BPROP_BITS32:
  1922. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT32 : AR_BASIC_INT32;
  1923. break;
  1924. case BPROP_BITS64:
  1925. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT64 : AR_BASIC_INT64;
  1926. break;
  1927. default:
  1928. DXASSERT(false, "Unexpected bit count for int result");
  1929. break;
  1930. }
  1931. }
  1932. return true;
  1933. }
  1934. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1935. {
  1936. };
  1937. static
  1938. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1939. {
  1940. DXASSERT_NOMSG(intrinsics != nullptr);
  1941. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1942. switch (kind)
  1943. {
  1944. case AR_OBJECT_TRIANGLESTREAM:
  1945. case AR_OBJECT_POINTSTREAM:
  1946. case AR_OBJECT_LINESTREAM:
  1947. *intrinsics = g_StreamMethods;
  1948. *intrinsicCount = _countof(g_StreamMethods);
  1949. break;
  1950. case AR_OBJECT_TEXTURE1D:
  1951. *intrinsics = g_Texture1DMethods;
  1952. *intrinsicCount = _countof(g_Texture1DMethods);
  1953. break;
  1954. case AR_OBJECT_TEXTURE1D_ARRAY:
  1955. *intrinsics = g_Texture1DArrayMethods;
  1956. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1957. break;
  1958. case AR_OBJECT_TEXTURE2D:
  1959. *intrinsics = g_Texture2DMethods;
  1960. *intrinsicCount = _countof(g_Texture2DMethods);
  1961. break;
  1962. case AR_OBJECT_TEXTURE2DMS:
  1963. *intrinsics = g_Texture2DMSMethods;
  1964. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1965. break;
  1966. case AR_OBJECT_TEXTURE2D_ARRAY:
  1967. *intrinsics = g_Texture2DArrayMethods;
  1968. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1969. break;
  1970. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1971. *intrinsics = g_Texture2DArrayMSMethods;
  1972. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1973. break;
  1974. case AR_OBJECT_TEXTURE3D:
  1975. *intrinsics = g_Texture3DMethods;
  1976. *intrinsicCount = _countof(g_Texture3DMethods);
  1977. break;
  1978. case AR_OBJECT_TEXTURECUBE:
  1979. *intrinsics = g_TextureCUBEMethods;
  1980. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1981. break;
  1982. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1983. *intrinsics = g_TextureCUBEArrayMethods;
  1984. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1985. break;
  1986. case AR_OBJECT_BUFFER:
  1987. *intrinsics = g_BufferMethods;
  1988. *intrinsicCount = _countof(g_BufferMethods);
  1989. break;
  1990. case AR_OBJECT_RWTEXTURE1D:
  1991. case AR_OBJECT_ROVTEXTURE1D:
  1992. *intrinsics = g_RWTexture1DMethods;
  1993. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1994. break;
  1995. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1996. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1997. *intrinsics = g_RWTexture1DArrayMethods;
  1998. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1999. break;
  2000. case AR_OBJECT_RWTEXTURE2D:
  2001. case AR_OBJECT_ROVTEXTURE2D:
  2002. *intrinsics = g_RWTexture2DMethods;
  2003. *intrinsicCount = _countof(g_RWTexture2DMethods);
  2004. break;
  2005. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  2006. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  2007. *intrinsics = g_RWTexture2DArrayMethods;
  2008. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  2009. break;
  2010. case AR_OBJECT_RWTEXTURE3D:
  2011. case AR_OBJECT_ROVTEXTURE3D:
  2012. *intrinsics = g_RWTexture3DMethods;
  2013. *intrinsicCount = _countof(g_RWTexture3DMethods);
  2014. break;
  2015. case AR_OBJECT_FEEDBACKTEXTURE2D:
  2016. *intrinsics = g_FeedbackTexture2DMethods;
  2017. *intrinsicCount = _countof(g_FeedbackTexture2DMethods);
  2018. break;
  2019. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  2020. *intrinsics = g_FeedbackTexture2DArrayMethods;
  2021. *intrinsicCount = _countof(g_FeedbackTexture2DArrayMethods);
  2022. break;
  2023. case AR_OBJECT_RWBUFFER:
  2024. case AR_OBJECT_ROVBUFFER:
  2025. *intrinsics = g_RWBufferMethods;
  2026. *intrinsicCount = _countof(g_RWBufferMethods);
  2027. break;
  2028. case AR_OBJECT_BYTEADDRESS_BUFFER:
  2029. *intrinsics = g_ByteAddressBufferMethods;
  2030. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  2031. break;
  2032. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  2033. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  2034. *intrinsics = g_RWByteAddressBufferMethods;
  2035. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  2036. break;
  2037. case AR_OBJECT_STRUCTURED_BUFFER:
  2038. *intrinsics = g_StructuredBufferMethods;
  2039. *intrinsicCount = _countof(g_StructuredBufferMethods);
  2040. break;
  2041. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  2042. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  2043. *intrinsics = g_RWStructuredBufferMethods;
  2044. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  2045. break;
  2046. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  2047. *intrinsics = g_AppendStructuredBufferMethods;
  2048. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  2049. break;
  2050. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  2051. *intrinsics = g_ConsumeStructuredBufferMethods;
  2052. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  2053. break;
  2054. case AR_OBJECT_RAY_QUERY:
  2055. *intrinsics = g_RayQueryMethods;
  2056. *intrinsicCount = _countof(g_RayQueryMethods);
  2057. break;
  2058. // SPIRV change starts
  2059. #ifdef ENABLE_SPIRV_CODEGEN
  2060. case AR_OBJECT_VK_SUBPASS_INPUT:
  2061. *intrinsics = g_VkSubpassInputMethods;
  2062. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  2063. break;
  2064. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  2065. *intrinsics = g_VkSubpassInputMSMethods;
  2066. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  2067. break;
  2068. #endif // ENABLE_SPIRV_CODEGEN
  2069. // SPIRV change ends
  2070. default:
  2071. *intrinsics = nullptr;
  2072. *intrinsicCount = 0;
  2073. break;
  2074. }
  2075. }
  2076. static
  2077. bool IsRowOrColumnVariable(size_t value)
  2078. {
  2079. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  2080. }
  2081. static
  2082. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  2083. {
  2084. return
  2085. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  2086. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  2087. value == LICOMPTYPE_ANY_FLOAT || // float or double
  2088. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  2089. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  2090. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  2091. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  2092. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  2093. value == LICOMPTYPE_ANY; // any time
  2094. }
  2095. static
  2096. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  2097. {
  2098. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  2099. }
  2100. static
  2101. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  2102. {
  2103. // Note that LITEMPLATE_OBJECT can accept different types, but it
  2104. // specifies a single 'layout'. In practice, this information is used
  2105. // together with a component type that specifies a single object.
  2106. return value == LITEMPLATE_ANY; // Any layout
  2107. }
  2108. static
  2109. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  2110. {
  2111. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  2112. }
  2113. static
  2114. bool TemplateHasDefaultType(ArBasicKind kind)
  2115. {
  2116. switch (kind) {
  2117. case AR_OBJECT_BUFFER:
  2118. case AR_OBJECT_TEXTURE1D:
  2119. case AR_OBJECT_TEXTURE2D:
  2120. case AR_OBJECT_TEXTURE3D:
  2121. case AR_OBJECT_TEXTURE1D_ARRAY:
  2122. case AR_OBJECT_TEXTURE2D_ARRAY:
  2123. case AR_OBJECT_TEXTURECUBE:
  2124. case AR_OBJECT_TEXTURECUBE_ARRAY:
  2125. // SPIRV change starts
  2126. #ifdef ENABLE_SPIRV_CODEGEN
  2127. case AR_OBJECT_VK_SUBPASS_INPUT:
  2128. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  2129. #endif // ENABLE_SPIRV_CODEGEN
  2130. // SPIRV change ends
  2131. return true;
  2132. default:
  2133. // Objects with default types return true. Everything else is false.
  2134. return false;
  2135. }
  2136. }
  2137. /// <summary>
  2138. /// Use this class to iterate over intrinsic definitions that come from an external source.
  2139. /// </summary>
  2140. class IntrinsicTableDefIter
  2141. {
  2142. private:
  2143. StringRef _typeName;
  2144. StringRef _functionName;
  2145. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  2146. const HLSL_INTRINSIC* _tableIntrinsic;
  2147. UINT64 _tableLookupCookie;
  2148. unsigned _tableIndex;
  2149. unsigned _argCount;
  2150. bool _firstChecked;
  2151. IntrinsicTableDefIter(
  2152. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2153. StringRef typeName,
  2154. StringRef functionName,
  2155. unsigned argCount) :
  2156. _typeName(typeName), _functionName(functionName), _tables(tables),
  2157. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  2158. _argCount(argCount), _firstChecked(false)
  2159. {
  2160. }
  2161. void CheckForIntrinsic() {
  2162. if (_tableIndex >= _tables.size()) {
  2163. return;
  2164. }
  2165. _firstChecked = true;
  2166. // TODO: review this - this will allocate at least once per string
  2167. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  2168. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  2169. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  2170. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  2171. _tableLookupCookie = 0;
  2172. _tableIntrinsic = nullptr;
  2173. }
  2174. }
  2175. void MoveToNext() {
  2176. for (;;) {
  2177. // If we don't have an intrinsic, try the following table.
  2178. if (_firstChecked && _tableIntrinsic == nullptr) {
  2179. _tableIndex++;
  2180. }
  2181. CheckForIntrinsic();
  2182. if (_tableIndex == _tables.size() ||
  2183. (_tableIntrinsic != nullptr &&
  2184. _tableIntrinsic->uNumArgs ==
  2185. (_argCount + 1))) // uNumArgs includes return
  2186. break;
  2187. }
  2188. }
  2189. public:
  2190. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2191. StringRef typeName,
  2192. StringRef functionName,
  2193. unsigned argCount)
  2194. {
  2195. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  2196. return result;
  2197. }
  2198. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  2199. {
  2200. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  2201. result._tableIndex = tables.size();
  2202. return result;
  2203. }
  2204. bool operator!=(const IntrinsicTableDefIter& other)
  2205. {
  2206. if (!_firstChecked) {
  2207. MoveToNext();
  2208. }
  2209. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  2210. }
  2211. const HLSL_INTRINSIC* operator*()
  2212. {
  2213. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  2214. return _tableIntrinsic;
  2215. }
  2216. LPCSTR GetTableName()
  2217. {
  2218. LPCSTR tableName = nullptr;
  2219. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  2220. return nullptr;
  2221. }
  2222. return tableName;
  2223. }
  2224. LPCSTR GetLoweringStrategy()
  2225. {
  2226. LPCSTR lowering = nullptr;
  2227. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  2228. return nullptr;
  2229. }
  2230. return lowering;
  2231. }
  2232. IntrinsicTableDefIter& operator++()
  2233. {
  2234. MoveToNext();
  2235. return *this;
  2236. }
  2237. };
  2238. /// <summary>
  2239. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2240. /// </summary>
  2241. class IntrinsicDefIter
  2242. {
  2243. const HLSL_INTRINSIC* _current;
  2244. const HLSL_INTRINSIC* _end;
  2245. IntrinsicTableDefIter _tableIter;
  2246. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2247. _current(value), _end(end), _tableIter(tableIter)
  2248. { }
  2249. public:
  2250. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2251. {
  2252. return IntrinsicDefIter(start, table + count, tableIter);
  2253. }
  2254. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2255. {
  2256. return IntrinsicDefIter(table + count, table + count, tableIter);
  2257. }
  2258. bool operator!=(const IntrinsicDefIter& other)
  2259. {
  2260. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2261. }
  2262. const HLSL_INTRINSIC* operator*()
  2263. {
  2264. return (_current != _end) ? _current : *_tableIter;
  2265. }
  2266. LPCSTR GetTableName()
  2267. {
  2268. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2269. }
  2270. LPCSTR GetLoweringStrategy()
  2271. {
  2272. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2273. }
  2274. IntrinsicDefIter& operator++()
  2275. {
  2276. if (_current != _end) {
  2277. const HLSL_INTRINSIC* next = _current + 1;
  2278. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2279. _current = next;
  2280. }
  2281. else {
  2282. _current = _end;
  2283. }
  2284. } else {
  2285. ++_tableIter;
  2286. }
  2287. return *this;
  2288. }
  2289. };
  2290. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2291. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2292. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2293. }
  2294. static void CreateSimpleField(clang::ASTContext &context, CXXRecordDecl *recordDecl, StringRef Name,
  2295. QualType Ty, AccessSpecifier access = AccessSpecifier::AS_public) {
  2296. IdentifierInfo &fieldId =
  2297. context.Idents.get(Name, tok::TokenKind::identifier);
  2298. TypeSourceInfo *filedTypeSource = context.getTrivialTypeSourceInfo(Ty, NoLoc);
  2299. const bool MutableFalse = false;
  2300. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  2301. FieldDecl *fieldDecl =
  2302. FieldDecl::Create(context, recordDecl, NoLoc, NoLoc, &fieldId, Ty,
  2303. filedTypeSource, nullptr, MutableFalse, initStyle);
  2304. fieldDecl->setAccess(access);
  2305. fieldDecl->setImplicit(true);
  2306. recordDecl->addDecl(fieldDecl);
  2307. }
  2308. // struct RayDesc
  2309. //{
  2310. // float3 Origin;
  2311. // float TMin;
  2312. // float3 Direction;
  2313. // float TMax;
  2314. //};
  2315. static CXXRecordDecl *CreateRayDescStruct(clang::ASTContext &context,
  2316. QualType float3Ty) {
  2317. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  2318. IdentifierInfo &rayDesc =
  2319. context.Idents.get(StringRef("RayDesc"), tok::TokenKind::identifier);
  2320. CXXRecordDecl *rayDescDecl = CXXRecordDecl::Create(
  2321. context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc,
  2322. &rayDesc, nullptr, DelayTypeCreationTrue);
  2323. rayDescDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2324. rayDescDecl->startDefinition();
  2325. QualType floatTy = context.FloatTy;
  2326. // float3 Origin;
  2327. CreateSimpleField(context, rayDescDecl, "Origin", float3Ty);
  2328. // float TMin;
  2329. CreateSimpleField(context, rayDescDecl, "TMin", floatTy);
  2330. // float3 Direction;
  2331. CreateSimpleField(context, rayDescDecl, "Direction", float3Ty);
  2332. // float TMax;
  2333. CreateSimpleField(context, rayDescDecl, "TMax", floatTy);
  2334. rayDescDecl->completeDefinition();
  2335. // Both declarations need to be present for correct handling.
  2336. currentDeclContext->addDecl(rayDescDecl);
  2337. rayDescDecl->setImplicit(true);
  2338. return rayDescDecl;
  2339. }
  2340. // struct BuiltInTriangleIntersectionAttributes
  2341. // {
  2342. // float2 barycentrics;
  2343. // };
  2344. static CXXRecordDecl *AddBuiltInTriangleIntersectionAttributes(ASTContext& context, QualType baryType) {
  2345. DeclContext *curDC = context.getTranslationUnitDecl();
  2346. IdentifierInfo &attributesId =
  2347. context.Idents.get(StringRef("BuiltInTriangleIntersectionAttributes"),
  2348. tok::TokenKind::identifier);
  2349. CXXRecordDecl *attributesDecl = CXXRecordDecl::Create(
  2350. context, TagTypeKind::TTK_Struct, curDC, NoLoc, NoLoc,
  2351. &attributesId, nullptr, DelayTypeCreationTrue);
  2352. attributesDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2353. attributesDecl->startDefinition();
  2354. // float2 barycentrics;
  2355. CreateSimpleField(context, attributesDecl, "barycentrics", baryType);
  2356. attributesDecl->completeDefinition();
  2357. attributesDecl->setImplicit(true);
  2358. curDC->addDecl(attributesDecl);
  2359. return attributesDecl;
  2360. }
  2361. //
  2362. // Subobjects
  2363. static CXXRecordDecl *StartSubobjectDecl(ASTContext& context, const char *name) {
  2364. IdentifierInfo &id = context.Idents.get(StringRef(name), tok::TokenKind::identifier);
  2365. CXXRecordDecl *decl = CXXRecordDecl::Create( context, TagTypeKind::TTK_Struct,
  2366. context.getTranslationUnitDecl(), NoLoc, NoLoc, &id, nullptr, DelayTypeCreationTrue);
  2367. decl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2368. decl->startDefinition();
  2369. return decl;
  2370. }
  2371. void FinishSubobjectDecl(ASTContext& context, CXXRecordDecl *decl) {
  2372. decl->completeDefinition();
  2373. context.getTranslationUnitDecl()->addDecl(decl);
  2374. decl->setImplicit(true);
  2375. }
  2376. // struct StateObjectConfig
  2377. // {
  2378. // uint32_t Flags;
  2379. // };
  2380. static CXXRecordDecl *CreateSubobjectStateObjectConfig(ASTContext& context) {
  2381. CXXRecordDecl *decl = StartSubobjectDecl(context, "StateObjectConfig");
  2382. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2383. FinishSubobjectDecl(context, decl);
  2384. return decl;
  2385. }
  2386. // struct GlobalRootSignature
  2387. // {
  2388. // string signature;
  2389. // };
  2390. static CXXRecordDecl *CreateSubobjectRootSignature(ASTContext& context, bool global) {
  2391. CXXRecordDecl *decl = StartSubobjectDecl(context, global ? "GlobalRootSignature" : "LocalRootSignature");
  2392. CreateSimpleField(context, decl, "Data", context.HLSLStringTy, AccessSpecifier::AS_private);
  2393. FinishSubobjectDecl(context, decl);
  2394. return decl;
  2395. }
  2396. // struct SubobjectToExportsAssociation
  2397. // {
  2398. // string Subobject;
  2399. // string Exports;
  2400. // };
  2401. static CXXRecordDecl *CreateSubobjectSubobjectToExportsAssoc(ASTContext& context) {
  2402. CXXRecordDecl *decl = StartSubobjectDecl(context, "SubobjectToExportsAssociation");
  2403. CreateSimpleField(context, decl, "Subobject", context.HLSLStringTy, AccessSpecifier::AS_private);
  2404. CreateSimpleField(context, decl, "Exports", context.HLSLStringTy, AccessSpecifier::AS_private);
  2405. FinishSubobjectDecl(context, decl);
  2406. return decl;
  2407. }
  2408. // struct RaytracingShaderConfig
  2409. // {
  2410. // uint32_t MaxPayloadSizeInBytes;
  2411. // uint32_t MaxAttributeSizeInBytes;
  2412. // };
  2413. static CXXRecordDecl *CreateSubobjectRaytracingShaderConfig(ASTContext& context) {
  2414. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingShaderConfig");
  2415. CreateSimpleField(context, decl, "MaxPayloadSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2416. CreateSimpleField(context, decl, "MaxAttributeSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2417. FinishSubobjectDecl(context, decl);
  2418. return decl;
  2419. }
  2420. // struct RaytracingPipelineConfig
  2421. // {
  2422. // uint32_t MaxTraceRecursionDepth;
  2423. // };
  2424. static CXXRecordDecl *CreateSubobjectRaytracingPipelineConfig(ASTContext& context) {
  2425. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingPipelineConfig");
  2426. CreateSimpleField(context, decl, "MaxTraceRecursionDepth", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2427. FinishSubobjectDecl(context, decl);
  2428. return decl;
  2429. }
  2430. // struct RaytracingPipelineConfig1
  2431. // {
  2432. // uint32_t MaxTraceRecursionDepth;
  2433. // uint32_t Flags;
  2434. // };
  2435. static CXXRecordDecl *
  2436. CreateSubobjectRaytracingPipelineConfig1(ASTContext &context) {
  2437. CXXRecordDecl *decl =
  2438. StartSubobjectDecl(context, "RaytracingPipelineConfig1");
  2439. CreateSimpleField(context, decl, "MaxTraceRecursionDepth",
  2440. context.UnsignedIntTy, AccessSpecifier::AS_private);
  2441. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy,
  2442. AccessSpecifier::AS_private);
  2443. FinishSubobjectDecl(context, decl);
  2444. return decl;
  2445. }
  2446. // struct TriangleHitGroup
  2447. // {
  2448. // string AnyHit;
  2449. // string ClosestHit;
  2450. // };
  2451. static CXXRecordDecl *CreateSubobjectTriangleHitGroup(ASTContext& context) {
  2452. CXXRecordDecl *decl = StartSubobjectDecl(context, "TriangleHitGroup");
  2453. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2454. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2455. FinishSubobjectDecl(context, decl);
  2456. return decl;
  2457. }
  2458. // struct ProceduralPrimitiveHitGroup
  2459. // {
  2460. // string AnyHit;
  2461. // string ClosestHit;
  2462. // string Intersection;
  2463. // };
  2464. static CXXRecordDecl *CreateSubobjectProceduralPrimitiveHitGroup(ASTContext& context) {
  2465. CXXRecordDecl *decl = StartSubobjectDecl(context, "ProceduralPrimitiveHitGroup");
  2466. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2467. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2468. CreateSimpleField(context, decl, "Intersection", context.HLSLStringTy, AccessSpecifier::AS_private);
  2469. FinishSubobjectDecl(context, decl);
  2470. return decl;
  2471. }
  2472. //
  2473. // This is similar to clang/Analysis/CallGraph, but the following differences
  2474. // motivate this:
  2475. //
  2476. // - track traversed vs. observed nodes explicitly
  2477. // - fully visit all reachable functions
  2478. // - merge graph visiting with checking for recursion
  2479. // - track global variables and types used (NYI)
  2480. //
  2481. namespace hlsl {
  2482. struct CallNode {
  2483. FunctionDecl *CallerFn;
  2484. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2485. };
  2486. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2487. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2488. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2489. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2490. // Returns the definition of a function.
  2491. // This serves two purposes - ignore built-in functions, and pick
  2492. // a single Decl * to be used in maps and sets.
  2493. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2494. if (!F) return nullptr;
  2495. if (F->doesThisDeclarationHaveABody()) return F;
  2496. F = F->getFirstDecl();
  2497. for (auto &&Candidate : F->redecls()) {
  2498. if (Candidate->doesThisDeclarationHaveABody()) {
  2499. return Candidate;
  2500. }
  2501. }
  2502. return nullptr;
  2503. }
  2504. // AST visitor that maintains visited and pending collections, as well
  2505. // as recording nodes of caller/callees.
  2506. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2507. private:
  2508. CallNodes &m_callNodes;
  2509. FunctionSet &m_visitedFunctions;
  2510. PendingFunctions &m_pendingFunctions;
  2511. FunctionDecl *m_source;
  2512. CallNodes::iterator m_sourceIt;
  2513. public:
  2514. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2515. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2516. : m_callNodes(callNodes),
  2517. m_visitedFunctions(visitedFunctions),
  2518. m_pendingFunctions(pendingFunctions) {}
  2519. void setSourceFn(FunctionDecl *F) {
  2520. F = getFunctionWithBody(F);
  2521. m_source = F;
  2522. m_sourceIt = m_callNodes.find(F);
  2523. }
  2524. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2525. ValueDecl *valueDecl = ref->getDecl();
  2526. RecordFunctionDecl(dyn_cast_or_null<FunctionDecl>(valueDecl));
  2527. return true;
  2528. }
  2529. bool VisitCXXMemberCallExpr(CXXMemberCallExpr* callExpr)
  2530. {
  2531. RecordFunctionDecl(callExpr->getMethodDecl());
  2532. return true;
  2533. }
  2534. void RecordFunctionDecl(FunctionDecl* funcDecl)
  2535. {
  2536. funcDecl = getFunctionWithBody(funcDecl);
  2537. if (funcDecl) {
  2538. if (m_sourceIt == m_callNodes.end()) {
  2539. auto result = m_callNodes.insert(
  2540. std::make_pair(m_source, CallNode{m_source, {}}));
  2541. DXASSERT(result.second == true,
  2542. "else setSourceFn didn't assign m_sourceIt");
  2543. m_sourceIt = result.first;
  2544. }
  2545. m_sourceIt->second.CalleeFns.insert(funcDecl);
  2546. if (!m_visitedFunctions.count(funcDecl)) {
  2547. m_pendingFunctions.push_back(funcDecl);
  2548. }
  2549. }
  2550. }
  2551. };
  2552. // A call graph that can check for reachability and recursion efficiently.
  2553. class CallGraphWithRecurseGuard {
  2554. private:
  2555. CallNodes m_callNodes;
  2556. FunctionSet m_visitedFunctions;
  2557. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2558. FunctionDecl *D) const {
  2559. if (CallStack.insert(D).second == false)
  2560. return D;
  2561. auto node = m_callNodes.find(D);
  2562. if (node != m_callNodes.end()) {
  2563. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2564. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2565. if (pResult)
  2566. return pResult;
  2567. }
  2568. }
  2569. CallStack.erase(D);
  2570. return nullptr;
  2571. }
  2572. public:
  2573. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2574. DXASSERT_NOMSG(EntryFnDecl);
  2575. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2576. PendingFunctions pendingFunctions;
  2577. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2578. pendingFunctions.push_back(EntryFnDecl);
  2579. while (!pendingFunctions.empty()) {
  2580. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2581. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2582. visitor.setSourceFn(pendingDecl);
  2583. visitor.TraverseDecl(pendingDecl);
  2584. }
  2585. }
  2586. }
  2587. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2588. FnCallStack CallStack;
  2589. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2590. return CheckRecursion(CallStack, EntryFnDecl);
  2591. }
  2592. const CallNodes &GetCallGraph() { return m_callNodes; }
  2593. void dump() const {
  2594. OutputDebugStringW(L"Call Nodes:\r\n");
  2595. for (auto &node : m_callNodes) {
  2596. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), (void*)node.first);
  2597. for (auto callee : node.second.CalleeFns) {
  2598. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), (void*)callee);
  2599. }
  2600. }
  2601. }
  2602. };
  2603. }
  2604. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2605. static
  2606. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2607. {
  2608. DXASSERT_NOMSG(context != nullptr);
  2609. DXASSERT_NOMSG(ident != nullptr);
  2610. DXASSERT_NOMSG(!baseType.isNull());
  2611. DeclContext* declContext = context->getTranslationUnitDecl();
  2612. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2613. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2614. declContext->addDecl(decl);
  2615. decl->setImplicit(true);
  2616. return decl;
  2617. }
  2618. class HLSLExternalSource : public ExternalSemaSource {
  2619. private:
  2620. // Inner types.
  2621. struct FindStructBasicTypeResult {
  2622. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2623. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2624. FindStructBasicTypeResult(ArBasicKind kind,
  2625. unsigned int basicKindAsTypeIndex)
  2626. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2627. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2628. };
  2629. // Declaration for matrix and vector templates.
  2630. ClassTemplateDecl* m_matrixTemplateDecl;
  2631. ClassTemplateDecl* m_vectorTemplateDecl;
  2632. // Namespace decl for hlsl intrinsic functions
  2633. NamespaceDecl* m_hlslNSDecl;
  2634. // Namespace decl for Vulkan-specific intrinsic functions
  2635. NamespaceDecl* m_vkNSDecl;
  2636. // Context being processed.
  2637. _Notnull_ ASTContext* m_context;
  2638. // Semantic analyzer being processed.
  2639. Sema* m_sema;
  2640. // Intrinsic tables available externally.
  2641. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2642. // Scalar types indexed by HLSLScalarType.
  2643. QualType m_scalarTypes[HLSLScalarTypeCount];
  2644. // Scalar types already built.
  2645. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2646. // 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.
  2647. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2648. // Matrix types already built, in shorthand form.
  2649. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2650. // Vector types already built.
  2651. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2652. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2653. // BuiltinType for each scalar type.
  2654. QualType m_baseTypes[HLSLScalarTypeCount];
  2655. // String type
  2656. QualType m_hlslStringType;
  2657. TypedefDecl* m_hlslStringTypedef;
  2658. // Built-in object types declarations, indexed by basic kind constant.
  2659. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2660. // Map from object decl to the object index.
  2661. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2662. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2663. // Mask for object which not has methods created.
  2664. uint64_t m_objectTypeLazyInitMask;
  2665. UsedIntrinsicStore m_usedIntrinsics;
  2666. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2667. void AddBaseTypes();
  2668. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2669. void AddHLSLScalarTypes();
  2670. /// <summary>Adds string type QualType for HSLS string declarations</summary>
  2671. void AddHLSLStringType();
  2672. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2673. {
  2674. DXASSERT_NOMSG(recordDecl != nullptr);
  2675. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2676. NamedDecl* parameterDecl = parameterList->getParam(0);
  2677. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2678. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2679. return QualType(parmDecl->getTypeForDecl(), 0);
  2680. }
  2681. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2682. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2683. {
  2684. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2685. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2686. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2687. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2688. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2689. if (
  2690. templateRef >= 0 &&
  2691. templateArg->uTemplateId == templateRef &&
  2692. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2693. componentRef >= 0 &&
  2694. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2695. componentArg->uComponentTypeId == 0 &&
  2696. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2697. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2698. !IsRowOrColumnVariable(matrixArg->uRows))
  2699. {
  2700. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2701. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2702. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2703. }
  2704. return QualType();
  2705. }
  2706. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2707. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2708. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2709. _Inout_ size_t* templateParamNamedDeclsCount)
  2710. {
  2711. DXASSERT_NOMSG(name != nullptr);
  2712. DXASSERT_NOMSG(recordDecl != nullptr);
  2713. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2714. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2715. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2716. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2717. // Create the declaration for the template parameter.
  2718. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2719. TemplateTypeParmDecl* templateTypeParmDecl =
  2720. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2721. id, TypenameTrue, ParameterPackFalse);
  2722. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2723. // Create the type that the parameter represents.
  2724. QualType result = m_context->getTemplateTypeParmType(
  2725. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2726. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2727. // it need not concern itself with maintaining this value.
  2728. (*templateParamNamedDeclsCount)++;
  2729. return result;
  2730. }
  2731. // Adds a function specified by the given intrinsic to a record declaration.
  2732. // The template depth will be zero for records that don't have a "template<>" line
  2733. // even if conceptual; or one if it does have one.
  2734. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2735. {
  2736. DXASSERT_NOMSG(recordDecl != nullptr);
  2737. DXASSERT_NOMSG(intrinsic != nullptr);
  2738. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2739. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2740. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2741. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2742. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2743. //
  2744. // Build template parameters, parameter types, and the return type.
  2745. // Parameter declarations are built after the function is created, to use it as their scope.
  2746. //
  2747. unsigned int numParams = intrinsic->uNumArgs - 1;
  2748. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2749. size_t templateParamNamedDeclsCount = 0;
  2750. QualType argsQTs[g_MaxIntrinsicParamCount];
  2751. StringRef argNames[g_MaxIntrinsicParamCount];
  2752. QualType functionResultQT = recordDecl->getASTContext().VoidTy;
  2753. DXASSERT(
  2754. _countof(templateParamNamedDecls) >= numParams + 1,
  2755. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2756. // Handle the return type.
  2757. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2758. // if (functionResultQT.isNull()) {
  2759. // Workaround for template parameter argument count mismatch.
  2760. // Create template parameter for return type always
  2761. // TODO: reenable the check and skip template argument.
  2762. functionResultQT = AddTemplateParamToArray(
  2763. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2764. &templateParamNamedDeclsCount);
  2765. // }
  2766. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2767. InitParamMods(intrinsic, paramMods);
  2768. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2769. // Handle parameters.
  2770. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2771. {
  2772. //
  2773. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2774. //
  2775. // However this may produce template instantiations with equivalent template arguments
  2776. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2777. // but the current intrinsic table has rules that are hard to process in their current form
  2778. // to find all cases.
  2779. //
  2780. char name[g_MaxIntrinsicParamName + 2];
  2781. name[0] = 'T';
  2782. name[1] = '\0';
  2783. strcat_s(name, intrinsic->pArgs[i].pName);
  2784. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2785. // Change out/inout param to reference type.
  2786. if (paramMods[i-1].isAnyOut())
  2787. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2788. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2789. }
  2790. // Create the declaration.
  2791. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2792. DeclarationName declarationName = DeclarationName(ii);
  2793. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2794. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2795. declarationName, true);
  2796. functionDecl->setImplicit(true);
  2797. // If the function is a template function, create the declaration and cross-reference.
  2798. if (templateParamNamedDeclsCount > 0)
  2799. {
  2800. hlsl::CreateFunctionTemplateDecl(
  2801. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2802. }
  2803. }
  2804. // Checks whether the two specified intrinsics generate equivalent templates.
  2805. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2806. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2807. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2808. {
  2809. if (left == right)
  2810. {
  2811. return true;
  2812. }
  2813. if (left == nullptr || right == nullptr)
  2814. {
  2815. return false;
  2816. }
  2817. return (left->uNumArgs == right->uNumArgs &&
  2818. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2819. }
  2820. // Adds all the intrinsic methods that correspond to the specified type.
  2821. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2822. {
  2823. DXASSERT_NOMSG(recordDecl != nullptr);
  2824. DXASSERT_NOMSG(templateDepth >= 0);
  2825. const HLSL_INTRINSIC* intrinsics;
  2826. const HLSL_INTRINSIC* prior = nullptr;
  2827. size_t intrinsicCount;
  2828. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2829. DXASSERT(
  2830. (intrinsics == nullptr) == (intrinsicCount == 0),
  2831. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2832. while (intrinsicCount--)
  2833. {
  2834. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2835. {
  2836. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2837. prior = intrinsics;
  2838. }
  2839. intrinsics++;
  2840. }
  2841. }
  2842. void AddDoubleSubscriptSupport(
  2843. _In_ ClassTemplateDecl* typeDecl,
  2844. _In_ CXXRecordDecl* recordDecl,
  2845. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2846. _In_z_ const char* type0Name,
  2847. _In_z_ const char* type1Name,
  2848. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2849. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2850. {
  2851. DXASSERT_NOMSG(typeDecl != nullptr);
  2852. DXASSERT_NOMSG(recordDecl != nullptr);
  2853. DXASSERT_NOMSG(memberName != nullptr);
  2854. DXASSERT_NOMSG(!elementType.isNull());
  2855. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2856. DXASSERT_NOMSG(type0Name != nullptr);
  2857. DXASSERT_NOMSG(type1Name != nullptr);
  2858. DXASSERT_NOMSG(indexer0Name != nullptr);
  2859. DXASSERT_NOMSG(!indexer0Type.isNull());
  2860. DXASSERT_NOMSG(indexer1Name != nullptr);
  2861. DXASSERT_NOMSG(!indexer1Type.isNull());
  2862. //
  2863. // Add inner types to the templates to represent the following C++ code inside the class.
  2864. // public:
  2865. // class sample_slice_type
  2866. // {
  2867. // public: TElement operator[](uint3 index);
  2868. // };
  2869. // class sample_type
  2870. // {
  2871. // public: sample_slice_type operator[](uint slice);
  2872. // };
  2873. // sample_type sample;
  2874. //
  2875. // Variable names reflect this structure, but this code will also produce the types
  2876. // for .mips access.
  2877. //
  2878. const bool MutableTrue = true;
  2879. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2880. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2881. &m_context->Idents.get(StringRef(type1Name)));
  2882. sampleSliceTypeDecl->setAccess(AS_public);
  2883. sampleSliceTypeDecl->setImplicit();
  2884. recordDecl->addDecl(sampleSliceTypeDecl);
  2885. sampleSliceTypeDecl->startDefinition();
  2886. const bool MutableFalse = false;
  2887. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2888. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2889. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2890. sliceHandleDecl->setAccess(AS_private);
  2891. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2892. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2893. sampleSliceTypeDecl, elementType,
  2894. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2895. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2896. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2897. sampleSliceTypeDecl->completeDefinition();
  2898. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2899. &m_context->Idents.get(StringRef(type0Name)));
  2900. sampleTypeDecl->setAccess(AS_public);
  2901. recordDecl->addDecl(sampleTypeDecl);
  2902. sampleTypeDecl->startDefinition();
  2903. sampleTypeDecl->setImplicit();
  2904. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2905. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2906. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2907. sampleHandleDecl->setAccess(AS_private);
  2908. sampleTypeDecl->addDecl(sampleHandleDecl);
  2909. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2910. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2911. sampleTypeDecl, m_context->getLValueReferenceType(sampleSliceType),
  2912. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2913. sampleTypeDecl->completeDefinition();
  2914. // Add subscript attribute
  2915. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2916. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2917. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2918. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2919. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2920. sampleFieldDecl->setAccess(AS_public);
  2921. recordDecl->addDecl(sampleFieldDecl);
  2922. }
  2923. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2924. _In_ CXXRecordDecl *recordDecl,
  2925. SubscriptOperatorRecord op) {
  2926. DXASSERT_NOMSG(typeDecl != nullptr);
  2927. DXASSERT_NOMSG(recordDecl != nullptr);
  2928. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2929. op.SubscriptCardinality <= 3);
  2930. DXASSERT(op.SubscriptCardinality > 0 ||
  2931. (op.HasMips == false && op.HasSample == false),
  2932. "objects that have .mips or .sample member also have a plain "
  2933. "subscript defined (otherwise static table is "
  2934. "likely incorrect, and this function won't know the cardinality "
  2935. "of the position parameter");
  2936. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2937. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2938. "read/write objects don't have .mips or .sample members");
  2939. // Return early if there is no work to be done.
  2940. if (op.SubscriptCardinality == 0) {
  2941. return;
  2942. }
  2943. const unsigned int templateDepth = 1;
  2944. // Add an operator[].
  2945. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2946. typeDecl->getTemplateParameters()->getParam(0));
  2947. QualType resultType = m_context->getTemplateTypeParmType(
  2948. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2949. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  2950. resultType = m_context->getLValueReferenceType(resultType);
  2951. QualType indexType =
  2952. op.SubscriptCardinality == 1
  2953. ? m_context->UnsignedIntTy
  2954. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2955. op.SubscriptCardinality);
  2956. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2957. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2958. ArrayRef<StringRef>(StringRef("index")),
  2959. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2960. hlsl::CreateFunctionTemplateDecl(
  2961. *m_context, recordDecl, functionDecl,
  2962. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2963. // Add a .mips member if necessary.
  2964. QualType uintType = m_context->UnsignedIntTy;
  2965. if (op.HasMips) {
  2966. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2967. templateTypeParmDecl, "mips_type",
  2968. "mips_slice_type", "mipSlice", uintType, "pos",
  2969. indexType);
  2970. }
  2971. // Add a .sample member if necessary.
  2972. if (op.HasSample) {
  2973. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2974. templateTypeParmDecl, "sample_type",
  2975. "sample_slice_type", "sampleSlice", uintType,
  2976. "pos", indexType);
  2977. // TODO: support operator[][](indexType, uint).
  2978. }
  2979. }
  2980. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2981. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2982. return a.first < b.first;
  2983. };
  2984. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2985. auto begin = m_objectTypeDeclsMap.begin();
  2986. auto end = m_objectTypeDeclsMap.end();
  2987. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2988. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2989. if (low == end)
  2990. return -1;
  2991. if (recordDecl == low->first)
  2992. return low->second;
  2993. else
  2994. return -1;
  2995. }
  2996. #ifdef ENABLE_SPIRV_CODEGEN
  2997. // Adds intrinsic function declarations to the "vk" namespace.
  2998. // It does so only if SPIR-V code generation is being done.
  2999. // Assumes the implicit "vk" namespace has already been created.
  3000. void AddVkIntrinsicFunctions() {
  3001. // If not doing SPIR-V CodeGen, return.
  3002. if (!m_sema->getLangOpts().SPIRV)
  3003. return;
  3004. DXASSERT(m_vkNSDecl, "caller has not created the vk namespace yet");
  3005. auto &context = m_sema->getASTContext();
  3006. for (uint32_t i = 0; i < _countof(g_VkIntrinsics); ++i) {
  3007. const HLSL_INTRINSIC *intrinsic = &g_VkIntrinsics[i];
  3008. const IdentifierInfo &fnII = context.Idents.get(
  3009. intrinsic->pArgs->pName, tok::TokenKind::identifier);
  3010. DeclarationName functionName(&fnII);
  3011. FunctionDecl *functionDecl = FunctionDecl::Create(
  3012. context, m_vkNSDecl, NoLoc, DeclarationNameInfo(functionName, NoLoc),
  3013. /*functionType*/ {}, nullptr, StorageClass::SC_Extern,
  3014. InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  3015. m_vkNSDecl->addDecl(functionDecl);
  3016. functionDecl->setLexicalDeclContext(m_vkNSDecl);
  3017. functionDecl->setDeclContext(m_vkNSDecl);
  3018. functionDecl->setImplicit(true);
  3019. }
  3020. }
  3021. // Adds implicitly defined Vulkan-specific constants to the "vk" namespace.
  3022. // It does so only if SPIR-V code generation is being done.
  3023. // Assumes the implicit "vk" namespace has already been created.
  3024. void AddVkIntrinsicConstants() {
  3025. // If not doing SPIR-V CodeGen, return.
  3026. if (!m_sema->getLangOpts().SPIRV)
  3027. return;
  3028. DXASSERT(m_vkNSDecl, "caller has not created the vk namespace yet");
  3029. for (auto intConst : GetVkIntegerConstants()) {
  3030. const llvm::StringRef name = intConst.first;
  3031. const uint32_t value = intConst.second;
  3032. auto &context = m_sema->getASTContext();
  3033. QualType type = context.getConstType(context.UnsignedIntTy);
  3034. IdentifierInfo &Id = context.Idents.get(name, tok::TokenKind::identifier);
  3035. VarDecl *varDecl =
  3036. VarDecl::Create(context, m_vkNSDecl, NoLoc, NoLoc, &Id, type,
  3037. context.getTrivialTypeSourceInfo(type),
  3038. clang::StorageClass::SC_Static);
  3039. Expr *exprVal = IntegerLiteral::Create(
  3040. context, llvm::APInt(context.getIntWidth(type), value), type, NoLoc);
  3041. varDecl->setInit(exprVal);
  3042. varDecl->setImplicit(true);
  3043. m_vkNSDecl->addDecl(varDecl);
  3044. }
  3045. }
  3046. #endif // ENABLE_SPIRV_CODEGEN
  3047. // Adds all built-in HLSL object types.
  3048. void AddObjectTypes()
  3049. {
  3050. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  3051. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  3052. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  3053. m_objectTypeLazyInitMask = 0;
  3054. unsigned effectKindIndex = 0;
  3055. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  3056. {
  3057. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3058. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  3059. continue;
  3060. }
  3061. if (kind == AR_OBJECT_LEGACY_EFFECT)
  3062. effectKindIndex = i;
  3063. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  3064. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  3065. const char* typeName = g_ArBasicTypeNames[kind];
  3066. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3067. CXXRecordDecl* recordDecl = nullptr;
  3068. if (kind == AR_OBJECT_RAY_DESC) {
  3069. QualType float3Ty = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 3);
  3070. recordDecl = CreateRayDescStruct(*m_context, float3Ty);
  3071. } else if (kind == AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES) {
  3072. QualType float2Type = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 2);
  3073. recordDecl = AddBuiltInTriangleIntersectionAttributes(*m_context, float2Type);
  3074. } else if (IsSubobjectBasicKind(kind)) {
  3075. switch (kind) {
  3076. case AR_OBJECT_STATE_OBJECT_CONFIG:
  3077. recordDecl = CreateSubobjectStateObjectConfig(*m_context);
  3078. break;
  3079. case AR_OBJECT_GLOBAL_ROOT_SIGNATURE:
  3080. recordDecl = CreateSubobjectRootSignature(*m_context, true);
  3081. break;
  3082. case AR_OBJECT_LOCAL_ROOT_SIGNATURE:
  3083. recordDecl = CreateSubobjectRootSignature(*m_context, false);
  3084. break;
  3085. case AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC:
  3086. recordDecl = CreateSubobjectSubobjectToExportsAssoc(*m_context);
  3087. break;
  3088. case AR_OBJECT_RAYTRACING_SHADER_CONFIG:
  3089. recordDecl = CreateSubobjectRaytracingShaderConfig(*m_context);
  3090. break;
  3091. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG:
  3092. recordDecl = CreateSubobjectRaytracingPipelineConfig(*m_context);
  3093. break;
  3094. case AR_OBJECT_TRIANGLE_HIT_GROUP:
  3095. recordDecl = CreateSubobjectTriangleHitGroup(*m_context);
  3096. break;
  3097. case AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP:
  3098. recordDecl = CreateSubobjectProceduralPrimitiveHitGroup(*m_context);
  3099. break;
  3100. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1:
  3101. recordDecl = CreateSubobjectRaytracingPipelineConfig1(*m_context);
  3102. break;
  3103. }
  3104. } else if (kind == AR_OBJECT_CONSTANT_BUFFER) {
  3105. recordDecl = DeclareConstantBufferViewType(*m_context, /*bTBuf*/false);
  3106. } else if (kind == AR_OBJECT_TEXTURE_BUFFER) {
  3107. recordDecl = DeclareConstantBufferViewType(*m_context, /*bTBuf*/true);
  3108. } else if (kind == AR_OBJECT_RAY_QUERY) {
  3109. recordDecl = DeclareRayQueryType(*m_context);
  3110. } else if (kind == AR_OBJECT_HEAP_RESOURCE) {
  3111. recordDecl = DeclareResourceType(*m_context, /*bSampler*/false);
  3112. // create Resource ResourceDescriptorHeap;
  3113. DeclareBuiltinGlobal("ResourceDescriptorHeap",
  3114. m_context->getRecordType(recordDecl), *m_context);
  3115. } else if (kind == AR_OBJECT_HEAP_SAMPLER) {
  3116. recordDecl = DeclareResourceType(*m_context, /*bSampler*/true);
  3117. // create Resource SamplerDescriptorHeap;
  3118. DeclareBuiltinGlobal("SamplerDescriptorHeap",
  3119. m_context->getRecordType(recordDecl), *m_context);
  3120. }
  3121. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D) {
  3122. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2D", "kind");
  3123. }
  3124. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY) {
  3125. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2DArray", "kind");
  3126. }
  3127. else if (templateArgCount == 0) {
  3128. recordDecl = DeclareRecordTypeWithHandle(*m_context, typeName);
  3129. }
  3130. else
  3131. {
  3132. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  3133. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  3134. recordDecl = DeclareTemplateTypeWithHandle(*m_context, typeName, templateArgCount, typeDefault);
  3135. }
  3136. m_objectTypeDecls[i] = recordDecl;
  3137. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  3138. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  3139. }
  3140. // Create an alias for SamplerState. 'sampler' is very commonly used.
  3141. {
  3142. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  3143. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  3144. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  3145. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  3146. currentDeclContext->addDecl(samplerDecl);
  3147. samplerDecl->setImplicit(true);
  3148. // Create decls for each deprecated effect object type:
  3149. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  3150. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  3151. for (unsigned i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  3152. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  3153. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  3154. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  3155. currentDeclContext->addDecl(effectObjDecl);
  3156. effectObjDecl->setImplicit(true);
  3157. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  3158. }
  3159. }
  3160. // Make sure it's in order.
  3161. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  3162. }
  3163. FunctionDecl* AddSubscriptSpecialization(
  3164. _In_ FunctionTemplateDecl* functionTemplate,
  3165. QualType objectElement,
  3166. const FindStructBasicTypeResult& findResult);
  3167. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  3168. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3169. }
  3170. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  3171. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3172. }
  3173. static TYPE_CONVERSION_REMARKS RemarksUnused;
  3174. static ImplicitConversionKind ImplicitConversionKindUnused;
  3175. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType,
  3176. ImplicitConversionKind &convKind = ImplicitConversionKindUnused,
  3177. TYPE_CONVERSION_REMARKS &Remarks = RemarksUnused);
  3178. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  3179. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3180. rowCount <= 4 && colCount <= 4);
  3181. TypedefDecl *qts =
  3182. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  3183. if (qts == nullptr) {
  3184. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  3185. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  3186. rowCount, colCount);
  3187. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  3188. }
  3189. return qts;
  3190. }
  3191. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  3192. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3193. colCount <= 4);
  3194. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  3195. if (qts == nullptr) {
  3196. QualType type = LookupVectorType(scalarType, colCount);
  3197. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  3198. colCount);
  3199. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  3200. }
  3201. return qts;
  3202. }
  3203. public:
  3204. HLSLExternalSource() :
  3205. m_matrixTemplateDecl(nullptr),
  3206. m_vectorTemplateDecl(nullptr),
  3207. m_hlslNSDecl(nullptr),
  3208. m_vkNSDecl(nullptr),
  3209. m_context(nullptr),
  3210. m_sema(nullptr),
  3211. m_hlslStringTypedef(nullptr)
  3212. {
  3213. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  3214. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  3215. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  3216. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  3217. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  3218. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  3219. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  3220. }
  3221. ~HLSLExternalSource() { }
  3222. static HLSLExternalSource* FromSema(_In_ Sema* self)
  3223. {
  3224. DXASSERT_NOMSG(self != nullptr);
  3225. ExternalSemaSource* externalSource = self->getExternalSource();
  3226. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  3227. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  3228. return hlsl;
  3229. }
  3230. void InitializeSema(Sema& S) override
  3231. {
  3232. auto &context = S.getASTContext();
  3233. m_sema = &S;
  3234. S.addExternalSource(this);
  3235. AddObjectTypes();
  3236. AddStdIsEqualImplementation(context, S);
  3237. for (auto && intrinsic : m_intrinsicTables) {
  3238. AddIntrinsicTableMethods(intrinsic);
  3239. }
  3240. #ifdef ENABLE_SPIRV_CODEGEN
  3241. if (m_sema->getLangOpts().SPIRV) {
  3242. // Create the "vk" namespace which contains Vulkan-specific intrinsics.
  3243. m_vkNSDecl =
  3244. NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3245. /*Inline*/ false, SourceLocation(),
  3246. SourceLocation(), &context.Idents.get("vk"),
  3247. /*PrevDecl*/ nullptr);
  3248. context.getTranslationUnitDecl()->addDecl(m_vkNSDecl);
  3249. // Add Vulkan-specific intrinsics.
  3250. AddVkIntrinsicFunctions();
  3251. AddVkIntrinsicConstants();
  3252. }
  3253. #endif // ENABLE_SPIRV_CODEGEN
  3254. }
  3255. void ForgetSema() override
  3256. {
  3257. m_sema = nullptr;
  3258. }
  3259. Sema* getSema() {
  3260. return m_sema;
  3261. }
  3262. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  3263. // We shouldn't create Typedef for built in scalar types.
  3264. // For built in scalar types, this funciton may be called for
  3265. // TypoCorrection. In that case, we return a nullptr.
  3266. if (m_scalarTypes[scalarType].isNull()) {
  3267. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  3268. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  3269. }
  3270. return m_scalarTypeDefs[scalarType];
  3271. }
  3272. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  3273. {
  3274. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  3275. if (qt.isNull()) {
  3276. // lazy initialization of scalar types
  3277. if (m_scalarTypes[scalarType].isNull()) {
  3278. LookupScalarTypeDef(scalarType);
  3279. }
  3280. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  3281. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  3282. }
  3283. return qt;
  3284. }
  3285. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  3286. {
  3287. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  3288. if (qt.isNull()) {
  3289. if (m_scalarTypes[scalarType].isNull()) {
  3290. LookupScalarTypeDef(scalarType);
  3291. }
  3292. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  3293. m_vectorTypes[scalarType][colCount - 1] = qt;
  3294. }
  3295. return qt;
  3296. }
  3297. TypedefDecl* GetStringTypedef() {
  3298. if (m_hlslStringTypedef == nullptr) {
  3299. m_hlslStringTypedef = CreateGlobalTypedef(m_context, "string", m_hlslStringType);
  3300. m_hlslStringType = m_context->getTypeDeclType(m_hlslStringTypedef);
  3301. }
  3302. DXASSERT_NOMSG(m_hlslStringTypedef != nullptr);
  3303. return m_hlslStringTypedef;
  3304. }
  3305. static bool IsSubobjectBasicKind(ArBasicKind kind) {
  3306. return kind >= AR_OBJECT_STATE_OBJECT_CONFIG && kind <= AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1;
  3307. }
  3308. bool IsSubobjectType(QualType type) {
  3309. return IsSubobjectBasicKind(GetTypeElementKind(type));
  3310. }
  3311. bool IsRayQueryBasicKind(ArBasicKind kind) {
  3312. return kind == AR_OBJECT_RAY_QUERY;
  3313. }
  3314. bool IsRayQueryType(QualType type) {
  3315. return IsRayQueryBasicKind(GetTypeElementKind(type));
  3316. }
  3317. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  3318. // TODO: enalbe this once we introduce precise master option
  3319. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  3320. if (type == HLSLScalarType_int_min12) {
  3321. const char *PromotedType =
  3322. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  3323. : HLSLScalarTypeNames[HLSLScalarType_int16];
  3324. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3325. << HLSLScalarTypeNames[type] << PromotedType;
  3326. } else if (type == HLSLScalarType_float_min10) {
  3327. const char *PromotedType =
  3328. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  3329. : HLSLScalarTypeNames[HLSLScalarType_float16];
  3330. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3331. << HLSLScalarTypeNames[type] << PromotedType;
  3332. }
  3333. if (!UseMinPrecision) {
  3334. if (type == HLSLScalarType_float_min16) {
  3335. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3336. << HLSLScalarTypeNames[type]
  3337. << HLSLScalarTypeNames[HLSLScalarType_float16];
  3338. } else if (type == HLSLScalarType_int_min16) {
  3339. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3340. << HLSLScalarTypeNames[type]
  3341. << HLSLScalarTypeNames[HLSLScalarType_int16];
  3342. } else if (type == HLSLScalarType_uint_min16) {
  3343. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3344. << HLSLScalarTypeNames[type]
  3345. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  3346. }
  3347. }
  3348. }
  3349. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  3350. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  3351. switch (type) {
  3352. case HLSLScalarType_float16:
  3353. case HLSLScalarType_float32:
  3354. case HLSLScalarType_float64:
  3355. case HLSLScalarType_int16:
  3356. case HLSLScalarType_int32:
  3357. case HLSLScalarType_uint16:
  3358. case HLSLScalarType_uint32:
  3359. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  3360. << HLSLScalarTypeNames[type] << "2018";
  3361. return false;
  3362. default:
  3363. break;
  3364. }
  3365. }
  3366. if (getSema()->getLangOpts().UseMinPrecision) {
  3367. switch (type) {
  3368. case HLSLScalarType_float16:
  3369. case HLSLScalarType_int16:
  3370. case HLSLScalarType_uint16:
  3371. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  3372. << HLSLScalarTypeNames[type];
  3373. return false;
  3374. default:
  3375. break;
  3376. }
  3377. }
  3378. return true;
  3379. }
  3380. bool LookupUnqualified(LookupResult &R, Scope *S) override
  3381. {
  3382. const DeclarationNameInfo declName = R.getLookupNameInfo();
  3383. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3384. if (idInfo == nullptr) {
  3385. return false;
  3386. }
  3387. // Currently template instantiation is blocked when a fatal error is
  3388. // detected. So no faulting-in types at this point, instead we simply
  3389. // back out.
  3390. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  3391. return false;
  3392. }
  3393. StringRef nameIdentifier = idInfo->getName();
  3394. HLSLScalarType parsedType;
  3395. int rowCount;
  3396. int colCount;
  3397. // Try parsing hlsl scalar types that is not initialized at AST time.
  3398. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  3399. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  3400. if (rowCount == 0 && colCount == 0) { // scalar
  3401. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  3402. if (!typeDecl) return false;
  3403. R.addDecl(typeDecl);
  3404. }
  3405. else if (rowCount == 0) { // vector
  3406. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  3407. R.addDecl(qts);
  3408. }
  3409. else { // matrix
  3410. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  3411. R.addDecl(qts);
  3412. }
  3413. return true;
  3414. }
  3415. // string
  3416. else if (TryParseString(nameIdentifier.data(), nameIdentifier.size(), getSema()->getLangOpts())) {
  3417. TypedefDecl *strDecl = GetStringTypedef();
  3418. R.addDecl(strDecl);
  3419. }
  3420. return false;
  3421. }
  3422. /// <summary>
  3423. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  3424. /// </summary>
  3425. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  3426. {
  3427. DXASSERT_NOMSG(type != nullptr);
  3428. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3429. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3430. if (templateSpecializationDecl) {
  3431. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  3432. if (decl == m_matrixTemplateDecl)
  3433. return AR_TOBJ_MATRIX;
  3434. else if (decl == m_vectorTemplateDecl)
  3435. return AR_TOBJ_VECTOR;
  3436. else if (!decl->isImplicit())
  3437. return AR_TOBJ_COMPOUND;
  3438. return AR_TOBJ_OBJECT;
  3439. }
  3440. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3441. if (typeRecordDecl->getDeclContext()->isFileContext()) {
  3442. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3443. if (index != -1) {
  3444. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  3445. if ( AR_OBJECT_RAY_DESC == kind || AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES == kind)
  3446. return AR_TOBJ_COMPOUND;
  3447. }
  3448. return AR_TOBJ_OBJECT;
  3449. }
  3450. else
  3451. return AR_TOBJ_INNER_OBJ;
  3452. }
  3453. return AR_TOBJ_COMPOUND;
  3454. }
  3455. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  3456. bool IsBuiltInObjectType(QualType type)
  3457. {
  3458. type = GetStructuralForm(type);
  3459. if (!type.isNull() && type->isStructureOrClassType()) {
  3460. const RecordType* recordType = type->getAs<RecordType>();
  3461. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  3462. }
  3463. return false;
  3464. }
  3465. /// <summary>
  3466. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  3467. /// possibly refering to original template record if it's a specialization; this makes the result
  3468. /// suitable for looking up in initialization tables.
  3469. /// </summary>
  3470. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  3471. {
  3472. const CXXRecordDecl* recordDecl;
  3473. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  3474. {
  3475. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  3476. }
  3477. else
  3478. {
  3479. recordDecl = dyn_cast<CXXRecordDecl>(context);
  3480. }
  3481. return recordDecl;
  3482. }
  3483. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  3484. ArTypeObjectKind GetTypeObjectKind(QualType type)
  3485. {
  3486. DXASSERT_NOMSG(!type.isNull());
  3487. type = GetStructuralForm(type);
  3488. if (type->isVoidType()) return AR_TOBJ_VOID;
  3489. if (type->isArrayType()) {
  3490. return hlsl::IsArrayConstantStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_ARRAY;
  3491. }
  3492. if (type->isPointerType()) {
  3493. return hlsl::IsPointerStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_POINTER;
  3494. }
  3495. if (type->isDependentType()) {
  3496. return AR_TOBJ_DEPENDENT;
  3497. }
  3498. if (type->isStructureOrClassType()) {
  3499. const RecordType* recordType = type->getAs<RecordType>();
  3500. return ClassifyRecordType(recordType);
  3501. } else if (const InjectedClassNameType *ClassNameTy =
  3502. type->getAs<InjectedClassNameType>()) {
  3503. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  3504. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  3505. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3506. if (templateSpecializationDecl) {
  3507. ClassTemplateDecl *decl =
  3508. templateSpecializationDecl->getSpecializedTemplate();
  3509. if (decl == m_matrixTemplateDecl)
  3510. return AR_TOBJ_MATRIX;
  3511. else if (decl == m_vectorTemplateDecl)
  3512. return AR_TOBJ_VECTOR;
  3513. DXASSERT(decl->isImplicit(),
  3514. "otherwise object template decl is not set to implicit");
  3515. return AR_TOBJ_OBJECT;
  3516. }
  3517. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3518. if (typeRecordDecl->getDeclContext()->isFileContext())
  3519. return AR_TOBJ_OBJECT;
  3520. else
  3521. return AR_TOBJ_INNER_OBJ;
  3522. }
  3523. return AR_TOBJ_COMPOUND;
  3524. }
  3525. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  3526. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  3527. return AR_TOBJ_INVALID;
  3528. }
  3529. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  3530. QualType GetMatrixOrVectorElementType(QualType type)
  3531. {
  3532. type = GetStructuralForm(type);
  3533. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3534. DXASSERT_NOMSG(typeRecordDecl);
  3535. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3536. DXASSERT_NOMSG(templateSpecializationDecl);
  3537. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  3538. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  3539. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  3540. }
  3541. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  3542. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  3543. QualType GetStructuralForm(QualType type)
  3544. {
  3545. if (type.isNull()) {
  3546. return type;
  3547. }
  3548. const ReferenceType *RefType = nullptr;
  3549. const AttributedType *AttrType = nullptr;
  3550. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  3551. (AttrType = dyn_cast<AttributedType>(type)))
  3552. {
  3553. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  3554. }
  3555. // Despite its name, getCanonicalTypeUnqualified will preserve const for array elements or something
  3556. return QualType(type->getCanonicalTypeUnqualified()->getTypePtr(), 0);
  3557. }
  3558. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  3559. ArBasicKind GetTypeElementKind(QualType type)
  3560. {
  3561. type = GetStructuralForm(type);
  3562. ArTypeObjectKind kind = GetTypeObjectKind(type);
  3563. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  3564. QualType elementType = GetMatrixOrVectorElementType(type);
  3565. return GetTypeElementKind(elementType);
  3566. }
  3567. if (kind == AR_TOBJ_STRING) {
  3568. return type->isArrayType() ? AR_OBJECT_STRING_LITERAL : AR_OBJECT_STRING;
  3569. }
  3570. if (type->isArrayType()) {
  3571. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  3572. return GetTypeElementKind(arrayType->getElementType());
  3573. }
  3574. if (kind == AR_TOBJ_INNER_OBJ) {
  3575. return AR_OBJECT_INNER;
  3576. } else if (kind == AR_TOBJ_OBJECT) {
  3577. // Classify the object as the element type.
  3578. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  3579. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3580. // NOTE: this will likely need to be updated for specialized records
  3581. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  3582. return g_ArBasicKindsAsTypes[index];
  3583. }
  3584. CanQualType canType = type->getCanonicalTypeUnqualified();
  3585. return BasicTypeForScalarType(canType);
  3586. }
  3587. ArBasicKind BasicTypeForScalarType(CanQualType type)
  3588. {
  3589. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3590. {
  3591. switch (BT->getKind())
  3592. {
  3593. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3594. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3595. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3596. case BuiltinType::Half: return AR_BASIC_FLOAT16;
  3597. case BuiltinType::HalfFloat: return AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  3598. case BuiltinType::Int: return AR_BASIC_INT32;
  3599. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3600. case BuiltinType::Short: return AR_BASIC_INT16;
  3601. case BuiltinType::UShort: return AR_BASIC_UINT16;
  3602. case BuiltinType::Long: return AR_BASIC_INT32;
  3603. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3604. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3605. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3606. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3607. case BuiltinType::Min16Float: return AR_BASIC_MIN16FLOAT;
  3608. case BuiltinType::Min16Int: return AR_BASIC_MIN16INT;
  3609. case BuiltinType::Min16UInt: return AR_BASIC_MIN16UINT;
  3610. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3611. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3612. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3613. case BuiltinType::Int8_4Packed: return AR_BASIC_INT8_4PACKED;
  3614. case BuiltinType::UInt8_4Packed: return AR_BASIC_UINT8_4PACKED;
  3615. case BuiltinType::Dependent: return AR_BASIC_DEPENDENT;
  3616. default:
  3617. // Only builtin types that have basickind equivalents.
  3618. break;
  3619. }
  3620. }
  3621. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3622. if (ET->getDecl()->isScopedUsingClassTag())
  3623. return AR_BASIC_ENUM_CLASS;
  3624. return AR_BASIC_ENUM;
  3625. }
  3626. return AR_BASIC_UNKNOWN;
  3627. }
  3628. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3629. DXASSERT_NOMSG(table != nullptr);
  3630. // Function intrinsics are added on-demand, objects get template methods.
  3631. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3632. // Grab information already processed by AddObjectTypes.
  3633. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3634. const char *typeName = g_ArBasicTypeNames[kind];
  3635. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3636. DXASSERT(templateArgCount <= 2, "otherwise a new case has been added");
  3637. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3638. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3639. if (recordDecl == nullptr) {
  3640. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3641. continue;
  3642. }
  3643. // This is a variation of AddObjectMethods using the new table.
  3644. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3645. const HLSL_INTRINSIC *pPrior = nullptr;
  3646. UINT64 lookupCookie = 0;
  3647. CA2W wideTypeName(typeName, CP_UTF8);
  3648. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3649. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3650. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3651. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3652. // NOTE: this only works with the current implementation because
  3653. // intrinsics are alive as long as the table is alive.
  3654. pPrior = pIntrinsic;
  3655. }
  3656. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3657. }
  3658. }
  3659. }
  3660. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3661. DXASSERT_NOMSG(table != nullptr);
  3662. m_intrinsicTables.push_back(table);
  3663. // If already initialized, add methods immediately.
  3664. if (m_sema != nullptr) {
  3665. AddIntrinsicTableMethods(table);
  3666. }
  3667. }
  3668. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3669. {
  3670. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3671. switch (kind) {
  3672. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3673. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3674. case AR_BASIC_FLOAT16: return HLSLScalarType_half;
  3675. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3676. return HLSLScalarType_float;
  3677. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3678. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3679. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3680. case AR_BASIC_INT8: return HLSLScalarType_int;
  3681. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3682. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3683. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3684. case AR_BASIC_INT32: return HLSLScalarType_int;
  3685. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3686. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3687. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3688. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3689. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3690. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3691. case AR_BASIC_INT8_4PACKED: return HLSLScalarType_int8_4packed;
  3692. case AR_BASIC_UINT8_4PACKED: return HLSLScalarType_uint8_4packed;
  3693. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3694. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3695. case AR_BASIC_ENUM: return HLSLScalarType_int;
  3696. default:
  3697. return HLSLScalarType_unknown;
  3698. }
  3699. }
  3700. QualType GetBasicKindType(ArBasicKind kind)
  3701. {
  3702. DXASSERT_VALIDBASICKIND(kind);
  3703. switch (kind) {
  3704. case AR_OBJECT_NULL: return m_context->VoidTy;
  3705. case AR_BASIC_BOOL: return m_context->BoolTy;
  3706. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3707. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3708. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->HalfFloatTy;
  3709. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3710. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3711. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3712. case AR_BASIC_INT8: return m_context->IntTy;
  3713. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3714. case AR_BASIC_INT16: return m_context->ShortTy;
  3715. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3716. case AR_BASIC_INT32: return m_context->IntTy;
  3717. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3718. case AR_BASIC_INT64: return m_context->LongLongTy;
  3719. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3720. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3721. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3722. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3723. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3724. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3725. case AR_BASIC_INT8_4PACKED: return m_scalarTypes[HLSLScalarType_int8_4packed];
  3726. case AR_BASIC_UINT8_4PACKED: return m_scalarTypes[HLSLScalarType_uint8_4packed];
  3727. case AR_BASIC_ENUM: return m_context->IntTy;
  3728. case AR_BASIC_ENUM_CLASS: return m_context->IntTy;
  3729. case AR_OBJECT_STRING: return m_hlslStringType;
  3730. case AR_OBJECT_STRING_LITERAL:
  3731. // m_hlslStringType is defined as 'char *'.
  3732. // for STRING_LITERAL we should use 'const char *'.
  3733. return m_context->getPointerType(m_context->CharTy.withConst());
  3734. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3735. case AR_OBJECT_TEXTURE1D:
  3736. case AR_OBJECT_TEXTURE1D_ARRAY:
  3737. case AR_OBJECT_TEXTURE2D:
  3738. case AR_OBJECT_TEXTURE2D_ARRAY:
  3739. case AR_OBJECT_TEXTURE3D:
  3740. case AR_OBJECT_TEXTURECUBE:
  3741. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3742. case AR_OBJECT_TEXTURE2DMS:
  3743. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3744. case AR_OBJECT_SAMPLER:
  3745. case AR_OBJECT_SAMPLERCOMPARISON:
  3746. case AR_OBJECT_HEAP_RESOURCE:
  3747. case AR_OBJECT_HEAP_SAMPLER:
  3748. case AR_OBJECT_BUFFER:
  3749. case AR_OBJECT_POINTSTREAM:
  3750. case AR_OBJECT_LINESTREAM:
  3751. case AR_OBJECT_TRIANGLESTREAM:
  3752. case AR_OBJECT_INPUTPATCH:
  3753. case AR_OBJECT_OUTPUTPATCH:
  3754. case AR_OBJECT_RWTEXTURE1D:
  3755. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3756. case AR_OBJECT_RWTEXTURE2D:
  3757. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3758. case AR_OBJECT_RWTEXTURE3D:
  3759. case AR_OBJECT_RWBUFFER:
  3760. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3761. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3762. case AR_OBJECT_STRUCTURED_BUFFER:
  3763. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3764. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3765. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3766. case AR_OBJECT_WAVE:
  3767. case AR_OBJECT_ACCELERATION_STRUCT:
  3768. case AR_OBJECT_RAY_DESC:
  3769. case AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES:
  3770. {
  3771. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3772. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3773. size_t index = match - g_ArBasicKindsAsTypes;
  3774. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3775. }
  3776. case AR_OBJECT_SAMPLER1D:
  3777. case AR_OBJECT_SAMPLER2D:
  3778. case AR_OBJECT_SAMPLER3D:
  3779. case AR_OBJECT_SAMPLERCUBE:
  3780. // Turn dimension-typed samplers into sampler states.
  3781. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3782. case AR_OBJECT_STATEBLOCK:
  3783. case AR_OBJECT_RASTERIZER:
  3784. case AR_OBJECT_DEPTHSTENCIL:
  3785. case AR_OBJECT_BLEND:
  3786. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3787. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3788. default:
  3789. return QualType();
  3790. }
  3791. }
  3792. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3793. /// <param name="E">Expression to typecast.</param>
  3794. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3795. ExprResult PromoteToIntIfBool(ExprResult& E);
  3796. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3797. {
  3798. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3799. (void)(qwUsages);
  3800. return type;
  3801. }
  3802. QualType NewSimpleAggregateType(
  3803. _In_ ArTypeObjectKind ExplicitKind,
  3804. _In_ ArBasicKind componentType,
  3805. _In_ UINT64 qwQual,
  3806. _In_ UINT uRows,
  3807. _In_ UINT uCols)
  3808. {
  3809. DXASSERT_VALIDBASICKIND(componentType);
  3810. QualType pType; // The type to return.
  3811. if (componentType < AR_BASIC_COUNT) {
  3812. // If basic numeric, call LookupScalarTypeDef to ensure on-demand
  3813. // initialization
  3814. LookupScalarTypeDef(ScalarTypeForBasic(componentType));
  3815. }
  3816. QualType pEltType = GetBasicKindType(componentType);
  3817. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3818. // TODO: handle adding qualifications like const
  3819. pType = NewQualifiedType(
  3820. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3821. pEltType);
  3822. if (uRows > 1 ||
  3823. uCols > 1 ||
  3824. ExplicitKind == AR_TOBJ_VECTOR ||
  3825. ExplicitKind == AR_TOBJ_MATRIX)
  3826. {
  3827. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3828. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3829. if ((uRows == 1 &&
  3830. ExplicitKind != AR_TOBJ_MATRIX) ||
  3831. ExplicitKind == AR_TOBJ_VECTOR)
  3832. {
  3833. pType = LookupVectorType(scalarType, uCols);
  3834. }
  3835. else
  3836. {
  3837. pType = LookupMatrixType(scalarType, uRows, uCols);
  3838. }
  3839. // TODO: handle colmajor/rowmajor
  3840. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3841. //{
  3842. // VN(pType = NewQualifiedType(pSrcLoc,
  3843. // qwQual & (AR_QUAL_COLMAJOR |
  3844. // AR_QUAL_ROWMAJOR),
  3845. // pMatrix));
  3846. //}
  3847. //else
  3848. //{
  3849. // pType = pMatrix;
  3850. //}
  3851. }
  3852. return pType;
  3853. }
  3854. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3855. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3856. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3857. /// <param name="Args">Invocation arguments to match.</param>
  3858. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3859. /// <param name="badArgIdx">The first argument to mismatch if any</param>
  3860. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3861. bool MatchArguments(
  3862. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3863. _In_ QualType objectElement,
  3864. _In_ QualType functionTemplateTypeArg,
  3865. _In_ ArrayRef<Expr *> Args,
  3866. _Out_ std::vector<QualType> *,
  3867. _Out_ size_t &badArgIdx);
  3868. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3869. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3870. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3871. bool IsValidateObjectElement(
  3872. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3873. _In_ QualType objectElement);
  3874. // Returns the iterator with the first entry that matches the requirement
  3875. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3876. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3877. size_t tableSize,
  3878. StringRef typeName,
  3879. StringRef nameIdentifier,
  3880. size_t argumentCount)
  3881. {
  3882. // This is implemented by a linear scan for now.
  3883. // We tested binary search on tables, and there was no performance gain on
  3884. // samples probably for the following reasons.
  3885. // 1. The tables are not big enough to make noticable difference
  3886. // 2. The user of this function assumes that it returns the first entry in
  3887. // the table that matches name and argument count. So even in the binary
  3888. // search, we have to scan backwards until the entry does not match the name
  3889. // or arg count. For linear search this is not a problem
  3890. for (unsigned int i = 0; i < tableSize; i++) {
  3891. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3892. const bool isVariadicFn = IsVariadicIntrinsicFunction(pIntrinsic);
  3893. // Do some quick checks to verify size and name.
  3894. if (!isVariadicFn && pIntrinsic->uNumArgs != 1 + argumentCount) {
  3895. continue;
  3896. }
  3897. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3898. continue;
  3899. }
  3900. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3901. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3902. }
  3903. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3904. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3905. }
  3906. bool AddOverloadedCallCandidates(
  3907. UnresolvedLookupExpr *ULE,
  3908. ArrayRef<Expr *> Args,
  3909. OverloadCandidateSet &CandidateSet,
  3910. bool PartialOverloading) override
  3911. {
  3912. DXASSERT_NOMSG(ULE != nullptr);
  3913. const bool isQualified = ULE->getQualifier();
  3914. const bool isGlobalNamespace =
  3915. ULE->getQualifier() &&
  3916. ULE->getQualifier()->getKind() == NestedNameSpecifier::Global;
  3917. const bool isVkNamespace =
  3918. ULE->getQualifier() &&
  3919. ULE->getQualifier()->getKind() == NestedNameSpecifier::Namespace &&
  3920. ULE->getQualifier()->getAsNamespace()->getName() == "vk";
  3921. // Intrinsics live in the global namespace, so references to their names
  3922. // should be either unqualified or '::'-prefixed.
  3923. // Exception: Vulkan-specific intrinsics live in the 'vk::' namespace.
  3924. if (isQualified && !isGlobalNamespace && !isVkNamespace) {
  3925. return false;
  3926. }
  3927. const DeclarationNameInfo declName = ULE->getNameInfo();
  3928. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3929. if (idInfo == nullptr)
  3930. {
  3931. return false;
  3932. }
  3933. StringRef nameIdentifier = idInfo->getName();
  3934. const HLSL_INTRINSIC *table = g_Intrinsics;
  3935. auto tableCount = _countof(g_Intrinsics);
  3936. #ifdef ENABLE_SPIRV_CODEGEN
  3937. if (isVkNamespace) {
  3938. table = g_VkIntrinsics;
  3939. tableCount = _countof(g_VkIntrinsics);
  3940. }
  3941. #endif // ENABLE_SPIRV_CODEGEN
  3942. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3943. table, tableCount, StringRef(), nameIdentifier, Args.size());
  3944. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3945. table, tableCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3946. for (;cursor != end; ++cursor)
  3947. {
  3948. // If this is the intrinsic we're interested in, build up a representation
  3949. // of the types we need.
  3950. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3951. LPCSTR tableName = cursor.GetTableName();
  3952. LPCSTR lowering = cursor.GetLoweringStrategy();
  3953. DXASSERT(
  3954. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3955. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3956. std::vector<QualType> functionArgTypes;
  3957. size_t badArgIdx;
  3958. bool argsMatch = MatchArguments(pIntrinsic, QualType(), QualType(), Args, &functionArgTypes, badArgIdx);
  3959. if (!functionArgTypes.size())
  3960. return false;
  3961. // Get or create the overload we're interested in.
  3962. FunctionDecl* intrinsicFuncDecl = nullptr;
  3963. std::pair<UsedIntrinsicStore::iterator, bool> insertResult =
  3964. m_usedIntrinsics.insert(UsedIntrinsic(pIntrinsic, functionArgTypes));
  3965. bool insertedNewValue = insertResult.second;
  3966. if (insertedNewValue)
  3967. {
  3968. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3969. intrinsicFuncDecl = AddHLSLIntrinsicFunction(
  3970. *m_context, isVkNamespace ? m_vkNSDecl : m_hlslNSDecl, tableName,
  3971. lowering, pIntrinsic, &functionArgTypes);
  3972. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3973. }
  3974. else
  3975. {
  3976. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3977. }
  3978. OverloadCandidate& candidate = CandidateSet.addCandidate(Args.size());
  3979. candidate.Function = intrinsicFuncDecl;
  3980. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3981. candidate.Viable = argsMatch;
  3982. CandidateSet.isNewCandidate(intrinsicFuncDecl); // used to insert into set
  3983. if (argsMatch)
  3984. return true;
  3985. if (badArgIdx) {
  3986. candidate.FailureKind = ovl_fail_bad_conversion;
  3987. QualType ParamType = functionArgTypes[badArgIdx];
  3988. candidate.Conversions[badArgIdx-1].setBad(BadConversionSequence::no_conversion, Args[badArgIdx-1], ParamType);
  3989. } else {
  3990. // A less informative error. Needed when the failure relates to the return type
  3991. candidate.FailureKind = ovl_fail_bad_final_conversion;
  3992. }
  3993. }
  3994. return false;
  3995. }
  3996. bool Initialize(ASTContext& context)
  3997. {
  3998. m_context = &context;
  3999. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  4000. /*Inline*/ false, SourceLocation(),
  4001. SourceLocation(), &context.Idents.get("hlsl"),
  4002. /*PrevDecl*/ nullptr);
  4003. m_hlslNSDecl->setImplicit();
  4004. AddBaseTypes();
  4005. AddHLSLScalarTypes();
  4006. AddHLSLStringType();
  4007. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  4008. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  4009. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  4010. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  4011. // Initializing built in integers for ray tracing
  4012. AddRaytracingConstants(*m_context);
  4013. AddSamplerFeedbackConstants(*m_context);
  4014. return true;
  4015. }
  4016. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  4017. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  4018. /// <summary>Checks whether the specified type is a scalar type.</summary>
  4019. bool IsScalarType(const QualType& type) {
  4020. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  4021. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  4022. }
  4023. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  4024. bool IsValidVectorSize(size_t length) {
  4025. return 1 <= length && length <= 4;
  4026. }
  4027. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  4028. bool IsValidMatrixColOrRowSize(size_t length) {
  4029. return 1 <= length && length <= 4;
  4030. }
  4031. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  4032. if (type.isNull()) {
  4033. return false;
  4034. }
  4035. if (type.hasQualifiers()) {
  4036. return false;
  4037. }
  4038. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  4039. if (type->getTypeClass() == Type::TemplateTypeParm)
  4040. return true;
  4041. QualType qt = GetStructuralForm(type);
  4042. if (requireScalar) {
  4043. if (!IsScalarType(qt)) {
  4044. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  4045. return false;
  4046. }
  4047. return true;
  4048. }
  4049. else {
  4050. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  4051. if (qt->isArrayType()) {
  4052. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  4053. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  4054. }
  4055. else if (objectKind == AR_TOBJ_VECTOR) {
  4056. bool valid = true;
  4057. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  4058. valid = false;
  4059. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  4060. }
  4061. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  4062. valid = false;
  4063. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  4064. }
  4065. return valid;
  4066. }
  4067. else if (objectKind == AR_TOBJ_MATRIX) {
  4068. bool valid = true;
  4069. UINT rowCount, colCount;
  4070. GetRowsAndCols(type, rowCount, colCount);
  4071. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  4072. valid = false;
  4073. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  4074. }
  4075. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  4076. valid = false;
  4077. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  4078. }
  4079. return valid;
  4080. }
  4081. else if (qt->isStructureType()) {
  4082. const RecordType* recordType = qt->getAsStructureType();
  4083. objectKind = ClassifyRecordType(recordType);
  4084. switch (objectKind)
  4085. {
  4086. case AR_TOBJ_OBJECT:
  4087. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  4088. return false;
  4089. case AR_TOBJ_COMPOUND:
  4090. {
  4091. const RecordDecl* recordDecl = recordType->getDecl();
  4092. RecordDecl::field_iterator begin = recordDecl->field_begin();
  4093. RecordDecl::field_iterator end = recordDecl->field_end();
  4094. bool result = true;
  4095. while (begin != end) {
  4096. const FieldDecl* fieldDecl = *begin;
  4097. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  4098. m_sema->Diag(argLoc, diag::note_field_type_usage)
  4099. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  4100. result = false;
  4101. }
  4102. begin++;
  4103. }
  4104. return result;
  4105. }
  4106. default:
  4107. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  4108. return false;
  4109. }
  4110. }
  4111. else if(IsScalarType(qt)) {
  4112. return true;
  4113. }
  4114. else {
  4115. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  4116. return false;
  4117. }
  4118. }
  4119. }
  4120. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  4121. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  4122. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  4123. _Inout_opt_ StandardConversionSequence* sequence);
  4124. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  4125. void GetConversionForm(
  4126. QualType type,
  4127. bool explicitConversion,
  4128. ArTypeInfo* pTypeInfo);
  4129. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  4130. bool suppressWarnings, bool suppressErrors,
  4131. _Inout_opt_ StandardConversionSequence* sequence);
  4132. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  4133. bool ValidateTypeRequirements(
  4134. SourceLocation loc,
  4135. ArBasicKind elementKind,
  4136. ArTypeObjectKind objectKind,
  4137. bool requiresIntegrals,
  4138. bool requiresNumerics);
  4139. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  4140. /// <param name="OpLoc">Source location for operator.</param>
  4141. /// <param name="Opc">Kind of binary operator.</param>
  4142. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  4143. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  4144. /// <param name="ResultTy">Result type for operator expression.</param>
  4145. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  4146. /// <param name="CompResultTy">Type of computation result.</param>
  4147. void CheckBinOpForHLSL(
  4148. SourceLocation OpLoc,
  4149. BinaryOperatorKind Opc,
  4150. ExprResult& LHS,
  4151. ExprResult& RHS,
  4152. QualType& ResultTy,
  4153. QualType& CompLHSTy,
  4154. QualType& CompResultTy);
  4155. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  4156. /// <param name="OpLoc">Source location for operator.</param>
  4157. /// <param name="Opc">Kind of operator.</param>
  4158. /// <param name="InputExpr">Input expression to the operator.</param>
  4159. /// <param name="VK">Value kind for resulting expression.</param>
  4160. /// <param name="OK">Object kind for resulting expression.</param>
  4161. /// <returns>The result type for the expression.</returns>
  4162. QualType CheckUnaryOpForHLSL(
  4163. SourceLocation OpLoc,
  4164. UnaryOperatorKind Opc,
  4165. ExprResult& InputExpr,
  4166. ExprValueKind& VK,
  4167. ExprObjectKind& OK);
  4168. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  4169. /// <param name="Cond">Vector condition expression.</param>
  4170. /// <param name="LHS">Left hand side.</param>
  4171. /// <param name="RHS">Right hand side.</param>
  4172. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  4173. /// <returns>Result type of vector conditional expression.</returns>
  4174. clang::QualType CheckVectorConditional(
  4175. _In_ ExprResult &Cond,
  4176. _In_ ExprResult &LHS,
  4177. _In_ ExprResult &RHS,
  4178. _In_ SourceLocation QuestionLoc);
  4179. clang::QualType ApplyTypeSpecSignToParsedType(
  4180. _In_ clang::QualType &type,
  4181. _In_ TypeSpecifierSign TSS,
  4182. _In_ SourceLocation Loc
  4183. );
  4184. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  4185. {
  4186. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  4187. {
  4188. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  4189. return true;
  4190. }
  4191. return false;
  4192. }
  4193. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  4194. bool
  4195. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  4196. SourceLocation /* TemplateLoc */,
  4197. TemplateArgumentListInfo &TemplateArgList) {
  4198. DXASSERT_NOMSG(Template != nullptr);
  4199. // Determine which object type the template refers to.
  4200. StringRef templateName = Template->getName();
  4201. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  4202. if (templateName.equals(StringRef("is_same"))) {
  4203. return false;
  4204. }
  4205. // Allow object type for Constant/TextureBuffer.
  4206. if (templateName == "ConstantBuffer" || templateName == "TextureBuffer") {
  4207. if (TemplateArgList.size() == 1) {
  4208. const TemplateArgumentLoc &argLoc = TemplateArgList[0];
  4209. const TemplateArgument &arg = argLoc.getArgument();
  4210. DXASSERT(arg.getKind() == TemplateArgument::ArgKind::Type, "");
  4211. QualType argType = arg.getAsType();
  4212. SourceLocation argSrcLoc = argLoc.getLocation();
  4213. if (IsScalarType(argType) || IsVectorType(m_sema, argType) ||
  4214. IsMatrixType(m_sema, argType) || argType->isArrayType()) {
  4215. m_sema->Diag(argSrcLoc,
  4216. diag::err_hlsl_typeintemplateargument_requires_struct)
  4217. << argType;
  4218. return true;
  4219. }
  4220. if (const RecordType* recordType = argType->getAsStructureType()) {
  4221. if (!recordType->getDecl()->isCompleteDefinition()) {
  4222. m_sema->Diag(argSrcLoc, diag::err_typecheck_decl_incomplete_type)
  4223. << argType;
  4224. return true;
  4225. }
  4226. }
  4227. }
  4228. return false;
  4229. }
  4230. bool isMatrix = Template->getCanonicalDecl() ==
  4231. m_matrixTemplateDecl->getCanonicalDecl();
  4232. bool isVector = Template->getCanonicalDecl() ==
  4233. m_vectorTemplateDecl->getCanonicalDecl();
  4234. bool requireScalar = isMatrix || isVector;
  4235. // Check constraints on the type. Right now we only check that template
  4236. // types are primitive types.
  4237. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  4238. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  4239. SourceLocation argSrcLoc = argLoc.getLocation();
  4240. const TemplateArgument &arg = argLoc.getArgument();
  4241. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  4242. QualType argType = arg.getAsType();
  4243. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  4244. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  4245. return true;
  4246. }
  4247. }
  4248. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  4249. if (isMatrix || isVector) {
  4250. Expr *expr = arg.getAsExpr();
  4251. llvm::APSInt constantResult;
  4252. if (expr != nullptr &&
  4253. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  4254. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  4255. return true;
  4256. }
  4257. }
  4258. }
  4259. }
  4260. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  4261. if (isMatrix || isVector) {
  4262. llvm::APSInt Val = arg.getAsIntegral();
  4263. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  4264. return true;
  4265. }
  4266. }
  4267. }
  4268. }
  4269. return false;
  4270. }
  4271. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  4272. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  4273. /// <param name="functionDeclContext">Declaration context of function.</param>
  4274. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  4275. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  4276. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  4277. void FindIntrinsicTable(
  4278. _In_ DeclContext* functionDeclContext,
  4279. _Outptr_result_z_ const char** name,
  4280. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  4281. _Out_ size_t* intrinsicCount);
  4282. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  4283. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  4284. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  4285. /// <param name="Args">Array of expressions being used as arguments.</param>
  4286. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  4287. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  4288. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  4289. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  4290. FunctionTemplateDecl *FunctionTemplate,
  4291. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  4292. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  4293. clang::OverloadingResult GetBestViableFunction(
  4294. clang::SourceLocation Loc,
  4295. clang::OverloadCandidateSet& set,
  4296. clang::OverloadCandidateSet::iterator& Best);
  4297. /// <summary>
  4298. /// Initializes the specified <paramref name="initSequence" /> describing how
  4299. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  4300. /// </summary>
  4301. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  4302. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  4303. /// <param name="Args">Arguments to the initialization.</param>
  4304. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  4305. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  4306. void InitializeInitSequenceForHLSL(
  4307. const InitializedEntity& Entity,
  4308. const InitializationKind& Kind,
  4309. MultiExprArg Args,
  4310. bool TopLevelOfInitList,
  4311. _Inout_ InitializationSequence* initSequence);
  4312. /// <summary>
  4313. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4314. /// </summary>
  4315. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4316. bool IsConversionToLessOrEqualElements(
  4317. const ExprResult& sourceExpr,
  4318. const QualType& targetType,
  4319. bool explicitConversion);
  4320. /// <summary>
  4321. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4322. /// </summary>
  4323. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4324. bool IsConversionToLessOrEqualElements(
  4325. const QualType& sourceType,
  4326. const QualType& targetType,
  4327. bool explicitConversion);
  4328. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  4329. /// <param name="BaseExpr">Base expression for member access.</param>
  4330. /// <param name="MemberName">Name of member to look up.</param>
  4331. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4332. /// <param name="OpLoc">Location of access operand.</param>
  4333. /// <param name="MemberLoc">Location of member.</param>
  4334. /// <returns>Result of lookup operation.</returns>
  4335. ExprResult LookupMatrixMemberExprForHLSL(
  4336. Expr& BaseExpr,
  4337. DeclarationName MemberName,
  4338. bool IsArrow,
  4339. SourceLocation OpLoc,
  4340. SourceLocation MemberLoc);
  4341. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  4342. /// <param name="BaseExpr">Base expression for member access.</param>
  4343. /// <param name="MemberName">Name of member to look up.</param>
  4344. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4345. /// <param name="OpLoc">Location of access operand.</param>
  4346. /// <param name="MemberLoc">Location of member.</param>
  4347. /// <returns>Result of lookup operation.</returns>
  4348. ExprResult LookupVectorMemberExprForHLSL(
  4349. Expr& BaseExpr,
  4350. DeclarationName MemberName,
  4351. bool IsArrow,
  4352. SourceLocation OpLoc,
  4353. SourceLocation MemberLoc);
  4354. /// <summary>Performs a member lookup on the specified BaseExpr if it's an array.</summary>
  4355. /// <param name="BaseExpr">Base expression for member access.</param>
  4356. /// <param name="MemberName">Name of member to look up.</param>
  4357. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4358. /// <param name="OpLoc">Location of access operand.</param>
  4359. /// <param name="MemberLoc">Location of member.</param>
  4360. /// <returns>Result of lookup operation.</returns>
  4361. ExprResult LookupArrayMemberExprForHLSL(
  4362. Expr& BaseExpr,
  4363. DeclarationName MemberName,
  4364. bool IsArrow,
  4365. SourceLocation OpLoc,
  4366. SourceLocation MemberLoc);
  4367. /// <summary>If E is a scalar, converts it to a 1-element vector. If E is a
  4368. /// Constant/TextureBuffer<T>, converts it to const T.</summary>
  4369. /// <param name="E">Expression to convert.</param>
  4370. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  4371. ExprResult MaybeConvertMemberAccess(_In_ clang::Expr* E);
  4372. clang::Expr *HLSLImpCastToScalar(
  4373. _In_ clang::Sema* self,
  4374. _In_ clang::Expr* From,
  4375. ArTypeObjectKind FromShape,
  4376. ArBasicKind EltKind);
  4377. clang::ExprResult PerformHLSLConversion(
  4378. _In_ clang::Expr* From,
  4379. _In_ clang::QualType targetType,
  4380. _In_ const clang::StandardConversionSequence &SCS,
  4381. _In_ clang::Sema::CheckedConversionKind CCK);
  4382. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  4383. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  4384. /// <summary>
  4385. /// Checks if a static cast can be performed, and performs it if possible.
  4386. /// </summary>
  4387. /// <param name="SrcExpr">Expression to cast.</param>
  4388. /// <param name="DestType">Type to cast SrcExpr to.</param>
  4389. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  4390. /// <param name="OpRange">Source range for the cast operation.</param>
  4391. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  4392. /// <param name="Kind">The kind of operation required for a conversion.</param>
  4393. /// <param name="BasePath">A simple array of base specifiers.</param>
  4394. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  4395. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  4396. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  4397. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  4398. QualType DestType,
  4399. Sema::CheckedConversionKind CCK,
  4400. const SourceRange &OpRange, unsigned &msg,
  4401. CastKind &Kind, CXXCastPath &BasePath,
  4402. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  4403. _Inout_opt_ StandardConversionSequence* standard);
  4404. /// <summary>
  4405. /// Checks if a subscript index argument can be initialized from the given expression.
  4406. /// </summary>
  4407. /// <param name="SrcExpr">Source expression used as argument.</param>
  4408. /// <param name="DestType">Parameter type to initialize.</param>
  4409. /// <remarks>
  4410. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  4411. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  4412. /// </remarks>
  4413. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  4414. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  4415. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  4416. // Everything is ready.
  4417. if (m_objectTypeLazyInitMask == 0)
  4418. return;
  4419. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  4420. int idx = FindObjectBasicKindIndex(recordDecl);
  4421. // Not object type.
  4422. if (idx == -1)
  4423. return;
  4424. uint64_t bit = ((uint64_t)1)<<idx;
  4425. // Already created.
  4426. if ((m_objectTypeLazyInitMask & bit) == 0)
  4427. return;
  4428. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  4429. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  4430. int startDepth = 0;
  4431. if (templateArgCount > 0) {
  4432. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  4433. "otherwise a new case has been added");
  4434. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  4435. AddObjectSubscripts(kind, typeDecl, recordDecl,
  4436. g_ArBasicKindsSubscripts[idx]);
  4437. startDepth = 1;
  4438. }
  4439. AddObjectMethods(kind, recordDecl, startDepth);
  4440. // Clear the object.
  4441. m_objectTypeLazyInitMask &= ~bit;
  4442. }
  4443. FunctionDecl* AddHLSLIntrinsicMethod(
  4444. LPCSTR tableName,
  4445. LPCSTR lowering,
  4446. _In_ const HLSL_INTRINSIC* intrinsic,
  4447. _In_ FunctionTemplateDecl *FunctionTemplate,
  4448. ArrayRef<Expr *> Args,
  4449. _In_count_(parameterTypeCount) QualType* parameterTypes,
  4450. size_t parameterTypeCount)
  4451. {
  4452. DXASSERT_NOMSG(intrinsic != nullptr);
  4453. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  4454. DXASSERT_NOMSG(parameterTypes != nullptr);
  4455. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  4456. // Create the template arguments.
  4457. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  4458. for (size_t i = 0; i < parameterTypeCount; i++) {
  4459. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  4460. }
  4461. // Look for an existing specialization.
  4462. void *InsertPos = nullptr;
  4463. FunctionDecl *SpecFunc =
  4464. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  4465. if (SpecFunc != nullptr) {
  4466. return SpecFunc;
  4467. }
  4468. // Change return type to lvalue reference type for aggregate types
  4469. QualType retTy = parameterTypes[0];
  4470. if (hlsl::IsHLSLAggregateType(retTy))
  4471. parameterTypes[0] = m_context->getLValueReferenceType(retTy);
  4472. // Create a new specialization.
  4473. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  4474. InitParamMods(intrinsic, paramMods);
  4475. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4476. // Change out/inout parameter type to rvalue reference type.
  4477. if (paramMods[i - 1].isAnyOut()) {
  4478. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  4479. }
  4480. }
  4481. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  4482. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  4483. // Remove this when update intrinsic table not affect other things.
  4484. // Change vector<float,1> into float for bias.
  4485. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  4486. DXASSERT(parameterTypeCount > biasOperandID,
  4487. "else operation was misrecognized");
  4488. if (const ExtVectorType *VecTy =
  4489. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  4490. *m_context, parameterTypes[biasOperandID])) {
  4491. if (VecTy->getNumElements() == 1)
  4492. parameterTypes[biasOperandID] = VecTy->getElementType();
  4493. }
  4494. }
  4495. DeclContext *owner = FunctionTemplate->getDeclContext();
  4496. TemplateArgumentList templateArgumentList(
  4497. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  4498. templateArgs.size());
  4499. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4500. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  4501. mlTemplateArgumentList);
  4502. FunctionProtoType::ExtProtoInfo EmptyEPI;
  4503. QualType functionType = m_context->getFunctionType(
  4504. parameterTypes[0],
  4505. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  4506. EmptyEPI, paramMods);
  4507. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4508. FunctionProtoTypeLoc Proto =
  4509. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4510. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  4511. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4512. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  4513. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  4514. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  4515. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  4516. Params.push_back(paramDecl);
  4517. }
  4518. QualType T = TInfo->getType();
  4519. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  4520. CXXMethodDecl* method = CXXMethodDecl::Create(
  4521. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4522. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4523. // Add intrinsic attr
  4524. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  4525. // Record this function template specialization.
  4526. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  4527. *m_context, templateArgs.data(), templateArgs.size());
  4528. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  4529. // Attach the parameters
  4530. for (unsigned P = 0; P < Params.size(); ++P) {
  4531. Params[P]->setOwningFunction(method);
  4532. Proto.setParam(P, Params[P]);
  4533. }
  4534. method->setParams(Params);
  4535. // Adjust access.
  4536. method->setAccess(AccessSpecifier::AS_public);
  4537. FunctionTemplate->setAccess(method->getAccess());
  4538. return method;
  4539. }
  4540. // Overload support.
  4541. UINT64 ScoreCast(QualType leftType, QualType rightType);
  4542. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  4543. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  4544. unsigned GetNumElements(QualType anyType);
  4545. unsigned GetNumBasicElements(QualType anyType);
  4546. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  4547. QualType GetNthElementType(QualType type, unsigned index);
  4548. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  4549. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4550. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4551. };
  4552. TYPE_CONVERSION_REMARKS HLSLExternalSource::RemarksUnused = TYPE_CONVERSION_REMARKS::TYPE_CONVERSION_NONE;
  4553. ImplicitConversionKind HLSLExternalSource::ImplicitConversionKindUnused = ImplicitConversionKind::ICK_Identity;
  4554. // Use this class to flatten a type into HLSL primitives and iterate through them.
  4555. class FlattenedTypeIterator
  4556. {
  4557. private:
  4558. enum FlattenedIterKind {
  4559. FK_Simple,
  4560. FK_Fields,
  4561. FK_Expressions,
  4562. FK_IncompleteArray,
  4563. FK_Bases,
  4564. };
  4565. // Use this struct to represent a specific point in the tracked tree.
  4566. struct FlattenedTypeTracker {
  4567. QualType Type; // Type at this position in the tree.
  4568. unsigned int Count; // Count of consecutive types
  4569. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  4570. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  4571. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  4572. RecordDecl::field_iterator EndField; // STL-style end of fields.
  4573. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  4574. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  4575. FlattenedIterKind IterKind; // Kind of tracker.
  4576. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  4577. FlattenedTypeTracker(QualType type)
  4578. : Type(type), Count(0), CurrentExpr(nullptr),
  4579. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  4580. FlattenedTypeTracker(QualType type, unsigned int count,
  4581. MultiExprArg::iterator expression)
  4582. : Type(type), Count(count), CurrentExpr(expression),
  4583. IterKind(FK_Simple), IsConsidered(false) {}
  4584. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  4585. RecordDecl::field_iterator end)
  4586. : Type(type), Count(0), CurrentField(current), EndField(end),
  4587. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  4588. FlattenedTypeTracker(MultiExprArg::iterator current,
  4589. MultiExprArg::iterator end)
  4590. : Count(0), CurrentExpr(current), EndExpr(end),
  4591. IterKind(FK_Expressions), IsConsidered(false) {}
  4592. FlattenedTypeTracker(QualType type,
  4593. CXXRecordDecl::base_class_iterator current,
  4594. CXXRecordDecl::base_class_iterator end)
  4595. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  4596. IterKind(FK_Bases), IsConsidered(false) {}
  4597. /// <summary>Gets the current expression if one is available.</summary>
  4598. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  4599. /// <summary>Replaces the current expression.</summary>
  4600. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  4601. };
  4602. HLSLExternalSource& m_source; // Source driving the iteration.
  4603. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  4604. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  4605. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  4606. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  4607. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  4608. QualType m_firstType; // Name of first type found, used for diagnostics.
  4609. SourceLocation m_loc; // Location used for diagnostics.
  4610. static const size_t MaxTypeDepth = 100;
  4611. void advanceLeafTracker();
  4612. /// <summary>Consumes leaves.</summary>
  4613. void consumeLeaf();
  4614. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  4615. bool considerLeaf();
  4616. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  4617. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  4618. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  4619. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  4620. public:
  4621. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  4622. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  4623. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  4624. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  4625. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  4626. QualType getCurrentElement() const;
  4627. /// <summary>Get the number of repeated current elements.</summary>
  4628. unsigned int getCurrentElementSize() const;
  4629. /// <summary>Gets the current element's Iterkind.</summary>
  4630. FlattenedIterKind getCurrentElementKind() const { return m_typeTrackers.back().IterKind; }
  4631. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  4632. bool hasCurrentElement() const;
  4633. /// <summary>Consumes count elements on this iterator.</summary>
  4634. void advanceCurrentElement(unsigned int count);
  4635. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  4636. unsigned int countRemaining();
  4637. /// <summary>Gets the current expression if one is available.</summary>
  4638. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  4639. /// <summary>Replaces the current expression.</summary>
  4640. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  4641. struct ComparisonResult
  4642. {
  4643. unsigned int LeftCount;
  4644. unsigned int RightCount;
  4645. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  4646. bool AreElementsEqual;
  4647. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  4648. bool CanConvertElements;
  4649. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  4650. bool IsConvertibleAndEqualLength() const {
  4651. return CanConvertElements && LeftCount == RightCount;
  4652. }
  4653. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  4654. bool IsConvertibleAndLeftLonger() const {
  4655. return CanConvertElements && LeftCount > RightCount;
  4656. }
  4657. bool IsRightLonger() const {
  4658. return RightCount > LeftCount;
  4659. }
  4660. bool IsEqualLength() const {
  4661. return LeftCount == RightCount;
  4662. }
  4663. };
  4664. static ComparisonResult CompareIterators(
  4665. HLSLExternalSource& source, SourceLocation loc,
  4666. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  4667. static ComparisonResult CompareTypes(
  4668. HLSLExternalSource& source,
  4669. SourceLocation leftLoc, SourceLocation rightLoc,
  4670. QualType left, QualType right);
  4671. // Compares the arguments to initialize the left type, modifying them if necessary.
  4672. static ComparisonResult CompareTypesForInit(
  4673. HLSLExternalSource& source, QualType left, MultiExprArg args,
  4674. SourceLocation leftLoc, SourceLocation rightLoc);
  4675. };
  4676. static
  4677. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  4678. {
  4679. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  4680. if (specialization) {
  4681. const TemplateArgumentList& list = specialization->getTemplateArgs();
  4682. if (list.size()) {
  4683. if (list[0].getKind() == TemplateArgument::ArgKind::Type)
  4684. return list[0].getAsType();
  4685. }
  4686. }
  4687. return QualType();
  4688. }
  4689. void HLSLExternalSource::AddBaseTypes()
  4690. {
  4691. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4692. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4693. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4694. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4695. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4696. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->HalfFloatTy : m_context->HalfTy;
  4697. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4698. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4699. m_baseTypes[HLSLScalarType_float_min10] = m_context->Min10FloatTy;
  4700. m_baseTypes[HLSLScalarType_float_min16] = m_context->Min16FloatTy;
  4701. m_baseTypes[HLSLScalarType_int_min12] = m_context->Min12IntTy;
  4702. m_baseTypes[HLSLScalarType_int_min16] = m_context->Min16IntTy;
  4703. m_baseTypes[HLSLScalarType_uint_min16] = m_context->Min16UIntTy;
  4704. m_baseTypes[HLSLScalarType_int8_4packed] = m_context->Int8_4PackedTy;
  4705. m_baseTypes[HLSLScalarType_uint8_4packed] = m_context->UInt8_4PackedTy;
  4706. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4707. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4708. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4709. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4710. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4711. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4712. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4713. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4714. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4715. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4716. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4717. }
  4718. void HLSLExternalSource::AddHLSLScalarTypes()
  4719. {
  4720. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4721. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4722. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4723. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4724. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4725. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4726. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4727. }
  4728. void HLSLExternalSource::AddHLSLStringType() {
  4729. m_hlslStringType = m_context->HLSLStringTy;
  4730. }
  4731. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4732. _In_ FunctionTemplateDecl* functionTemplate,
  4733. QualType objectElement,
  4734. const FindStructBasicTypeResult& findResult)
  4735. {
  4736. DXASSERT_NOMSG(functionTemplate != nullptr);
  4737. DXASSERT_NOMSG(!objectElement.isNull());
  4738. DXASSERT_NOMSG(findResult.Found());
  4739. DXASSERT(
  4740. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4741. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4742. // Subscript is templated only on its return type.
  4743. // Create the template argument.
  4744. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4745. QualType resultType = objectElement;
  4746. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  4747. resultType = m_context->getLValueReferenceType(resultType);
  4748. TemplateArgument templateArgument(resultType);
  4749. unsigned subscriptCardinality =
  4750. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4751. QualType subscriptIndexType =
  4752. subscriptCardinality == 1
  4753. ? m_context->UnsignedIntTy
  4754. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4755. subscriptCardinality);
  4756. // Look for an existing specialization.
  4757. void* InsertPos = nullptr;
  4758. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4759. if (SpecFunc != nullptr) {
  4760. return SpecFunc;
  4761. }
  4762. // Create a new specialization.
  4763. DeclContext* owner = functionTemplate->getDeclContext();
  4764. TemplateArgumentList templateArgumentList(
  4765. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4766. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4767. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4768. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4769. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4770. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4771. QualType functionType = m_context->getFunctionType(
  4772. resultType, subscriptIndexType, templateEPI, None);
  4773. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4774. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4775. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4776. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4777. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4778. QualType T = TInfo->getType();
  4779. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4780. CXXMethodDecl* method = CXXMethodDecl::Create(
  4781. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4782. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4783. // Add subscript attribute
  4784. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4785. // Record this function template specialization.
  4786. method->setFunctionTemplateSpecialization(functionTemplate,
  4787. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4788. // Attach the parameters
  4789. indexerParam->setOwningFunction(method);
  4790. Proto.setParam(0, indexerParam);
  4791. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4792. // Adjust access.
  4793. method->setAccess(AccessSpecifier::AS_public);
  4794. functionTemplate->setAccess(method->getAccess());
  4795. return method;
  4796. }
  4797. /// <summary>
  4798. /// This routine combines Source into Target. If you have a symmetric operation
  4799. /// and want to treat either side equally you should call it twice, swapping the
  4800. /// parameter order.
  4801. /// </summary>
  4802. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4803. _Out_opt_ ArBasicKind *pCombined) {
  4804. if (Target == Source) {
  4805. AssignOpt(Target, pCombined);
  4806. return true;
  4807. }
  4808. if (Source == AR_OBJECT_NULL) {
  4809. // NULL is valid for any object type.
  4810. AssignOpt(Target, pCombined);
  4811. return true;
  4812. }
  4813. switch (Target) {
  4814. AR_BASIC_ROBJECT_CASES:
  4815. if (Source == AR_OBJECT_STATEBLOCK) {
  4816. AssignOpt(Target, pCombined);
  4817. return true;
  4818. }
  4819. break;
  4820. AR_BASIC_TEXTURE_CASES:
  4821. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4822. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4823. AssignOpt(Target, pCombined);
  4824. return true;
  4825. }
  4826. break;
  4827. case AR_OBJECT_SAMPLERCOMPARISON:
  4828. if (Source == AR_OBJECT_STATEBLOCK) {
  4829. AssignOpt(Target, pCombined);
  4830. return true;
  4831. }
  4832. break;
  4833. default:
  4834. // Not a combinable target.
  4835. break;
  4836. }
  4837. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4838. return false;
  4839. }
  4840. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4841. HLSLExternalSource *pHLSLExternalSource) {
  4842. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4843. llvm::APInt val = intLit->getValue();
  4844. unsigned width = val.getActiveBits();
  4845. bool isNeg = val.isNegative();
  4846. if (isNeg) {
  4847. // Signed.
  4848. if (width <= 32)
  4849. return ArBasicKind::AR_BASIC_INT32;
  4850. else
  4851. return ArBasicKind::AR_BASIC_INT64;
  4852. } else {
  4853. // Unsigned.
  4854. if (width <= 32)
  4855. return ArBasicKind::AR_BASIC_UINT32;
  4856. else
  4857. return ArBasicKind::AR_BASIC_UINT64;
  4858. }
  4859. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4860. llvm::APFloat val = floatLit->getValue();
  4861. unsigned width = val.getSizeInBits(val.getSemantics());
  4862. if (width <= 16)
  4863. return ArBasicKind::AR_BASIC_FLOAT16;
  4864. else if (width <= 32)
  4865. return ArBasicKind::AR_BASIC_FLOAT32;
  4866. else
  4867. return AR_BASIC_FLOAT64;
  4868. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4869. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4870. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4871. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4872. kind = ArBasicKind::AR_BASIC_INT32;
  4873. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4874. kind = ArBasicKind::AR_BASIC_INT64;
  4875. }
  4876. return kind;
  4877. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4878. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4879. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4880. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4881. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4882. CombineBasicTypes(kind, kind1, &kind);
  4883. return kind;
  4884. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4885. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4886. return kind;
  4887. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4888. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4889. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4890. CombineBasicTypes(kind, kind1, &kind);
  4891. return kind;
  4892. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4893. // Use target Type for cast.
  4894. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4895. return kind;
  4896. } else {
  4897. // Could only be function call.
  4898. CallExpr *CE = cast<CallExpr>(litExpr);
  4899. // TODO: calculate the function call result.
  4900. if (CE->getNumArgs() == 1)
  4901. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4902. else {
  4903. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4904. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4905. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4906. CombineBasicTypes(kind, kindI, &kind);
  4907. }
  4908. return kind;
  4909. }
  4910. }
  4911. }
  4912. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4913. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4914. if (kind == *pCT)
  4915. return true;
  4916. pCT++;
  4917. }
  4918. return false;
  4919. }
  4920. static ArBasicKind
  4921. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4922. unsigned uLegalComponentTypes,
  4923. HLSLExternalSource *pHLSLExternalSource) {
  4924. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4925. ArBasicKind defaultKind = *pCT;
  4926. // Use first none literal kind as defaultKind.
  4927. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4928. ArBasicKind kind = *pCT;
  4929. pCT++;
  4930. // Skip literal type.
  4931. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4932. continue;
  4933. defaultKind = kind;
  4934. break;
  4935. }
  4936. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4937. if (kind == AR_BASIC_LITERAL_INT) {
  4938. // Search for match first.
  4939. // For literal arg which don't affect return type, the search should always success.
  4940. // Unless use literal int on a float parameter.
  4941. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4942. return litKind;
  4943. // Return the default.
  4944. return defaultKind;
  4945. }
  4946. else {
  4947. // Search for float32 first.
  4948. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4949. return AR_BASIC_FLOAT32;
  4950. // Search for float64.
  4951. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4952. return AR_BASIC_FLOAT64;
  4953. // return default.
  4954. return defaultKind;
  4955. }
  4956. }
  4957. _Use_decl_annotations_ bool
  4958. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4959. QualType objectElement) {
  4960. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4961. switch (op) {
  4962. case IntrinsicOp::MOP_Sample:
  4963. case IntrinsicOp::MOP_SampleBias:
  4964. case IntrinsicOp::MOP_SampleCmp:
  4965. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4966. case IntrinsicOp::MOP_SampleGrad:
  4967. case IntrinsicOp::MOP_SampleLevel: {
  4968. ArBasicKind kind = GetTypeElementKind(objectElement);
  4969. UINT uBits = GET_BPROP_BITS(kind);
  4970. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4971. } break;
  4972. default:
  4973. return true;
  4974. }
  4975. }
  4976. _Use_decl_annotations_
  4977. bool HLSLExternalSource::MatchArguments(
  4978. const HLSL_INTRINSIC* pIntrinsic,
  4979. QualType objectElement,
  4980. QualType functionTemplateTypeArg,
  4981. ArrayRef<Expr *> Args,
  4982. std::vector<QualType> *argTypesVector,
  4983. size_t &badArgIdx)
  4984. {
  4985. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4986. DXASSERT_NOMSG(argTypesVector != nullptr);
  4987. std::vector<QualType> &argTypes = *argTypesVector;
  4988. argTypes.clear();
  4989. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  4990. static const UINT UnusedSize = 0xFF;
  4991. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4992. #define CAB(cond,arg) { if (!(cond)) { badArgIdx = (arg); return false; } }
  4993. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4994. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4995. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4996. badArgIdx = MaxIntrinsicArgs;
  4997. // Reset infos
  4998. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4999. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  5000. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  5001. const unsigned retArgIdx = 0;
  5002. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  5003. // Populate the template for each argument.
  5004. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  5005. ArrayRef<Expr*>::iterator end = Args.end();
  5006. size_t iArg = 1;
  5007. for (; iterArg != end; ++iterArg) {
  5008. Expr* pCallArg = *iterArg;
  5009. // If vararg is reached, we can break out of this loop.
  5010. if(pIntrinsic->pArgs[iArg].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5011. break;
  5012. // Check bounds for non-variadic functions.
  5013. if (iArg >= MaxIntrinsicArgs || iArg > pIntrinsic->uNumArgs) {
  5014. // Currently never reached
  5015. badArgIdx = iArg;
  5016. return false;
  5017. }
  5018. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  5019. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  5020. DXASSERT(isVariadic ||
  5021. pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS,
  5022. "found vararg for non-variadic function");
  5023. QualType pType = pCallArg->getType();
  5024. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  5025. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  5026. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_RAYDESC) {
  5027. if (TypeInfoShapeKind == AR_TOBJ_COMPOUND) {
  5028. if (CXXRecordDecl *pDecl = pType->getAsCXXRecordDecl()) {
  5029. int index = FindObjectBasicKindIndex(pDecl);
  5030. if (index != -1 && AR_OBJECT_RAY_DESC == g_ArBasicKindsAsTypes[index]) {
  5031. ++iArg;
  5032. continue;
  5033. }
  5034. }
  5035. }
  5036. m_sema->Diag(pCallArg->getExprLoc(),
  5037. diag::err_hlsl_ray_desc_required);
  5038. badArgIdx = iArg;
  5039. return false;
  5040. }
  5041. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5042. DXASSERT_NOMSG(objectElement.isNull());
  5043. QualType Ty = pCallArg->getType();
  5044. // Must be user define type for LICOMPTYPE_USER_DEFINED_TYPE arg.
  5045. if (TypeInfoShapeKind != AR_TOBJ_COMPOUND) {
  5046. m_sema->Diag(pCallArg->getExprLoc(),
  5047. diag::err_hlsl_no_struct_user_defined_type);
  5048. badArgIdx = iArg;
  5049. return false;
  5050. }
  5051. objectElement = Ty;
  5052. ++iArg;
  5053. continue;
  5054. }
  5055. // If we are a type and templateID requires one, this isn't a match.
  5056. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  5057. || pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5058. ++iArg;
  5059. continue;
  5060. }
  5061. // Verify TypeInfoEltKind can be cast to something legal for this param
  5062. if (AR_BASIC_UNKNOWN != TypeInfoEltKind) {
  5063. for (const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pIntrinsicArg->uLegalComponentTypes];
  5064. AR_BASIC_UNKNOWN != *pCT; pCT++) {
  5065. if (TypeInfoEltKind == *pCT)
  5066. break;
  5067. else if ((TypeInfoEltKind == AR_BASIC_LITERAL_INT && *pCT == AR_BASIC_LITERAL_FLOAT) ||
  5068. (TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT && *pCT == AR_BASIC_LITERAL_INT))
  5069. break;
  5070. else if (*pCT == AR_BASIC_NOCAST) {
  5071. badArgIdx = std::min(badArgIdx, iArg);
  5072. }
  5073. }
  5074. }
  5075. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  5076. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  5077. bool affectRetType =
  5078. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  5079. // For literal arg which don't affect return type, find concrete type.
  5080. // For literal arg affect return type,
  5081. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  5082. // where all argumentss are literal.
  5083. // CombineBasicTypes will cover the rest cases.
  5084. if (!affectRetType) {
  5085. TypeInfoEltKind = ConcreteLiteralType(
  5086. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  5087. }
  5088. }
  5089. UINT TypeInfoCols = 1;
  5090. UINT TypeInfoRows = 1;
  5091. switch (TypeInfoShapeKind) {
  5092. case AR_TOBJ_MATRIX:
  5093. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  5094. break;
  5095. case AR_TOBJ_VECTOR:
  5096. TypeInfoCols = GetHLSLVecSize(pType);
  5097. break;
  5098. case AR_TOBJ_BASIC:
  5099. case AR_TOBJ_OBJECT:
  5100. case AR_TOBJ_STRING:
  5101. break;
  5102. default:
  5103. badArgIdx = std::min(badArgIdx, iArg); // no struct, arrays or void
  5104. }
  5105. DXASSERT(
  5106. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  5107. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  5108. // Compare template
  5109. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  5110. ((AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  5111. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind))) {
  5112. // Unrestricted or truncation of tuples to scalars are allowed
  5113. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  5114. }
  5115. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  5116. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  5117. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  5118. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  5119. // Scalars to tuples can be splatted, scalar to anything else is not allowed
  5120. badArgIdx = std::min(badArgIdx, iArg);
  5121. }
  5122. }
  5123. else {
  5124. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  5125. // Outside of simple splats and truncations, templates must match
  5126. badArgIdx = std::min(badArgIdx, iArg);
  5127. }
  5128. }
  5129. DXASSERT(
  5130. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  5131. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  5132. // Merge ComponentTypes
  5133. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  5134. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  5135. }
  5136. else {
  5137. if (!CombineBasicTypes(
  5138. ComponentType[pIntrinsicArg->uComponentTypeId],
  5139. TypeInfoEltKind,
  5140. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  5141. badArgIdx = std::min(badArgIdx, iArg);
  5142. }
  5143. }
  5144. // Rows
  5145. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  5146. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  5147. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  5148. CAB(uSpecialId < IA_SPECIAL_SLOTS, iArg);
  5149. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  5150. uSpecialSize[uSpecialId] = TypeInfoRows;
  5151. }
  5152. }
  5153. else {
  5154. if (TypeInfoRows < pIntrinsicArg->uRows) {
  5155. badArgIdx = std::min(badArgIdx, iArg);
  5156. }
  5157. }
  5158. }
  5159. // Columns
  5160. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  5161. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  5162. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  5163. CAB(uSpecialId < IA_SPECIAL_SLOTS, iArg);
  5164. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  5165. uSpecialSize[uSpecialId] = TypeInfoCols;
  5166. }
  5167. }
  5168. else {
  5169. if (TypeInfoCols < pIntrinsicArg->uCols) {
  5170. badArgIdx = std::min(badArgIdx, iArg);
  5171. }
  5172. }
  5173. }
  5174. // Usage
  5175. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  5176. if (pCallArg->getType().isConstQualified()) {
  5177. // Can't use a const type in an out or inout parameter.
  5178. badArgIdx = std::min(badArgIdx, iArg);
  5179. }
  5180. }
  5181. iArg++;
  5182. }
  5183. DXASSERT(isVariadic || iterArg == end,
  5184. "otherwise the argument list wasn't fully processed");
  5185. // Default template and component type for return value
  5186. if (pIntrinsic->pArgs[0].qwUsage
  5187. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE
  5188. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_FUNCTION) {
  5189. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs, 0);
  5190. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  5191. Template[pIntrinsic->pArgs[0].uTemplateId] =
  5192. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  5193. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  5194. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  5195. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  5196. // half return type should map to float for min precision
  5197. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  5198. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  5199. getSema()->getLangOpts().UseMinPrecision) {
  5200. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  5201. ArBasicKind::AR_BASIC_FLOAT32;
  5202. }
  5203. else {
  5204. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  5205. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  5206. }
  5207. }
  5208. }
  5209. }
  5210. }
  5211. // Make sure all template, component type, and texture type selections are valid.
  5212. for (size_t i = 0; i < Args.size() + 1; i++) {
  5213. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  5214. // If vararg is reached, we can break out of this loop.
  5215. if(pIntrinsic->pArgs[i].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5216. break;
  5217. // Check template.
  5218. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  5219. || pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5220. continue; // Already verified that this is available.
  5221. }
  5222. if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5223. continue;
  5224. }
  5225. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  5226. if (AR_TOBJ_UNKNOWN != Template[i]) {
  5227. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  5228. Template[i] = *pTT;
  5229. }
  5230. else if(AR_TOBJ_STRING == Template[i] && *pTT == AR_TOBJ_OBJECT) {
  5231. Template[i] = *pTT;
  5232. }
  5233. else {
  5234. while (AR_TOBJ_UNKNOWN != *pTT) {
  5235. if (Template[i] == *pTT)
  5236. break;
  5237. pTT++;
  5238. }
  5239. }
  5240. if (AR_TOBJ_UNKNOWN == *pTT) {
  5241. Template[i] = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates][0];
  5242. badArgIdx = std::min(badArgIdx, i);
  5243. }
  5244. }
  5245. else if (pTT) {
  5246. Template[i] = *pTT;
  5247. }
  5248. // Check component type.
  5249. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  5250. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  5251. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  5252. if (ComponentType[i] == *pCT)
  5253. break;
  5254. pCT++;
  5255. }
  5256. // has to be a strict match
  5257. if (*pCT == AR_BASIC_NOCAST) {
  5258. badArgIdx = std::min(badArgIdx, i);
  5259. // the match has failed, but the types are useful for errors. Present the cannonical overload for error
  5260. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  5261. }
  5262. // If it is an object, see if it can be cast to the first thing in the
  5263. // list, otherwise move on to next intrinsic.
  5264. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  5265. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  5266. badArgIdx = std::min(badArgIdx, i);
  5267. }
  5268. }
  5269. if (AR_BASIC_UNKNOWN == *pCT) {
  5270. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  5271. }
  5272. }
  5273. else if (pCT) {
  5274. ComponentType[i] = *pCT;
  5275. }
  5276. }
  5277. argTypes.resize(1 + Args.size()); // +1 for return type
  5278. // Default to a void return type.
  5279. argTypes[0] = m_context->VoidTy;
  5280. // Default specials sizes.
  5281. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  5282. if (UnusedSize == uSpecialSize[i]) {
  5283. uSpecialSize[i] = 1;
  5284. }
  5285. }
  5286. // Populate argTypes.
  5287. for (size_t i = 0; i <= Args.size(); i++) {
  5288. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  5289. // If vararg is reached, we can break out of this loop.
  5290. if (pArgument->uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5291. break;
  5292. if (!pArgument->qwUsage)
  5293. continue;
  5294. QualType pNewType;
  5295. unsigned int quals = 0; // qualifications for this argument
  5296. // If we have no type, set it to our input type (templatized)
  5297. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  5298. // Use the templated input type, but resize it if the
  5299. // intrinsic's rows/cols isn't 0
  5300. if (pArgument->uRows && pArgument->uCols) {
  5301. UINT uRows, uCols = 0;
  5302. // if type is overriden, use new type size, for
  5303. // now it only supports scalars
  5304. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5305. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5306. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5307. uRows = uSpecialSize[uSpecialId];
  5308. }
  5309. else if (pArgument->uRows > 0) {
  5310. uRows = pArgument->uRows;
  5311. }
  5312. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5313. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5314. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5315. uCols = uSpecialSize[uSpecialId];
  5316. }
  5317. else if (pArgument->uCols > 0) {
  5318. uCols = pArgument->uCols;
  5319. }
  5320. // 1x1 numeric outputs are always scalar.. since these
  5321. // are most flexible
  5322. if ((1 == uCols) && (1 == uRows)) {
  5323. pNewType = objectElement;
  5324. if (pNewType.isNull()) {
  5325. badArgIdx = std::min(badArgIdx, i);
  5326. }
  5327. }
  5328. else {
  5329. // non-scalars unsupported right now since nothing
  5330. // uses it, would have to create either a type
  5331. // list for sub-structures or just resize the
  5332. // given type
  5333. // VH(E_NOTIMPL);
  5334. badArgIdx = std::min(badArgIdx, i);
  5335. }
  5336. }
  5337. else {
  5338. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  5339. if (objectElement.isNull()) {
  5340. badArgIdx = std::min(badArgIdx, i);
  5341. }
  5342. pNewType = objectElement;
  5343. }
  5344. }
  5345. else if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5346. if (functionTemplateTypeArg.isNull()) {
  5347. if (i == 0) {
  5348. // [RW]ByteAddressBuffer.Load, default to uint
  5349. pNewType = m_context->UnsignedIntTy;
  5350. }
  5351. else {
  5352. // [RW]ByteAddressBuffer.Store, default to argument type
  5353. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5354. if (const BuiltinType *BuiltinTy = pNewType->getAs<BuiltinType>()) {
  5355. // For backcompat, ensure that Store(0, 42 or 42.0) matches a uint/float overload
  5356. // rather than a uint64_t/double one.
  5357. if (BuiltinTy->getKind() == BuiltinType::LitInt) {
  5358. pNewType = m_context->UnsignedIntTy;
  5359. } else if (BuiltinTy->getKind() == BuiltinType::LitFloat) {
  5360. pNewType = m_context->FloatTy;
  5361. }
  5362. }
  5363. }
  5364. }
  5365. else {
  5366. pNewType = functionTemplateTypeArg;
  5367. }
  5368. }
  5369. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5370. if (objectElement.isNull()) {
  5371. badArgIdx = std::min(badArgIdx, i);
  5372. }
  5373. pNewType = objectElement;
  5374. }
  5375. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2D
  5376. || pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2DARRAY) {
  5377. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5378. }
  5379. else {
  5380. ArBasicKind pEltType;
  5381. // ComponentType, if the Id is special then it gets the
  5382. // component type from the first component of the type, if
  5383. // we need more (for the second component, e.g.), then we
  5384. // can use more specials, etc.
  5385. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  5386. if (objectElement.isNull()) {
  5387. badArgIdx = std::min(badArgIdx, i);
  5388. return false;
  5389. }
  5390. pEltType = GetTypeElementKind(objectElement);
  5391. if (!IsValidBasicKind(pEltType)) {
  5392. // This can happen with Texture2D<Struct> or other invalid declarations
  5393. badArgIdx = std::min(badArgIdx, i);
  5394. return false;
  5395. }
  5396. }
  5397. else {
  5398. pEltType = ComponentType[pArgument->uComponentTypeId];
  5399. DXASSERT_VALIDBASICKIND(pEltType);
  5400. }
  5401. UINT uRows, uCols;
  5402. // Rows
  5403. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5404. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5405. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5406. uRows = uSpecialSize[uSpecialId];
  5407. }
  5408. else {
  5409. uRows = pArgument->uRows;
  5410. }
  5411. // Cols
  5412. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5413. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5414. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5415. uCols = uSpecialSize[uSpecialId];
  5416. }
  5417. else {
  5418. uCols = pArgument->uCols;
  5419. }
  5420. // Verify that the final results are in bounds.
  5421. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize, i);
  5422. // Const
  5423. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  5424. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  5425. qwQual |= AR_QUAL_CONST;
  5426. DXASSERT_VALIDBASICKIND(pEltType);
  5427. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  5428. }
  5429. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  5430. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  5431. // TODO: support out modifier
  5432. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  5433. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  5434. //}
  5435. }
  5436. // For variadic functions, we need to add the additional arguments here.
  5437. if(isVariadic) {
  5438. for (; iArg <= Args.size(); ++iArg) {
  5439. argTypes[iArg] = Args[iArg - 1]->getType().getNonReferenceType();
  5440. }
  5441. } else {
  5442. DXASSERT(iArg == pIntrinsic->uNumArgs,
  5443. "In the absence of varargs, a successful match would indicate we "
  5444. "have as many arguments and types as the intrinsic template");
  5445. }
  5446. return badArgIdx == MaxIntrinsicArgs;
  5447. #undef CAB
  5448. }
  5449. _Use_decl_annotations_
  5450. HLSLExternalSource::FindStructBasicTypeResult
  5451. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  5452. {
  5453. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5454. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  5455. // may be a simple class, such as RWByteAddressBuffer.
  5456. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  5457. // We save the caller from filtering out other types of context (like the translation unit itself).
  5458. if (recordDecl != nullptr)
  5459. {
  5460. int index = FindObjectBasicKindIndex(recordDecl);
  5461. if (index != -1) {
  5462. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  5463. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  5464. }
  5465. }
  5466. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  5467. }
  5468. _Use_decl_annotations_
  5469. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  5470. {
  5471. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5472. DXASSERT_NOMSG(name != nullptr);
  5473. DXASSERT_NOMSG(intrinsics != nullptr);
  5474. DXASSERT_NOMSG(intrinsicCount != nullptr);
  5475. *intrinsics = nullptr;
  5476. *intrinsicCount = 0;
  5477. *name = nullptr;
  5478. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  5479. if (lookup.Found()) {
  5480. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  5481. *name = g_ArBasicTypeNames[lookup.Kind];
  5482. }
  5483. }
  5484. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  5485. {
  5486. return
  5487. // Arithmetic operators.
  5488. Opc == BinaryOperatorKind::BO_Add ||
  5489. Opc == BinaryOperatorKind::BO_AddAssign ||
  5490. Opc == BinaryOperatorKind::BO_Sub ||
  5491. Opc == BinaryOperatorKind::BO_SubAssign ||
  5492. Opc == BinaryOperatorKind::BO_Rem ||
  5493. Opc == BinaryOperatorKind::BO_RemAssign ||
  5494. Opc == BinaryOperatorKind::BO_Div ||
  5495. Opc == BinaryOperatorKind::BO_DivAssign ||
  5496. Opc == BinaryOperatorKind::BO_Mul ||
  5497. Opc == BinaryOperatorKind::BO_MulAssign;
  5498. }
  5499. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  5500. {
  5501. return
  5502. // Arithmetic-and-assignment operators.
  5503. Opc == BinaryOperatorKind::BO_AddAssign ||
  5504. Opc == BinaryOperatorKind::BO_SubAssign ||
  5505. Opc == BinaryOperatorKind::BO_RemAssign ||
  5506. Opc == BinaryOperatorKind::BO_DivAssign ||
  5507. Opc == BinaryOperatorKind::BO_MulAssign ||
  5508. // Bitwise-and-assignment operators.
  5509. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5510. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5511. Opc == BinaryOperatorKind::BO_AndAssign ||
  5512. Opc == BinaryOperatorKind::BO_OrAssign ||
  5513. Opc == BinaryOperatorKind::BO_XorAssign;
  5514. }
  5515. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  5516. {
  5517. return
  5518. Opc == BinaryOperatorKind::BO_AndAssign ||
  5519. Opc == BinaryOperatorKind::BO_OrAssign ||
  5520. Opc == BinaryOperatorKind::BO_XorAssign;
  5521. }
  5522. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  5523. {
  5524. return
  5525. Opc == BinaryOperatorKind::BO_Shl ||
  5526. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5527. Opc == BinaryOperatorKind::BO_Shr ||
  5528. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5529. Opc == BinaryOperatorKind::BO_And ||
  5530. Opc == BinaryOperatorKind::BO_AndAssign ||
  5531. Opc == BinaryOperatorKind::BO_Or ||
  5532. Opc == BinaryOperatorKind::BO_OrAssign ||
  5533. Opc == BinaryOperatorKind::BO_Xor ||
  5534. Opc == BinaryOperatorKind::BO_XorAssign;
  5535. }
  5536. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  5537. {
  5538. return
  5539. Opc == BinaryOperatorKind::BO_Shl ||
  5540. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5541. Opc == BinaryOperatorKind::BO_Shr ||
  5542. Opc == BinaryOperatorKind::BO_ShrAssign;
  5543. }
  5544. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  5545. {
  5546. return
  5547. Opc == BinaryOperatorKind::BO_EQ ||
  5548. Opc == BinaryOperatorKind::BO_NE;
  5549. }
  5550. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  5551. {
  5552. return
  5553. Opc == BinaryOperatorKind::BO_LT ||
  5554. Opc == BinaryOperatorKind::BO_GT ||
  5555. Opc == BinaryOperatorKind::BO_LE ||
  5556. Opc == BinaryOperatorKind::BO_GE;
  5557. }
  5558. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  5559. {
  5560. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  5561. }
  5562. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  5563. {
  5564. return
  5565. Opc == BinaryOperatorKind::BO_LAnd ||
  5566. Opc == BinaryOperatorKind::BO_LOr;
  5567. }
  5568. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  5569. {
  5570. return
  5571. BinaryOperatorKindIsArithmetic(Opc) ||
  5572. BinaryOperatorKindIsOrderComparison(Opc) ||
  5573. BinaryOperatorKindIsLogical(Opc);
  5574. }
  5575. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  5576. {
  5577. return BinaryOperatorKindIsBitwise(Opc);
  5578. }
  5579. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  5580. {
  5581. return
  5582. BinaryOperatorKindIsBitwise(Opc) ||
  5583. BinaryOperatorKindIsArithmetic(Opc);
  5584. }
  5585. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  5586. {
  5587. return Opc == UnaryOperatorKind::UO_Not;
  5588. }
  5589. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  5590. {
  5591. return
  5592. Opc == UnaryOperatorKind::UO_LNot ||
  5593. Opc == UnaryOperatorKind::UO_Plus ||
  5594. Opc == UnaryOperatorKind::UO_Minus ||
  5595. // The omission in fxc caused objects and structs to accept this.
  5596. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5597. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5598. }
  5599. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  5600. {
  5601. return
  5602. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5603. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5604. }
  5605. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  5606. {
  5607. return
  5608. Opc == UnaryOperatorKind::UO_Not ||
  5609. Opc == UnaryOperatorKind::UO_Plus ||
  5610. Opc == UnaryOperatorKind::UO_Minus;
  5611. }
  5612. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  5613. {
  5614. return
  5615. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5616. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5617. }
  5618. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  5619. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  5620. }
  5621. /// <summary>
  5622. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  5623. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  5624. /// </summary>
  5625. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  5626. {
  5627. return
  5628. value == AR_TOBJ_BASIC ||
  5629. value == AR_TOBJ_MATRIX ||
  5630. value == AR_TOBJ_VECTOR;
  5631. }
  5632. static bool IsBasicKindIntegral(ArBasicKind value)
  5633. {
  5634. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  5635. }
  5636. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  5637. {
  5638. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  5639. }
  5640. static bool IsBasicKindNumeric(ArBasicKind value)
  5641. {
  5642. return GetBasicKindProps(value) & BPROP_NUMERIC;
  5643. }
  5644. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  5645. {
  5646. // An invalid expression is pass-through at this point.
  5647. if (E.isInvalid())
  5648. {
  5649. return E;
  5650. }
  5651. QualType qt = E.get()->getType();
  5652. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  5653. if (elementKind != AR_BASIC_BOOL)
  5654. {
  5655. return E;
  5656. }
  5657. // Construct a scalar/vector/matrix type with the same shape as E.
  5658. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  5659. QualType targetType;
  5660. UINT colCount, rowCount;
  5661. GetRowsAndColsForAny(qt, rowCount, colCount);
  5662. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  5663. if (E.get()->isLValue()) {
  5664. E = m_sema->DefaultLvalueConversion(E.get()).get();
  5665. }
  5666. switch (objectKind)
  5667. {
  5668. case AR_TOBJ_SCALAR:
  5669. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5670. case AR_TOBJ_ARRAY:
  5671. case AR_TOBJ_VECTOR:
  5672. case AR_TOBJ_MATRIX:
  5673. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5674. default:
  5675. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  5676. }
  5677. return E;
  5678. }
  5679. _Use_decl_annotations_
  5680. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  5681. {
  5682. DXASSERT_NOMSG(pTypeInfo != nullptr);
  5683. DXASSERT_NOMSG(!type.isNull());
  5684. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  5685. // TODO: Get* functions used here add up to a bunch of redundant code.
  5686. // Try to inline that here, making it cheaper to use this function
  5687. // when retrieving multiple properties.
  5688. pTypeInfo->ObjKind = GetTypeElementKind(type);
  5689. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  5690. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  5691. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  5692. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  5693. }
  5694. // Highest possible score (i.e., worst possible score).
  5695. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  5696. // Leave the first two score bits to handle higher-level
  5697. // variations like target type.
  5698. #define SCORE_MIN_SHIFT 2
  5699. // Space out scores to allow up to 128 parameters to
  5700. // vary between score sets spill into each other.
  5701. #define SCORE_PARAM_SHIFT 7
  5702. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  5703. if (anyType.isNull()) {
  5704. return 0;
  5705. }
  5706. anyType = GetStructuralForm(anyType);
  5707. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5708. switch (kind) {
  5709. case AR_TOBJ_BASIC:
  5710. case AR_TOBJ_OBJECT:
  5711. case AR_TOBJ_STRING:
  5712. return 1;
  5713. case AR_TOBJ_COMPOUND: {
  5714. // TODO: consider caching this value for perf
  5715. unsigned total = 0;
  5716. const RecordType *recordType = anyType->getAs<RecordType>();
  5717. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5718. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5719. while (fi != fend) {
  5720. total += GetNumElements(fi->getType());
  5721. ++fi;
  5722. }
  5723. return total;
  5724. }
  5725. case AR_TOBJ_ARRAY:
  5726. case AR_TOBJ_MATRIX:
  5727. case AR_TOBJ_VECTOR:
  5728. return GetElementCount(anyType);
  5729. default:
  5730. DXASSERT(kind == AR_TOBJ_VOID,
  5731. "otherwise the type cannot be classified or is not supported");
  5732. return 0;
  5733. }
  5734. }
  5735. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  5736. if (anyType.isNull()) {
  5737. return 0;
  5738. }
  5739. anyType = GetStructuralForm(anyType);
  5740. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5741. switch (kind) {
  5742. case AR_TOBJ_BASIC:
  5743. case AR_TOBJ_OBJECT:
  5744. case AR_TOBJ_STRING:
  5745. return 1;
  5746. case AR_TOBJ_COMPOUND: {
  5747. // TODO: consider caching this value for perf
  5748. unsigned total = 0;
  5749. const RecordType *recordType = anyType->getAs<RecordType>();
  5750. RecordDecl * RD = recordType->getDecl();
  5751. // Take care base.
  5752. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5753. if (CXXRD->getNumBases()) {
  5754. for (const auto &I : CXXRD->bases()) {
  5755. const CXXRecordDecl *BaseDecl =
  5756. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5757. if (BaseDecl->field_empty())
  5758. continue;
  5759. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5760. total += GetNumBasicElements(parentTy);
  5761. }
  5762. }
  5763. }
  5764. RecordDecl::field_iterator fi = RD->field_begin();
  5765. RecordDecl::field_iterator fend = RD->field_end();
  5766. while (fi != fend) {
  5767. total += GetNumBasicElements(fi->getType());
  5768. ++fi;
  5769. }
  5770. return total;
  5771. }
  5772. case AR_TOBJ_ARRAY: {
  5773. unsigned arraySize = GetElementCount(anyType);
  5774. unsigned eltSize = GetNumBasicElements(
  5775. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  5776. return arraySize * eltSize;
  5777. }
  5778. case AR_TOBJ_MATRIX:
  5779. case AR_TOBJ_VECTOR:
  5780. return GetElementCount(anyType);
  5781. default:
  5782. DXASSERT(kind == AR_TOBJ_VOID,
  5783. "otherwise the type cannot be classified or is not supported");
  5784. return 0;
  5785. }
  5786. }
  5787. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  5788. unsigned leftSize,
  5789. QualType rightType,
  5790. unsigned rightSize) {
  5791. // We can convert from a larger type to a smaller
  5792. // but not a smaller type to a larger so default
  5793. // to just comparing the destination size.
  5794. unsigned uElts = leftSize;
  5795. leftType = GetStructuralForm(leftType);
  5796. rightType = GetStructuralForm(rightType);
  5797. if (leftType->isArrayType() && rightType->isArrayType()) {
  5798. //
  5799. // If we're comparing arrays we don't
  5800. // need to compare every element of
  5801. // the arrays since all elements
  5802. // will have the same type.
  5803. // We only need to compare enough
  5804. // elements that we've tried every
  5805. // possible mix of dst and src elements.
  5806. //
  5807. // TODO: handle multidimensional arrays and arrays of arrays
  5808. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5809. unsigned uDstEltSize = GetNumElements(pDstElt);
  5810. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5811. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5812. if (uDstEltSize == uSrcEltSize) {
  5813. uElts = uDstEltSize;
  5814. } else if (uDstEltSize > uSrcEltSize) {
  5815. // If one size is not an even multiple of the other we need to let the
  5816. // full compare run in order to try all alignments.
  5817. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5818. uElts = uDstEltSize;
  5819. }
  5820. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5821. uElts = uSrcEltSize;
  5822. }
  5823. }
  5824. return uElts;
  5825. }
  5826. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5827. if (type.isNull()) {
  5828. return type;
  5829. }
  5830. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5831. switch (kind) {
  5832. case AR_TOBJ_BASIC:
  5833. case AR_TOBJ_OBJECT:
  5834. case AR_TOBJ_STRING:
  5835. return (index == 0) ? type : QualType();
  5836. case AR_TOBJ_COMPOUND: {
  5837. // TODO: consider caching this value for perf
  5838. const RecordType *recordType = type->getAsStructureType();
  5839. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5840. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5841. while (fi != fend) {
  5842. if (!fi->getType().isNull()) {
  5843. unsigned subElements = GetNumElements(fi->getType());
  5844. if (index < subElements) {
  5845. return GetNthElementType(fi->getType(), index);
  5846. } else {
  5847. index -= subElements;
  5848. }
  5849. }
  5850. ++fi;
  5851. }
  5852. return QualType();
  5853. }
  5854. case AR_TOBJ_ARRAY: {
  5855. unsigned arraySize;
  5856. QualType elementType;
  5857. unsigned elementCount;
  5858. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5859. elementCount = GetElementCount(elementType);
  5860. if (index < elementCount) {
  5861. return GetNthElementType(elementType, index);
  5862. }
  5863. arraySize = GetArraySize(type);
  5864. if (index >= arraySize * elementCount) {
  5865. return QualType();
  5866. }
  5867. return GetNthElementType(elementType, index % elementCount);
  5868. }
  5869. case AR_TOBJ_MATRIX:
  5870. case AR_TOBJ_VECTOR:
  5871. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5872. : QualType();
  5873. default:
  5874. DXASSERT(kind == AR_TOBJ_VOID,
  5875. "otherwise the type cannot be classified or is not supported");
  5876. return QualType();
  5877. }
  5878. }
  5879. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5880. // Eliminate exact matches first, then check for promotions.
  5881. if (leftKind == rightKind) {
  5882. return false;
  5883. }
  5884. switch (rightKind) {
  5885. case AR_BASIC_FLOAT16:
  5886. switch (leftKind) {
  5887. case AR_BASIC_FLOAT32:
  5888. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5889. case AR_BASIC_FLOAT64:
  5890. return true;
  5891. default:
  5892. return false; // No other type is a promotion.
  5893. }
  5894. break;
  5895. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5896. switch (leftKind) {
  5897. case AR_BASIC_FLOAT32:
  5898. case AR_BASIC_FLOAT64:
  5899. return true;
  5900. default:
  5901. return false; // No other type is a promotion.
  5902. }
  5903. break;
  5904. case AR_BASIC_FLOAT32:
  5905. switch (leftKind) {
  5906. case AR_BASIC_FLOAT64:
  5907. return true;
  5908. default:
  5909. return false; // No other type is a promotion.
  5910. }
  5911. break;
  5912. case AR_BASIC_MIN10FLOAT:
  5913. switch (leftKind) {
  5914. case AR_BASIC_MIN16FLOAT:
  5915. case AR_BASIC_FLOAT16:
  5916. case AR_BASIC_FLOAT32:
  5917. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5918. case AR_BASIC_FLOAT64:
  5919. return true;
  5920. default:
  5921. return false; // No other type is a promotion.
  5922. }
  5923. break;
  5924. case AR_BASIC_MIN16FLOAT:
  5925. switch (leftKind) {
  5926. case AR_BASIC_FLOAT16:
  5927. case AR_BASIC_FLOAT32:
  5928. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5929. case AR_BASIC_FLOAT64:
  5930. return true;
  5931. default:
  5932. return false; // No other type is a promotion.
  5933. }
  5934. break;
  5935. case AR_BASIC_INT8:
  5936. case AR_BASIC_UINT8:
  5937. // For backwards compat we consider signed/unsigned the same.
  5938. switch (leftKind) {
  5939. case AR_BASIC_INT16:
  5940. case AR_BASIC_INT32:
  5941. case AR_BASIC_INT64:
  5942. case AR_BASIC_UINT16:
  5943. case AR_BASIC_UINT32:
  5944. case AR_BASIC_UINT64:
  5945. return true;
  5946. default:
  5947. return false; // No other type is a promotion.
  5948. }
  5949. break;
  5950. case AR_BASIC_INT16:
  5951. case AR_BASIC_UINT16:
  5952. // For backwards compat we consider signed/unsigned the same.
  5953. switch (leftKind) {
  5954. case AR_BASIC_INT32:
  5955. case AR_BASIC_INT64:
  5956. case AR_BASIC_UINT32:
  5957. case AR_BASIC_UINT64:
  5958. return true;
  5959. default:
  5960. return false; // No other type is a promotion.
  5961. }
  5962. break;
  5963. case AR_BASIC_INT32:
  5964. case AR_BASIC_UINT32:
  5965. // For backwards compat we consider signed/unsigned the same.
  5966. switch (leftKind) {
  5967. case AR_BASIC_INT64:
  5968. case AR_BASIC_UINT64:
  5969. return true;
  5970. default:
  5971. return false; // No other type is a promotion.
  5972. }
  5973. break;
  5974. case AR_BASIC_MIN12INT:
  5975. switch (leftKind) {
  5976. case AR_BASIC_MIN16INT:
  5977. case AR_BASIC_INT32:
  5978. case AR_BASIC_INT64:
  5979. return true;
  5980. default:
  5981. return false; // No other type is a promotion.
  5982. }
  5983. break;
  5984. case AR_BASIC_MIN16INT:
  5985. switch (leftKind) {
  5986. case AR_BASIC_INT32:
  5987. case AR_BASIC_INT64:
  5988. return true;
  5989. default:
  5990. return false; // No other type is a promotion.
  5991. }
  5992. break;
  5993. case AR_BASIC_MIN16UINT:
  5994. switch (leftKind) {
  5995. case AR_BASIC_UINT32:
  5996. case AR_BASIC_UINT64:
  5997. return true;
  5998. default:
  5999. return false; // No other type is a promotion.
  6000. }
  6001. break;
  6002. }
  6003. return false;
  6004. }
  6005. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  6006. // Eliminate exact matches first, then check for casts.
  6007. if (leftKind == rightKind) {
  6008. return false;
  6009. }
  6010. //
  6011. // All minimum-bits types are only considered matches of themselves
  6012. // and thus are not in this table.
  6013. //
  6014. switch (leftKind) {
  6015. case AR_BASIC_LITERAL_INT:
  6016. switch (rightKind) {
  6017. case AR_BASIC_INT8:
  6018. case AR_BASIC_INT16:
  6019. case AR_BASIC_INT32:
  6020. case AR_BASIC_INT64:
  6021. case AR_BASIC_UINT8:
  6022. case AR_BASIC_UINT16:
  6023. case AR_BASIC_UINT32:
  6024. case AR_BASIC_UINT64:
  6025. return false;
  6026. default:
  6027. break; // No other valid cast types
  6028. }
  6029. break;
  6030. case AR_BASIC_INT8:
  6031. switch (rightKind) {
  6032. // For backwards compat we consider signed/unsigned the same.
  6033. case AR_BASIC_LITERAL_INT:
  6034. case AR_BASIC_UINT8:
  6035. return false;
  6036. default:
  6037. break; // No other valid cast types
  6038. }
  6039. break;
  6040. case AR_BASIC_INT16:
  6041. switch (rightKind) {
  6042. // For backwards compat we consider signed/unsigned the same.
  6043. case AR_BASIC_LITERAL_INT:
  6044. case AR_BASIC_UINT16:
  6045. return false;
  6046. default:
  6047. break; // No other valid cast types
  6048. }
  6049. break;
  6050. case AR_BASIC_INT32:
  6051. switch (rightKind) {
  6052. // For backwards compat we consider signed/unsigned the same.
  6053. case AR_BASIC_LITERAL_INT:
  6054. case AR_BASIC_UINT32:
  6055. return false;
  6056. default:
  6057. break; // No other valid cast types.
  6058. }
  6059. break;
  6060. case AR_BASIC_INT64:
  6061. switch (rightKind) {
  6062. // For backwards compat we consider signed/unsigned the same.
  6063. case AR_BASIC_LITERAL_INT:
  6064. case AR_BASIC_UINT64:
  6065. return false;
  6066. default:
  6067. break; // No other valid cast types.
  6068. }
  6069. break;
  6070. case AR_BASIC_UINT8:
  6071. switch (rightKind) {
  6072. // For backwards compat we consider signed/unsigned the same.
  6073. case AR_BASIC_LITERAL_INT:
  6074. case AR_BASIC_INT8:
  6075. return false;
  6076. default:
  6077. break; // No other valid cast types.
  6078. }
  6079. break;
  6080. case AR_BASIC_UINT16:
  6081. switch (rightKind) {
  6082. // For backwards compat we consider signed/unsigned the same.
  6083. case AR_BASIC_LITERAL_INT:
  6084. case AR_BASIC_INT16:
  6085. return false;
  6086. default:
  6087. break; // No other valid cast types.
  6088. }
  6089. break;
  6090. case AR_BASIC_UINT32:
  6091. switch (rightKind) {
  6092. // For backwards compat we consider signed/unsigned the same.
  6093. case AR_BASIC_LITERAL_INT:
  6094. case AR_BASIC_INT32:
  6095. return false;
  6096. default:
  6097. break; // No other valid cast types.
  6098. }
  6099. break;
  6100. case AR_BASIC_UINT64:
  6101. switch (rightKind) {
  6102. // For backwards compat we consider signed/unsigned the same.
  6103. case AR_BASIC_LITERAL_INT:
  6104. case AR_BASIC_INT64:
  6105. return false;
  6106. default:
  6107. break; // No other valid cast types.
  6108. }
  6109. break;
  6110. case AR_BASIC_LITERAL_FLOAT:
  6111. switch (rightKind) {
  6112. case AR_BASIC_LITERAL_FLOAT:
  6113. case AR_BASIC_FLOAT16:
  6114. case AR_BASIC_FLOAT32:
  6115. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6116. case AR_BASIC_FLOAT64:
  6117. return false;
  6118. default:
  6119. break; // No other valid cast types.
  6120. }
  6121. break;
  6122. case AR_BASIC_FLOAT16:
  6123. switch (rightKind) {
  6124. case AR_BASIC_LITERAL_FLOAT:
  6125. return false;
  6126. default:
  6127. break; // No other valid cast types.
  6128. }
  6129. break;
  6130. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6131. switch (rightKind) {
  6132. case AR_BASIC_LITERAL_FLOAT:
  6133. return false;
  6134. default:
  6135. break; // No other valid cast types.
  6136. }
  6137. break;
  6138. case AR_BASIC_FLOAT32:
  6139. switch (rightKind) {
  6140. case AR_BASIC_LITERAL_FLOAT:
  6141. return false;
  6142. default:
  6143. break; // No other valid cast types.
  6144. }
  6145. break;
  6146. case AR_BASIC_FLOAT64:
  6147. switch (rightKind) {
  6148. case AR_BASIC_LITERAL_FLOAT:
  6149. return false;
  6150. default:
  6151. break; // No other valid cast types.
  6152. }
  6153. break;
  6154. default:
  6155. break; // No other relevant targets.
  6156. }
  6157. return true;
  6158. }
  6159. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  6160. // Eliminate exact matches first, then check for casts.
  6161. if (leftKind == rightKind) {
  6162. return false;
  6163. }
  6164. //
  6165. // All minimum-bits types are only considered matches of themselves
  6166. // and thus are not in this table.
  6167. //
  6168. switch (leftKind) {
  6169. case AR_BASIC_LITERAL_INT:
  6170. switch (rightKind) {
  6171. case AR_BASIC_INT8:
  6172. case AR_BASIC_INT16:
  6173. case AR_BASIC_INT32:
  6174. case AR_BASIC_INT64:
  6175. case AR_BASIC_UINT8:
  6176. case AR_BASIC_UINT16:
  6177. case AR_BASIC_UINT32:
  6178. case AR_BASIC_UINT64:
  6179. return false;
  6180. default:
  6181. break; // No other valid conversions
  6182. }
  6183. break;
  6184. case AR_BASIC_INT8:
  6185. case AR_BASIC_INT16:
  6186. case AR_BASIC_INT32:
  6187. case AR_BASIC_INT64:
  6188. case AR_BASIC_UINT8:
  6189. case AR_BASIC_UINT16:
  6190. case AR_BASIC_UINT32:
  6191. case AR_BASIC_UINT64:
  6192. switch (rightKind) {
  6193. case AR_BASIC_LITERAL_INT:
  6194. return false;
  6195. default:
  6196. break; // No other valid conversions
  6197. }
  6198. break;
  6199. case AR_BASIC_LITERAL_FLOAT:
  6200. switch (rightKind) {
  6201. case AR_BASIC_LITERAL_FLOAT:
  6202. case AR_BASIC_FLOAT16:
  6203. case AR_BASIC_FLOAT32:
  6204. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6205. case AR_BASIC_FLOAT64:
  6206. return false;
  6207. default:
  6208. break; // No other valid conversions
  6209. }
  6210. break;
  6211. case AR_BASIC_FLOAT16:
  6212. case AR_BASIC_FLOAT32:
  6213. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6214. case AR_BASIC_FLOAT64:
  6215. switch (rightKind) {
  6216. case AR_BASIC_LITERAL_FLOAT:
  6217. return false;
  6218. default:
  6219. break; // No other valid conversions
  6220. }
  6221. break;
  6222. default:
  6223. // No other relevant targets
  6224. break;
  6225. }
  6226. return true;
  6227. }
  6228. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  6229. {
  6230. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  6231. return 0;
  6232. }
  6233. UINT64 uScore = 0;
  6234. UINT uLSize = GetNumElements(pLType);
  6235. UINT uRSize = GetNumElements(pRType);
  6236. UINT uCompareSize;
  6237. bool bLCast = false;
  6238. bool bRCast = false;
  6239. bool bLIntCast = false;
  6240. bool bRIntCast = false;
  6241. bool bLPromo = false;
  6242. bool bRPromo = false;
  6243. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  6244. if (uCompareSize > uRSize) {
  6245. uCompareSize = uRSize;
  6246. }
  6247. for (UINT i = 0; i < uCompareSize; i++) {
  6248. ArBasicKind LeftElementKind, RightElementKind;
  6249. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  6250. QualType leftSub = GetNthElementType(pLType, i);
  6251. QualType rightSub = GetNthElementType(pRType, i);
  6252. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  6253. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  6254. LeftElementKind = GetTypeElementKind(leftSub);
  6255. RightElementKind = GetTypeElementKind(rightSub);
  6256. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  6257. // information needed is the ShapeKind, EltKind and ObjKind.
  6258. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  6259. bool bCombine;
  6260. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  6261. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  6262. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  6263. ArBasicKind RightObjKind = RightElementKind;
  6264. LeftElementKind = LeftObjKind;
  6265. RightElementKind = RightObjKind;
  6266. if (leftKind != rightKind) {
  6267. bCombine = false;
  6268. }
  6269. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  6270. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  6271. }
  6272. }
  6273. else {
  6274. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  6275. }
  6276. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  6277. bLPromo = true;
  6278. }
  6279. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  6280. bLCast = true;
  6281. }
  6282. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  6283. bLIntCast = true;
  6284. }
  6285. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  6286. bRPromo = true;
  6287. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  6288. bRCast = true;
  6289. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  6290. bRIntCast = true;
  6291. }
  6292. } else {
  6293. bLCast = true;
  6294. bRCast = true;
  6295. }
  6296. }
  6297. #define SCORE_COND(shift, cond) { \
  6298. if (cond) uScore += 1ULL << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  6299. SCORE_COND(0, uRSize < uLSize);
  6300. SCORE_COND(1, bLPromo);
  6301. SCORE_COND(2, bRPromo);
  6302. SCORE_COND(3, bLIntCast);
  6303. SCORE_COND(4, bRIntCast);
  6304. SCORE_COND(5, bLCast);
  6305. SCORE_COND(6, bRCast);
  6306. SCORE_COND(7, uLSize < uRSize);
  6307. #undef SCORE_COND
  6308. // Make sure our scores fit in a UINT64.
  6309. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  6310. return uScore;
  6311. }
  6312. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  6313. DXASSERT(ics, "otherwise conversion has not been initialized");
  6314. if (!ics->isInitialized()) {
  6315. return 0;
  6316. }
  6317. if (!ics->isStandard()) {
  6318. return SCORE_MAX;
  6319. }
  6320. QualType fromType = ics->Standard.getFromType();
  6321. QualType toType = ics->Standard.getToType(2); // final type
  6322. return ScoreCast(toType, fromType);
  6323. }
  6324. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  6325. // Ignore target version mismatches.
  6326. // in/out considerations have been taken care of by viability.
  6327. // 'this' considerations don't matter without inheritance, other
  6328. // than lookup and viability.
  6329. UINT64 result = 0;
  6330. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  6331. UINT64 score;
  6332. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  6333. if (score == SCORE_MAX) {
  6334. return SCORE_MAX;
  6335. }
  6336. result += score;
  6337. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  6338. if (score == SCORE_MAX) {
  6339. return SCORE_MAX;
  6340. }
  6341. result += score;
  6342. }
  6343. return result;
  6344. }
  6345. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  6346. SourceLocation Loc,
  6347. OverloadCandidateSet& set,
  6348. OverloadCandidateSet::iterator& Best)
  6349. {
  6350. UINT64 bestScore = SCORE_MAX;
  6351. unsigned scoreMatch = 0;
  6352. Best = set.end();
  6353. if (set.size() == 1 && set.begin()->Viable) {
  6354. Best = set.begin();
  6355. return OR_Success;
  6356. }
  6357. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  6358. if (Cand->Viable) {
  6359. UINT64 score = ScoreFunction(Cand);
  6360. if (score != SCORE_MAX) {
  6361. if (score == bestScore) {
  6362. ++scoreMatch;
  6363. } else if (score < bestScore) {
  6364. Best = Cand;
  6365. scoreMatch = 1;
  6366. bestScore = score;
  6367. }
  6368. }
  6369. }
  6370. }
  6371. if (Best == set.end()) {
  6372. return OR_No_Viable_Function;
  6373. }
  6374. if (scoreMatch > 1) {
  6375. Best = set.end();
  6376. return OR_Ambiguous;
  6377. }
  6378. // No need to check for deleted functions to yield OR_Deleted.
  6379. return OR_Success;
  6380. }
  6381. /// <summary>
  6382. /// Initializes the specified <paramref name="initSequence" /> describing how
  6383. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  6384. /// </summary>
  6385. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  6386. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  6387. /// <param name="Args">Arguments to the initialization.</param>
  6388. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  6389. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  6390. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  6391. const InitializedEntity& Entity,
  6392. const InitializationKind& Kind,
  6393. MultiExprArg Args,
  6394. bool TopLevelOfInitList,
  6395. _Inout_ InitializationSequence* initSequence)
  6396. {
  6397. DXASSERT_NOMSG(initSequence != nullptr);
  6398. // In HLSL there are no default initializers, eg float4x4 m();
  6399. // Except for RayQuery constructor (also handle InitializationKind::IK_Value)
  6400. if (Kind.getKind() == InitializationKind::IK_Default ||
  6401. Kind.getKind() == InitializationKind::IK_Value) {
  6402. QualType destBaseType = m_context->getBaseElementType(Entity.getType());
  6403. ArTypeObjectKind destBaseShape = GetTypeObjectKind(destBaseType);
  6404. if (destBaseShape == AR_TOBJ_OBJECT) {
  6405. const CXXRecordDecl *typeRecordDecl = destBaseType->getAsCXXRecordDecl();
  6406. int index = FindObjectBasicKindIndex(GetRecordDeclForBuiltInOrStruct(typeRecordDecl));
  6407. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  6408. if (g_ArBasicKindsAsTypes[index] == AR_OBJECT_RAY_QUERY) {
  6409. CXXConstructorDecl *Constructor = *typeRecordDecl->ctor_begin();
  6410. initSequence->AddConstructorInitializationStep(
  6411. Constructor, AccessSpecifier::AS_public, destBaseType, false, false, false);
  6412. return;
  6413. }
  6414. }
  6415. // Value initializers occur for temporaries with empty parens or braces.
  6416. if (Kind.getKind() == InitializationKind::IK_Value) {
  6417. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  6418. SilenceSequenceDiagnostics(initSequence);
  6419. }
  6420. return;
  6421. }
  6422. // If we have a DirectList, we should have a single InitListExprClass argument.
  6423. DXASSERT(
  6424. Kind.getKind() != InitializationKind::IK_DirectList ||
  6425. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  6426. "otherwise caller is passing in incorrect initialization configuration");
  6427. bool isCast = Kind.isCStyleCast();
  6428. QualType destType = Entity.getType();
  6429. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  6430. // Direct initialization occurs for explicit constructor arguments.
  6431. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  6432. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  6433. !Kind.isCStyleOrFunctionalCast()) {
  6434. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  6435. SilenceSequenceDiagnostics(initSequence);
  6436. return;
  6437. }
  6438. bool flatten =
  6439. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  6440. Kind.getKind() == InitializationKind::IK_DirectList ||
  6441. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  6442. if (flatten) {
  6443. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  6444. // array types to adjust the value - we do calculate this as part of type analysis.
  6445. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  6446. FlattenedTypeIterator::ComparisonResult comparisonResult =
  6447. FlattenedTypeIterator::CompareTypesForInit(
  6448. *this, destType, Args,
  6449. Kind.getLocation(), Kind.getLocation());
  6450. if (comparisonResult.IsConvertibleAndEqualLength() ||
  6451. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  6452. {
  6453. initSequence->AddListInitializationStep(destType);
  6454. }
  6455. else
  6456. {
  6457. SourceLocation diagLocation;
  6458. if (Args.size() > 0)
  6459. {
  6460. diagLocation = Args.front()->getLocStart();
  6461. }
  6462. else
  6463. {
  6464. diagLocation = Entity.getDiagLoc();
  6465. }
  6466. if (comparisonResult.IsEqualLength()) {
  6467. m_sema->Diag(diagLocation, diag::err_hlsl_type_mismatch);
  6468. }
  6469. else {
  6470. m_sema->Diag(diagLocation,
  6471. diag::err_incorrect_num_initializers)
  6472. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  6473. << IsSubobjectType(destType)
  6474. << comparisonResult.LeftCount << comparisonResult.RightCount;
  6475. }
  6476. SilenceSequenceDiagnostics(initSequence);
  6477. }
  6478. }
  6479. else {
  6480. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  6481. Expr* firstArg = Args.front();
  6482. if (IsExpressionBinaryComma(firstArg)) {
  6483. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  6484. }
  6485. ExprResult expr = ExprResult(firstArg);
  6486. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  6487. Sema::CheckedConversionKind::CCK_CStyleCast :
  6488. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  6489. unsigned int msg = 0;
  6490. CastKind castKind;
  6491. CXXCastPath basePath;
  6492. SourceRange range = Kind.getRange();
  6493. ImplicitConversionSequence ics;
  6494. ics.setStandard();
  6495. bool castWorked = TryStaticCastForHLSL(
  6496. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  6497. if (castWorked) {
  6498. if (destType.getCanonicalType() ==
  6499. firstArg->getType().getCanonicalType() &&
  6500. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  6501. initSequence->AddCAssignmentStep(destType);
  6502. } else {
  6503. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  6504. }
  6505. }
  6506. else {
  6507. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  6508. }
  6509. }
  6510. }
  6511. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6512. const QualType& sourceType,
  6513. const QualType& targetType,
  6514. bool explicitConversion)
  6515. {
  6516. DXASSERT_NOMSG(!sourceType.isNull());
  6517. DXASSERT_NOMSG(!targetType.isNull());
  6518. ArTypeInfo sourceTypeInfo;
  6519. ArTypeInfo targetTypeInfo;
  6520. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  6521. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  6522. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  6523. {
  6524. return false;
  6525. }
  6526. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  6527. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  6528. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  6529. !isVecMatTrunc)
  6530. {
  6531. return false;
  6532. }
  6533. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  6534. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  6535. return true;
  6536. }
  6537. // Same struct is eqaul.
  6538. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  6539. sourceType.getCanonicalType().getUnqualifiedType() ==
  6540. targetType.getCanonicalType().getUnqualifiedType()) {
  6541. return true;
  6542. }
  6543. // DerivedFrom is less.
  6544. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  6545. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  6546. const RecordType *targetRT = targetType->getAsStructureType();
  6547. if (!targetRT)
  6548. targetRT = dyn_cast<RecordType>(targetType);
  6549. const RecordType *sourceRT = sourceType->getAsStructureType();
  6550. if (!sourceRT)
  6551. sourceRT = dyn_cast<RecordType>(sourceType);
  6552. if (targetRT && sourceRT) {
  6553. RecordDecl *targetRD = targetRT->getDecl();
  6554. RecordDecl *sourceRD = sourceRT->getDecl();
  6555. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6556. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6557. if (targetCXXRD && sourceCXXRD) {
  6558. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  6559. return true;
  6560. }
  6561. }
  6562. }
  6563. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  6564. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  6565. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  6566. {
  6567. return false;
  6568. }
  6569. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  6570. }
  6571. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6572. const ExprResult& sourceExpr,
  6573. const QualType& targetType,
  6574. bool explicitConversion)
  6575. {
  6576. if (sourceExpr.isInvalid() || targetType.isNull())
  6577. {
  6578. return false;
  6579. }
  6580. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  6581. }
  6582. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  6583. {
  6584. DXASSERT_NOMSG(!type.isNull());
  6585. DXASSERT_NOMSG(count != nullptr);
  6586. *count = 0;
  6587. UINT subCount = 0;
  6588. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  6589. switch (shapeKind)
  6590. {
  6591. case AR_TOBJ_ARRAY:
  6592. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  6593. {
  6594. *count = subCount * GetArraySize(type);
  6595. return true;
  6596. }
  6597. return false;
  6598. case AR_TOBJ_COMPOUND:
  6599. {
  6600. UINT maxCount = 0;
  6601. { // Determine maximum count to prevent infinite loop on incomplete array
  6602. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  6603. maxCount = itCount.countRemaining();
  6604. if (!maxCount) {
  6605. return false; // empty struct.
  6606. }
  6607. }
  6608. FlattenedTypeIterator it(SourceLocation(), type, *this);
  6609. while (it.hasCurrentElement()) {
  6610. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  6611. if (!isFieldNumeric) {
  6612. return false;
  6613. }
  6614. if (*count >= maxCount) {
  6615. // this element is an incomplete array at the end; iterator will not advance past this element.
  6616. // don't add to *count either, so *count will represent minimum size of the structure.
  6617. break;
  6618. }
  6619. *count += (subCount * it.getCurrentElementSize());
  6620. it.advanceCurrentElement(it.getCurrentElementSize());
  6621. }
  6622. return true;
  6623. }
  6624. default:
  6625. DXASSERT(false, "unreachable");
  6626. case AR_TOBJ_BASIC:
  6627. case AR_TOBJ_MATRIX:
  6628. case AR_TOBJ_VECTOR:
  6629. *count = GetElementCount(type);
  6630. return IsBasicKindNumeric(GetTypeElementKind(type));
  6631. case AR_TOBJ_OBJECT:
  6632. case AR_TOBJ_STRING:
  6633. return false;
  6634. }
  6635. }
  6636. enum MatrixMemberAccessError {
  6637. MatrixMemberAccessError_None, // No errors found.
  6638. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  6639. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  6640. MatrixMemberAccessError_Empty, // No members specified.
  6641. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  6642. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  6643. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6644. };
  6645. static
  6646. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  6647. {
  6648. DXASSERT_NOMSG(memberText != nullptr);
  6649. DXASSERT_NOMSG(value != nullptr);
  6650. if ('0' <= *memberText && *memberText <= '9')
  6651. {
  6652. *value = (*memberText) - '0';
  6653. }
  6654. else
  6655. {
  6656. return MatrixMemberAccessError_BadFormat;
  6657. }
  6658. memberText++;
  6659. return MatrixMemberAccessError_None;
  6660. }
  6661. static
  6662. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  6663. {
  6664. DXASSERT_NOMSG(memberText != nullptr);
  6665. DXASSERT_NOMSG(value != nullptr);
  6666. MatrixMemberAccessPositions result;
  6667. bool zeroBasedDecided = false;
  6668. bool zeroBased = false;
  6669. // Set the output value to invalid to allow early exits when errors are found.
  6670. value->IsValid = 0;
  6671. // Assume this is true until proven otherwise.
  6672. result.IsValid = 1;
  6673. result.Count = 0;
  6674. while (*memberText)
  6675. {
  6676. // Check for a leading underscore.
  6677. if (*memberText != '_')
  6678. {
  6679. return MatrixMemberAccessError_BadFormat;
  6680. }
  6681. ++memberText;
  6682. // Check whether we have an 'm' or a digit.
  6683. if (*memberText == 'm')
  6684. {
  6685. if (zeroBasedDecided && !zeroBased)
  6686. {
  6687. return MatrixMemberAccessError_MixingRefs;
  6688. }
  6689. zeroBased = true;
  6690. zeroBasedDecided = true;
  6691. ++memberText;
  6692. }
  6693. else if (!('0' <= *memberText && *memberText <= '9'))
  6694. {
  6695. return MatrixMemberAccessError_BadFormat;
  6696. }
  6697. else
  6698. {
  6699. if (zeroBasedDecided && zeroBased)
  6700. {
  6701. return MatrixMemberAccessError_MixingRefs;
  6702. }
  6703. zeroBased = false;
  6704. zeroBasedDecided = true;
  6705. }
  6706. // Consume two digits for the position.
  6707. uint32_t rowPosition;
  6708. uint32_t colPosition;
  6709. MatrixMemberAccessError digitError;
  6710. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  6711. {
  6712. return digitError;
  6713. }
  6714. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  6715. {
  6716. return digitError;
  6717. }
  6718. // Look for specific common errors (developer likely mixed up reference style).
  6719. if (zeroBased)
  6720. {
  6721. if (rowPosition == 4 || colPosition == 4)
  6722. {
  6723. return MatrixMemberAccessError_FourInZeroBased;
  6724. }
  6725. }
  6726. else
  6727. {
  6728. if (rowPosition == 0 || colPosition == 0)
  6729. {
  6730. return MatrixMemberAccessError_ZeroInOneBased;
  6731. }
  6732. // SetPosition will use zero-based indices.
  6733. --rowPosition;
  6734. --colPosition;
  6735. }
  6736. if (result.Count == 4)
  6737. {
  6738. return MatrixMemberAccessError_TooManyPositions;
  6739. }
  6740. result.SetPosition(result.Count, rowPosition, colPosition);
  6741. result.Count++;
  6742. }
  6743. if (result.Count == 0)
  6744. {
  6745. return MatrixMemberAccessError_Empty;
  6746. }
  6747. *value = result;
  6748. return MatrixMemberAccessError_None;
  6749. }
  6750. ExprResult HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  6751. Expr& BaseExpr,
  6752. DeclarationName MemberName,
  6753. bool IsArrow,
  6754. SourceLocation OpLoc,
  6755. SourceLocation MemberLoc)
  6756. {
  6757. QualType BaseType = BaseExpr.getType();
  6758. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6759. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_MATRIX, "Should only be called on known matrix types");
  6760. QualType elementType;
  6761. UINT rowCount, colCount;
  6762. GetRowsAndCols(BaseType, rowCount, colCount);
  6763. elementType = GetMatrixOrVectorElementType(BaseType);
  6764. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6765. const char *memberText = member->getNameStart();
  6766. MatrixMemberAccessPositions positions;
  6767. MatrixMemberAccessError memberAccessError;
  6768. unsigned msg = 0;
  6769. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  6770. switch (memberAccessError)
  6771. {
  6772. case MatrixMemberAccessError_BadFormat:
  6773. msg = diag::err_hlsl_matrix_member_bad_format;
  6774. break;
  6775. case MatrixMemberAccessError_Empty:
  6776. msg = diag::err_hlsl_matrix_member_empty;
  6777. break;
  6778. case MatrixMemberAccessError_FourInZeroBased:
  6779. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  6780. break;
  6781. case MatrixMemberAccessError_MixingRefs:
  6782. msg = diag::err_hlsl_matrix_member_mixing_refs;
  6783. break;
  6784. case MatrixMemberAccessError_None:
  6785. msg = 0;
  6786. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6787. // Check the position with the type now.
  6788. for (unsigned int i = 0; i < positions.Count; i++)
  6789. {
  6790. uint32_t rowPos, colPos;
  6791. positions.GetPosition(i, &rowPos, &colPos);
  6792. if (rowPos >= rowCount || colPos >= colCount)
  6793. {
  6794. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  6795. break;
  6796. }
  6797. }
  6798. break;
  6799. case MatrixMemberAccessError_TooManyPositions:
  6800. msg = diag::err_hlsl_matrix_member_too_many_positions;
  6801. break;
  6802. case MatrixMemberAccessError_ZeroInOneBased:
  6803. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  6804. break;
  6805. default:
  6806. llvm_unreachable("Unknown MatrixMemberAccessError value");
  6807. }
  6808. if (msg != 0)
  6809. {
  6810. m_sema->Diag(MemberLoc, msg) << memberText;
  6811. // It's possible that it's a simple out-of-bounds condition. In this case,
  6812. // generate the member access expression with the correct arity and continue
  6813. // processing.
  6814. if (!positions.IsValid)
  6815. {
  6816. return ExprError();
  6817. }
  6818. }
  6819. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6820. // Consume elements
  6821. QualType resultType;
  6822. if (positions.Count == 1)
  6823. resultType = elementType;
  6824. else
  6825. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6826. // Add qualifiers from BaseType.
  6827. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6828. ExprValueKind VK =
  6829. positions.ContainsDuplicateElements() ? VK_RValue :
  6830. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6831. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6832. return matrixExpr;
  6833. }
  6834. enum VectorMemberAccessError {
  6835. VectorMemberAccessError_None, // No errors found.
  6836. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  6837. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  6838. VectorMemberAccessError_Empty, // No members specified.
  6839. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6840. };
  6841. static
  6842. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  6843. DXASSERT_NOMSG(memberText != nullptr);
  6844. DXASSERT_NOMSG(value != nullptr);
  6845. rgbaStyle = false;
  6846. switch (*memberText) {
  6847. case 'r':
  6848. rgbaStyle = true;
  6849. case 'x':
  6850. *value = 0;
  6851. break;
  6852. case 'g':
  6853. rgbaStyle = true;
  6854. case 'y':
  6855. *value = 1;
  6856. break;
  6857. case 'b':
  6858. rgbaStyle = true;
  6859. case 'z':
  6860. *value = 2;
  6861. break;
  6862. case 'a':
  6863. rgbaStyle = true;
  6864. case 'w':
  6865. *value = 3;
  6866. break;
  6867. default:
  6868. return VectorMemberAccessError_BadFormat;
  6869. }
  6870. memberText++;
  6871. return VectorMemberAccessError_None;
  6872. }
  6873. static
  6874. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  6875. DXASSERT_NOMSG(memberText != nullptr);
  6876. DXASSERT_NOMSG(value != nullptr);
  6877. VectorMemberAccessPositions result;
  6878. bool rgbaStyleDecided = false;
  6879. bool rgbaStyle = false;
  6880. // Set the output value to invalid to allow early exits when errors are found.
  6881. value->IsValid = 0;
  6882. // Assume this is true until proven otherwise.
  6883. result.IsValid = 1;
  6884. result.Count = 0;
  6885. while (*memberText) {
  6886. // Consume one character for the swizzle.
  6887. uint32_t colPosition;
  6888. VectorMemberAccessError digitError;
  6889. bool rgbaStyleTmp = false;
  6890. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6891. return digitError;
  6892. }
  6893. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6894. return VectorMemberAccessError_MixingStyles;
  6895. }
  6896. else {
  6897. rgbaStyleDecided = true;
  6898. rgbaStyle = rgbaStyleTmp;
  6899. }
  6900. if (result.Count == 4) {
  6901. return VectorMemberAccessError_TooManyPositions;
  6902. }
  6903. result.SetPosition(result.Count, colPosition);
  6904. result.Count++;
  6905. }
  6906. if (result.Count == 0) {
  6907. return VectorMemberAccessError_Empty;
  6908. }
  6909. *value = result;
  6910. return VectorMemberAccessError_None;
  6911. }
  6912. bool IsExprAccessingOutIndicesArray(Expr* BaseExpr) {
  6913. switch(BaseExpr->getStmtClass()) {
  6914. case Stmt::ArraySubscriptExprClass: {
  6915. ArraySubscriptExpr* ase = cast<ArraySubscriptExpr>(BaseExpr);
  6916. return IsExprAccessingOutIndicesArray(ase->getBase());
  6917. }
  6918. case Stmt::ImplicitCastExprClass: {
  6919. ImplicitCastExpr* ice = cast<ImplicitCastExpr>(BaseExpr);
  6920. return IsExprAccessingOutIndicesArray(ice->getSubExpr());
  6921. }
  6922. case Stmt::DeclRefExprClass: {
  6923. DeclRefExpr* dre = cast<DeclRefExpr>(BaseExpr);
  6924. ValueDecl* vd = dre->getDecl();
  6925. if (vd->getAttr<HLSLIndicesAttr>() && vd->getAttr<HLSLOutAttr>()) {
  6926. return true;
  6927. }
  6928. return false;
  6929. }
  6930. default:
  6931. return false;
  6932. }
  6933. }
  6934. ExprResult HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6935. Expr& BaseExpr,
  6936. DeclarationName MemberName,
  6937. bool IsArrow,
  6938. SourceLocation OpLoc,
  6939. SourceLocation MemberLoc) {
  6940. QualType BaseType = BaseExpr.getType();
  6941. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6942. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_VECTOR, "Should only be called on known vector types");
  6943. QualType elementType;
  6944. UINT colCount = GetHLSLVecSize(BaseType);
  6945. elementType = GetMatrixOrVectorElementType(BaseType);
  6946. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6947. const char *memberText = member->getNameStart();
  6948. VectorMemberAccessPositions positions;
  6949. VectorMemberAccessError memberAccessError;
  6950. unsigned msg = 0;
  6951. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6952. switch (memberAccessError) {
  6953. case VectorMemberAccessError_BadFormat:
  6954. msg = diag::err_hlsl_vector_member_bad_format;
  6955. break;
  6956. case VectorMemberAccessError_Empty:
  6957. msg = diag::err_hlsl_vector_member_empty;
  6958. break;
  6959. case VectorMemberAccessError_MixingStyles:
  6960. msg = diag::err_ext_vector_component_name_mixedsets;
  6961. break;
  6962. case VectorMemberAccessError_None:
  6963. msg = 0;
  6964. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6965. // Check the position with the type now.
  6966. for (unsigned int i = 0; i < positions.Count; i++) {
  6967. uint32_t colPos;
  6968. positions.GetPosition(i, &colPos);
  6969. if (colPos >= colCount) {
  6970. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6971. break;
  6972. }
  6973. }
  6974. break;
  6975. case VectorMemberAccessError_TooManyPositions:
  6976. msg = diag::err_hlsl_vector_member_too_many_positions;
  6977. break;
  6978. default:
  6979. llvm_unreachable("Unknown VectorMemberAccessError value");
  6980. }
  6981. if (msg != 0) {
  6982. m_sema->Diag(MemberLoc, msg) << memberText;
  6983. // It's possible that it's a simple out-of-bounds condition. In this case,
  6984. // generate the member access expression with the correct arity and continue
  6985. // processing.
  6986. if (!positions.IsValid) {
  6987. return ExprError();
  6988. }
  6989. }
  6990. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6991. // Disallow component access for out indices for DXIL path. We still allow
  6992. // this in SPIR-V path.
  6993. if (!m_sema->getLangOpts().SPIRV &&
  6994. IsExprAccessingOutIndicesArray(&BaseExpr) && positions.Count < colCount) {
  6995. m_sema->Diag(MemberLoc, diag::err_hlsl_out_indices_array_incorrect_access);
  6996. return ExprError();
  6997. }
  6998. // Consume elements
  6999. QualType resultType;
  7000. if (positions.Count == 1)
  7001. resultType = elementType;
  7002. else
  7003. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  7004. // Add qualifiers from BaseType.
  7005. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  7006. ExprValueKind VK =
  7007. positions.ContainsDuplicateElements() ? VK_RValue :
  7008. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  7009. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  7010. return vectorExpr;
  7011. }
  7012. ExprResult HLSLExternalSource::LookupArrayMemberExprForHLSL(
  7013. Expr& BaseExpr,
  7014. DeclarationName MemberName,
  7015. bool IsArrow,
  7016. SourceLocation OpLoc,
  7017. SourceLocation MemberLoc) {
  7018. QualType BaseType = BaseExpr.getType();
  7019. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  7020. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_ARRAY, "Should only be called on known array types");
  7021. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  7022. const char *memberText = member->getNameStart();
  7023. // The only property available on arrays is Length; it is deprecated and available only on HLSL version <=2018
  7024. if (member->getLength() == 6 && 0 == strcmp(memberText, "Length")) {
  7025. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(BaseType)) {
  7026. // check version support
  7027. unsigned hlslVer = getSema()->getLangOpts().HLSLVersion;
  7028. if (hlslVer > 2016) {
  7029. m_sema->Diag(MemberLoc, diag::err_hlsl_unsupported_for_version_lower) << "Length" << "2016";
  7030. return ExprError();
  7031. }
  7032. if (hlslVer == 2016) {
  7033. m_sema->Diag(MemberLoc, diag::warn_deprecated) << "Length";
  7034. }
  7035. UnaryExprOrTypeTraitExpr *arrayLenExpr = new (m_context) UnaryExprOrTypeTraitExpr(
  7036. UETT_ArrayLength, &BaseExpr, m_context->getSizeType(), MemberLoc, BaseExpr.getSourceRange().getEnd());
  7037. return arrayLenExpr;
  7038. }
  7039. }
  7040. m_sema->Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
  7041. << BaseType << BaseExpr.getSourceRange() << MemberLoc;
  7042. return ExprError();
  7043. }
  7044. ExprResult HLSLExternalSource::MaybeConvertMemberAccess(_In_ clang::Expr* E) {
  7045. DXASSERT_NOMSG(E != nullptr);
  7046. if (IsHLSLBufferViewType(E->getType())) {
  7047. QualType targetType =
  7048. m_context->getConstType(hlsl::GetHLSLResourceResultType(E->getType()));
  7049. return ImplicitCastExpr::Create(*m_context, targetType,
  7050. CastKind::CK_FlatConversion, E, nullptr,
  7051. E->getValueKind());
  7052. }
  7053. ArBasicKind basic = GetTypeElementKind(E->getType());
  7054. if (!IS_BASIC_PRIMITIVE(basic)) {
  7055. return E;
  7056. }
  7057. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  7058. if (kind != AR_TOBJ_SCALAR) {
  7059. return E;
  7060. }
  7061. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  7062. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  7063. }
  7064. static clang::CastKind ImplicitConversionKindToCastKind(
  7065. clang::ImplicitConversionKind ICK,
  7066. ArBasicKind FromKind,
  7067. ArBasicKind ToKind) {
  7068. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  7069. // based on from/to kinds in order to determine CastKind?
  7070. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  7071. // problem.
  7072. switch (ICK) {
  7073. case ICK_Integral_Promotion:
  7074. case ICK_Integral_Conversion:
  7075. return CK_IntegralCast;
  7076. case ICK_Floating_Promotion:
  7077. case ICK_Floating_Conversion:
  7078. return CK_FloatingCast;
  7079. case ICK_Floating_Integral:
  7080. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  7081. return CK_FloatingToIntegral;
  7082. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  7083. return CK_IntegralToFloating;
  7084. break;
  7085. case ICK_Boolean_Conversion:
  7086. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  7087. return CK_FloatingToBoolean;
  7088. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  7089. return CK_IntegralToBoolean;
  7090. break;
  7091. default:
  7092. // Only covers implicit conversions with cast kind equivalents.
  7093. return CK_Invalid;
  7094. }
  7095. return CK_Invalid;
  7096. }
  7097. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  7098. switch (CK) {
  7099. case CK_IntegralCast:
  7100. return CK_HLSLCC_IntegralCast;
  7101. case CK_FloatingCast:
  7102. return CK_HLSLCC_FloatingCast;
  7103. case CK_FloatingToIntegral:
  7104. return CK_HLSLCC_FloatingToIntegral;
  7105. case CK_IntegralToFloating:
  7106. return CK_HLSLCC_IntegralToFloating;
  7107. case CK_FloatingToBoolean:
  7108. return CK_HLSLCC_FloatingToBoolean;
  7109. case CK_IntegralToBoolean:
  7110. return CK_HLSLCC_IntegralToBoolean;
  7111. default:
  7112. // Only HLSLCC castkinds are relevant. Ignore the rest.
  7113. return CK_Invalid;
  7114. }
  7115. return CK_Invalid;
  7116. }
  7117. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  7118. _In_ clang::Sema* self,
  7119. _In_ clang::Expr* From,
  7120. ArTypeObjectKind FromShape,
  7121. ArBasicKind EltKind)
  7122. {
  7123. clang::CastKind CK = CK_Invalid;
  7124. if (AR_TOBJ_MATRIX == FromShape)
  7125. CK = CK_HLSLMatrixToScalarCast;
  7126. if (AR_TOBJ_VECTOR == FromShape)
  7127. CK = CK_HLSLVectorToScalarCast;
  7128. if (CK_Invalid != CK) {
  7129. return self->ImpCastExprToType(From,
  7130. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  7131. }
  7132. return From;
  7133. }
  7134. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  7135. _In_ clang::Expr* From,
  7136. _In_ clang::QualType targetType,
  7137. _In_ const clang::StandardConversionSequence &SCS,
  7138. _In_ clang::Sema::CheckedConversionKind CCK)
  7139. {
  7140. QualType sourceType = From->getType();
  7141. sourceType = GetStructuralForm(sourceType);
  7142. targetType = GetStructuralForm(targetType);
  7143. ArTypeInfo SourceInfo, TargetInfo;
  7144. CollectInfo(sourceType, &SourceInfo);
  7145. CollectInfo(targetType, &TargetInfo);
  7146. clang::CastKind CK = CK_Invalid;
  7147. QualType intermediateTarget;
  7148. // TODO: construct vector/matrix and component cast expressions
  7149. switch (SCS.Second) {
  7150. case ICK_Flat_Conversion: {
  7151. // TODO: determine how to handle individual component conversions:
  7152. // - have an array of conversions for ComponentConversion in SCS?
  7153. // convert that to an array of casts under a special kind of flat
  7154. // flat conversion node? What do component conversion casts cast
  7155. // from? We don't have a From expression for individiual components.
  7156. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7157. break;
  7158. }
  7159. case ICK_HLSL_Derived_To_Base: {
  7160. CXXCastPath BasePath;
  7161. if (m_sema->CheckDerivedToBaseConversion(
  7162. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  7163. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  7164. return ExprError();
  7165. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  7166. break;
  7167. }
  7168. case ICK_HLSLVector_Splat: {
  7169. // 1. optionally convert from vec1 or mat1x1 to scalar
  7170. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  7171. // 2. optionally convert component type
  7172. if (ICK_Identity != SCS.ComponentConversion) {
  7173. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  7174. if (CK_Invalid != CK) {
  7175. From = m_sema->ImpCastExprToType(From,
  7176. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7177. }
  7178. }
  7179. // 3. splat scalar to final vector or matrix
  7180. CK = CK_Invalid;
  7181. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  7182. CK = CK_HLSLVectorSplat;
  7183. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  7184. CK = CK_HLSLMatrixSplat;
  7185. if (CK_Invalid != CK) {
  7186. From = m_sema->ImpCastExprToType(From,
  7187. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7188. }
  7189. break;
  7190. }
  7191. case ICK_HLSLVector_Scalar: {
  7192. // 1. select vector or matrix component
  7193. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  7194. // 2. optionally convert component type
  7195. if (ICK_Identity != SCS.ComponentConversion) {
  7196. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  7197. if (CK_Invalid != CK) {
  7198. From = m_sema->ImpCastExprToType(From,
  7199. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7200. }
  7201. }
  7202. break;
  7203. }
  7204. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  7205. // can be done with case fall-through, since this is the order in which we want to
  7206. // do the conversion operations.
  7207. case ICK_HLSLVector_Truncation: {
  7208. // 1. dimension truncation
  7209. // vector truncation or matrix truncation?
  7210. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  7211. From = m_sema->ImpCastExprToType(From,
  7212. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  7213. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7214. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  7215. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  7216. // Handle the column to vector case
  7217. From = m_sema->ImpCastExprToType(From,
  7218. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  7219. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7220. } else {
  7221. From = m_sema->ImpCastExprToType(From,
  7222. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  7223. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7224. }
  7225. } else {
  7226. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  7227. }
  7228. }
  7229. __fallthrough;
  7230. case ICK_HLSLVector_Conversion: {
  7231. // 2. Do ShapeKind conversion if necessary
  7232. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  7233. switch (TargetInfo.ShapeKind) {
  7234. case AR_TOBJ_VECTOR:
  7235. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  7236. From = m_sema->ImpCastExprToType(From,
  7237. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  7238. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7239. break;
  7240. case AR_TOBJ_MATRIX:
  7241. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  7242. From = m_sema->ImpCastExprToType(From,
  7243. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  7244. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7245. break;
  7246. case AR_TOBJ_BASIC:
  7247. // Truncation may be followed by cast to scalar
  7248. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  7249. break;
  7250. default:
  7251. DXASSERT(false, "otherwise, invalid casting sequence");
  7252. break;
  7253. }
  7254. }
  7255. // 3. Do component type conversion
  7256. if (ICK_Identity != SCS.ComponentConversion) {
  7257. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  7258. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  7259. CK = ConvertToComponentCastKind(CK);
  7260. if (CK_Invalid != CK) {
  7261. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7262. }
  7263. }
  7264. break;
  7265. }
  7266. case ICK_Identity:
  7267. // Nothing to do.
  7268. break;
  7269. default:
  7270. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  7271. }
  7272. return From;
  7273. }
  7274. void HLSLExternalSource::GetConversionForm(
  7275. QualType type,
  7276. bool explicitConversion,
  7277. ArTypeInfo* pTypeInfo)
  7278. {
  7279. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  7280. CollectInfo(type, pTypeInfo);
  7281. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  7282. // but that value is only used for pointer conversions.
  7283. // When explicitly converting types complex aggregates can be treated
  7284. // as vectors if they are entirely numeric.
  7285. switch (pTypeInfo->ShapeKind)
  7286. {
  7287. case AR_TOBJ_COMPOUND:
  7288. case AR_TOBJ_ARRAY:
  7289. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  7290. {
  7291. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  7292. }
  7293. else
  7294. {
  7295. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  7296. }
  7297. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  7298. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  7299. break;
  7300. case AR_TOBJ_VECTOR:
  7301. case AR_TOBJ_MATRIX:
  7302. // Convert 1x1 types to scalars.
  7303. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  7304. {
  7305. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  7306. }
  7307. break;
  7308. default:
  7309. // Only convertable shapekinds are relevant.
  7310. break;
  7311. }
  7312. }
  7313. static
  7314. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  7315. {
  7316. DXASSERT_NOMSG(allowed != nullptr);
  7317. bool applicable = true;
  7318. *allowed = true;
  7319. if (explicitConversion) {
  7320. // (void) non-void
  7321. if (target->isVoidType()) {
  7322. DXASSERT_NOMSG(*allowed);
  7323. }
  7324. // (non-void) void
  7325. else if (source->isVoidType()) {
  7326. *allowed = false;
  7327. }
  7328. else {
  7329. applicable = false;
  7330. }
  7331. }
  7332. else {
  7333. // (void) void
  7334. if (source->isVoidType() && target->isVoidType()) {
  7335. DXASSERT_NOMSG(*allowed);
  7336. }
  7337. // (void) non-void, (non-void) void
  7338. else if (source->isVoidType() || target->isVoidType()) {
  7339. *allowed = false;
  7340. }
  7341. else {
  7342. applicable = false;
  7343. }
  7344. }
  7345. return applicable;
  7346. }
  7347. static bool ConvertDimensions(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7348. ImplicitConversionKind &Second,
  7349. TYPE_CONVERSION_REMARKS &Remarks) {
  7350. // The rules for aggregate conversions are:
  7351. // 1. A scalar can be replicated to any layout.
  7352. // 2. Any type may be truncated to anything else with one component.
  7353. // 3. A vector may be truncated to a smaller vector.
  7354. // 4. A matrix may be truncated to a smaller matrix.
  7355. // 5. The result of a vector and a matrix is:
  7356. // a. If the matrix has one row it's a vector-sized
  7357. // piece of the row.
  7358. // b. If the matrix has one column it's a vector-sized
  7359. // piece of the column.
  7360. // c. Otherwise the number of elements in the vector
  7361. // and matrix must match and the result is the vector.
  7362. // 6. The result of a matrix and a vector is similar to #5.
  7363. switch (TargetInfo.ShapeKind) {
  7364. case AR_TOBJ_BASIC:
  7365. switch (SourceInfo.ShapeKind)
  7366. {
  7367. case AR_TOBJ_BASIC:
  7368. Second = ICK_Identity;
  7369. break;
  7370. case AR_TOBJ_VECTOR:
  7371. if (1 < SourceInfo.uCols)
  7372. Second = ICK_HLSLVector_Truncation;
  7373. else
  7374. Second = ICK_HLSLVector_Scalar;
  7375. break;
  7376. case AR_TOBJ_MATRIX:
  7377. if (1 < SourceInfo.uRows * SourceInfo.uCols)
  7378. Second = ICK_HLSLVector_Truncation;
  7379. else
  7380. Second = ICK_HLSLVector_Scalar;
  7381. break;
  7382. default:
  7383. return false;
  7384. }
  7385. break;
  7386. case AR_TOBJ_VECTOR:
  7387. switch (SourceInfo.ShapeKind)
  7388. {
  7389. case AR_TOBJ_BASIC:
  7390. // Conversions between scalars and aggregates are always supported.
  7391. Second = ICK_HLSLVector_Splat;
  7392. break;
  7393. case AR_TOBJ_VECTOR:
  7394. if (TargetInfo.uCols > SourceInfo.uCols) {
  7395. if (SourceInfo.uCols == 1) {
  7396. Second = ICK_HLSLVector_Splat;
  7397. }
  7398. else {
  7399. return false;
  7400. }
  7401. }
  7402. else if (TargetInfo.uCols < SourceInfo.uCols) {
  7403. Second = ICK_HLSLVector_Truncation;
  7404. }
  7405. else {
  7406. Second = ICK_Identity;
  7407. }
  7408. break;
  7409. case AR_TOBJ_MATRIX: {
  7410. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7411. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  7412. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  7413. Second = ICK_HLSLVector_Splat;
  7414. }
  7415. else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  7416. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  7417. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  7418. return false;
  7419. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  7420. Second = ICK_HLSLVector_Truncation;
  7421. else // equalivalent: O == N*M
  7422. Second = ICK_HLSLVector_Conversion;
  7423. }
  7424. else if (TargetInfo.uCols == 1 && SourceComponents > 1) {
  7425. Second = ICK_HLSLVector_Truncation;
  7426. }
  7427. else if (TargetInfo.uCols != SourceComponents) {
  7428. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  7429. return false;
  7430. }
  7431. else {
  7432. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  7433. Second = ICK_HLSLVector_Conversion;
  7434. }
  7435. break;
  7436. }
  7437. default:
  7438. return false;
  7439. }
  7440. break;
  7441. case AR_TOBJ_MATRIX: {
  7442. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  7443. switch (SourceInfo.ShapeKind)
  7444. {
  7445. case AR_TOBJ_BASIC:
  7446. // Conversions between scalars and aggregates are always supported.
  7447. Second = ICK_HLSLVector_Splat;
  7448. break;
  7449. case AR_TOBJ_VECTOR: {
  7450. // We can only convert vector to matrix in following cases:
  7451. // - splat from vector<...,1>
  7452. // - same number of components
  7453. // - one target component (truncate to scalar)
  7454. // - matrix has one row or one column, and fewer components (truncation)
  7455. // Other cases disallowed even if implicitly convertable in two steps (truncation+conversion).
  7456. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  7457. // splat: vector<[..], 1> -> matrix<[..], M, N>
  7458. Second = ICK_HLSLVector_Splat;
  7459. }
  7460. else if (TargetComponents == SourceInfo.uCols) {
  7461. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  7462. Second = ICK_HLSLVector_Conversion;
  7463. }
  7464. else if (1 == TargetComponents) {
  7465. // truncate to scalar: matrix<[..], 1, 1>
  7466. Second = ICK_HLSLVector_Truncation;
  7467. }
  7468. else if ((1 == TargetInfo.uRows || 1 == TargetInfo.uCols) &&
  7469. TargetComponents < SourceInfo.uCols) {
  7470. Second = ICK_HLSLVector_Truncation;
  7471. }
  7472. else {
  7473. // illegal: change in components without going to or from scalar equivalent
  7474. return false;
  7475. }
  7476. break;
  7477. }
  7478. case AR_TOBJ_MATRIX: {
  7479. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7480. if (1 == SourceComponents && TargetComponents != 1) {
  7481. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  7482. Second = ICK_HLSLVector_Splat;
  7483. }
  7484. else if (TargetComponents == 1) {
  7485. Second = ICK_HLSLVector_Truncation;
  7486. }
  7487. else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  7488. return false;
  7489. }
  7490. else if (TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  7491. Second = ICK_HLSLVector_Truncation;
  7492. }
  7493. else {
  7494. Second = ICK_Identity;
  7495. }
  7496. break;
  7497. }
  7498. default:
  7499. return false;
  7500. }
  7501. break;
  7502. }
  7503. case AR_TOBJ_STRING:
  7504. if (SourceInfo.ShapeKind == AR_TOBJ_STRING) {
  7505. Second = ICK_Identity;
  7506. break;
  7507. }
  7508. else {
  7509. return false;
  7510. }
  7511. default:
  7512. return false;
  7513. }
  7514. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  7515. {
  7516. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  7517. }
  7518. return true;
  7519. }
  7520. static bool ConvertComponent(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7521. ImplicitConversionKind &ComponentConversion,
  7522. TYPE_CONVERSION_REMARKS &Remarks) {
  7523. // Conversion to/from unknown types not supported.
  7524. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  7525. SourceInfo.EltKind == AR_BASIC_UNKNOWN) {
  7526. return false;
  7527. }
  7528. bool precisionLoss = false;
  7529. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  7530. GET_BASIC_BITS(TargetInfo.EltKind) <
  7531. GET_BASIC_BITS(SourceInfo.EltKind))
  7532. {
  7533. precisionLoss = true;
  7534. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  7535. }
  7536. // enum -> enum not allowed
  7537. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  7538. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  7539. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  7540. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  7541. return false;
  7542. }
  7543. if (SourceInfo.EltKind != TargetInfo.EltKind)
  7544. {
  7545. if (IS_BASIC_BOOL(TargetInfo.EltKind))
  7546. {
  7547. ComponentConversion = ICK_Boolean_Conversion;
  7548. }
  7549. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  7550. {
  7551. // conversion to enum type not allowed
  7552. return false;
  7553. }
  7554. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  7555. {
  7556. // enum -> int/float
  7557. ComponentConversion = ICK_Integral_Conversion;
  7558. }
  7559. else if (TargetInfo.EltKind == AR_OBJECT_STRING)
  7560. {
  7561. if (SourceInfo.EltKind == AR_OBJECT_STRING_LITERAL) {
  7562. ComponentConversion = ICK_Array_To_Pointer;
  7563. }
  7564. else
  7565. {
  7566. return false;
  7567. }
  7568. }
  7569. else
  7570. {
  7571. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  7572. if (IS_BASIC_AINT(SourceInfo.EltKind))
  7573. {
  7574. if (targetIsInt)
  7575. {
  7576. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  7577. }
  7578. else
  7579. {
  7580. ComponentConversion = ICK_Floating_Integral;
  7581. }
  7582. }
  7583. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  7584. {
  7585. if (targetIsInt)
  7586. {
  7587. ComponentConversion = ICK_Floating_Integral;
  7588. }
  7589. else
  7590. {
  7591. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  7592. }
  7593. }
  7594. else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  7595. if (targetIsInt)
  7596. ComponentConversion = ICK_Integral_Conversion;
  7597. else
  7598. ComponentConversion = ICK_Floating_Integral;
  7599. }
  7600. }
  7601. }
  7602. return true;
  7603. }
  7604. _Use_decl_annotations_
  7605. bool HLSLExternalSource::CanConvert(
  7606. SourceLocation loc,
  7607. Expr* sourceExpr,
  7608. QualType target,
  7609. bool explicitConversion,
  7610. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  7611. _Inout_opt_ StandardConversionSequence* standard)
  7612. {
  7613. UINT uTSize, uSSize;
  7614. bool SourceIsAggregate, TargetIsAggregate; // Early declarations due to gotos below
  7615. DXASSERT_NOMSG(sourceExpr != nullptr);
  7616. DXASSERT_NOMSG(!target.isNull());
  7617. // Implements the semantics of ArType::CanConvertTo.
  7618. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  7619. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  7620. QualType source = sourceExpr->getType();
  7621. // Cannot cast function type.
  7622. if (source->isFunctionType())
  7623. return false;
  7624. // Convert to an r-value to begin with, with an exception for strings
  7625. // since they are not first-class values and we want to preserve them as literals.
  7626. bool needsLValueToRValue = sourceExpr->isLValue() && !target->isLValueReferenceType()
  7627. && sourceExpr->getStmtClass() != Expr::StringLiteralClass;
  7628. bool targetRef = target->isReferenceType();
  7629. // Initialize the output standard sequence if available.
  7630. if (standard != nullptr) {
  7631. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  7632. standard->setAsIdentityConversion();
  7633. if (needsLValueToRValue) {
  7634. standard->First = ICK_Lvalue_To_Rvalue;
  7635. }
  7636. standard->setFromType(source);
  7637. standard->setAllToTypes(target);
  7638. }
  7639. source = GetStructuralForm(source);
  7640. target = GetStructuralForm(target);
  7641. // Temporary conversion kind tracking which will be used/fixed up at the end
  7642. ImplicitConversionKind Second = ICK_Identity;
  7643. ImplicitConversionKind ComponentConversion = ICK_Identity;
  7644. // Identical types require no conversion.
  7645. if (source == target) {
  7646. Remarks = TYPE_CONVERSION_IDENTICAL;
  7647. goto lSuccess;
  7648. }
  7649. // Trivial cases for void.
  7650. bool allowed;
  7651. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  7652. if (allowed) {
  7653. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  7654. goto lSuccess;
  7655. }
  7656. else {
  7657. return false;
  7658. }
  7659. }
  7660. ArTypeInfo TargetInfo, SourceInfo;
  7661. CollectInfo(target, &TargetInfo);
  7662. CollectInfo(source, &SourceInfo);
  7663. uTSize = TargetInfo.uTotalElts;
  7664. uSSize = SourceInfo.uTotalElts;
  7665. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  7666. // are we missing cases?
  7667. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  7668. return false;
  7669. }
  7670. // Cast cbuffer to its result value.
  7671. if ((SourceInfo.EltKind == AR_OBJECT_CONSTANT_BUFFER ||
  7672. SourceInfo.EltKind == AR_OBJECT_TEXTURE_BUFFER) &&
  7673. TargetInfo.ShapeKind == AR_TOBJ_COMPOUND) {
  7674. if (standard)
  7675. standard->Second = ICK_Flat_Conversion;
  7676. return hlsl::GetHLSLResourceResultType(source) == target;
  7677. }
  7678. // Structure cast.
  7679. SourceIsAggregate = SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY;
  7680. TargetIsAggregate = TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY;
  7681. if (SourceIsAggregate || TargetIsAggregate) {
  7682. // For implicit conversions, FXC treats arrays the same as structures
  7683. // and rejects conversions between them and numeric types
  7684. if (!explicitConversion && SourceIsAggregate != TargetIsAggregate)
  7685. {
  7686. return false;
  7687. }
  7688. // Structure to structure cases
  7689. const RecordType *targetRT = dyn_cast<RecordType>(target);
  7690. const RecordType *sourceRT = dyn_cast<RecordType>(source);
  7691. if (targetRT && sourceRT) {
  7692. RecordDecl *targetRD = targetRT->getDecl();
  7693. RecordDecl *sourceRD = sourceRT->getDecl();
  7694. if (sourceRT && targetRT) {
  7695. if (targetRD == sourceRD) {
  7696. Second = ICK_Flat_Conversion;
  7697. goto lSuccess;
  7698. }
  7699. const CXXRecordDecl* targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  7700. const CXXRecordDecl* sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  7701. if (targetCXXRD && sourceCXXRD && sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  7702. Second = ICK_HLSL_Derived_To_Base;
  7703. goto lSuccess;
  7704. }
  7705. }
  7706. }
  7707. // Handle explicit splats from single element numerical types (scalars, vector1s and matrix1x1s) to aggregate types.
  7708. if (explicitConversion) {
  7709. const BuiltinType *sourceSingleElementBuiltinType = source->getAs<BuiltinType>();
  7710. if (sourceSingleElementBuiltinType == nullptr
  7711. && hlsl::IsHLSLVecMatType(source)
  7712. && hlsl::GetElementCount(source) == 1) {
  7713. sourceSingleElementBuiltinType = hlsl::GetElementTypeOrType(source)->getAs<BuiltinType>();
  7714. }
  7715. // We can only splat to target types that do not contain object/resource types
  7716. if (sourceSingleElementBuiltinType != nullptr && hlsl::IsHLSLNumericOrAggregateOfNumericType(target)) {
  7717. BuiltinType::Kind kind = sourceSingleElementBuiltinType->getKind();
  7718. switch (kind) {
  7719. case BuiltinType::Kind::UInt:
  7720. case BuiltinType::Kind::Int:
  7721. case BuiltinType::Kind::Float:
  7722. case BuiltinType::Kind::LitFloat:
  7723. case BuiltinType::Kind::LitInt:
  7724. Second = ICK_Flat_Conversion;
  7725. goto lSuccess;
  7726. default:
  7727. // Only flat conversion kinds are relevant.
  7728. break;
  7729. }
  7730. }
  7731. }
  7732. FlattenedTypeIterator::ComparisonResult result =
  7733. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  7734. if (!result.CanConvertElements) {
  7735. return false;
  7736. }
  7737. // Only allow scalar to compound or array with explicit cast
  7738. if (result.IsConvertibleAndLeftLonger()) {
  7739. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  7740. return false;
  7741. }
  7742. }
  7743. // Assignment is valid if elements are exactly the same in type and size; if
  7744. // an explicit conversion is being done, we accept converted elements and a
  7745. // longer right-hand sequence.
  7746. if (!explicitConversion &&
  7747. (!result.AreElementsEqual || result.IsRightLonger()))
  7748. {
  7749. return false;
  7750. }
  7751. Second = ICK_Flat_Conversion;
  7752. goto lSuccess;
  7753. }
  7754. // Cast from Resource to Object types.
  7755. if (SourceInfo.EltKind == AR_OBJECT_HEAP_RESOURCE ||
  7756. SourceInfo.EltKind == AR_OBJECT_HEAP_SAMPLER) {
  7757. // TODO: skip things like PointStream.
  7758. if (TargetInfo.ShapeKind == AR_TOBJ_OBJECT) {
  7759. Second = ICK_Flat_Conversion;
  7760. goto lSuccess;
  7761. }
  7762. }
  7763. // Convert scalar/vector/matrix dimensions
  7764. if (!ConvertDimensions(TargetInfo, SourceInfo, Second, Remarks))
  7765. return false;
  7766. // Convert component type
  7767. if (!ConvertComponent(TargetInfo, SourceInfo, ComponentConversion, Remarks))
  7768. return false;
  7769. lSuccess:
  7770. if (standard)
  7771. {
  7772. if (sourceExpr->isLValue())
  7773. {
  7774. if (needsLValueToRValue) {
  7775. // We don't need LValueToRValue cast before casting a derived object
  7776. // to its base.
  7777. if (Second == ICK_HLSL_Derived_To_Base) {
  7778. standard->First = ICK_Identity;
  7779. } else {
  7780. standard->First = ICK_Lvalue_To_Rvalue;
  7781. }
  7782. } else {
  7783. switch (Second)
  7784. {
  7785. case ICK_NoReturn_Adjustment:
  7786. case ICK_Vector_Conversion:
  7787. case ICK_Vector_Splat:
  7788. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  7789. case ICK_Flat_Conversion:
  7790. case ICK_HLSLVector_Splat:
  7791. standard->First = ICK_Lvalue_To_Rvalue;
  7792. break;
  7793. default:
  7794. // Only flat and splat conversions handled.
  7795. break;
  7796. }
  7797. switch (ComponentConversion)
  7798. {
  7799. case ICK_Integral_Promotion:
  7800. case ICK_Integral_Conversion:
  7801. case ICK_Floating_Promotion:
  7802. case ICK_Floating_Conversion:
  7803. case ICK_Floating_Integral:
  7804. case ICK_Boolean_Conversion:
  7805. standard->First = ICK_Lvalue_To_Rvalue;
  7806. break;
  7807. case ICK_Array_To_Pointer:
  7808. standard->First = ICK_Array_To_Pointer;
  7809. break;
  7810. default:
  7811. // Only potential assignments above covered.
  7812. break;
  7813. }
  7814. }
  7815. }
  7816. // Finally fix up the cases for scalar->scalar component conversion, and
  7817. // identity vector/matrix component conversion
  7818. if (ICK_Identity != ComponentConversion) {
  7819. if (Second == ICK_Identity) {
  7820. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  7821. // Scalar to scalar type conversion, use normal mechanism (Second)
  7822. Second = ComponentConversion;
  7823. ComponentConversion = ICK_Identity;
  7824. }
  7825. else if (TargetInfo.ShapeKind != AR_TOBJ_STRING) {
  7826. // vector or matrix dimensions are not being changed, but component type
  7827. // is being converted, so change Second to signal the conversion
  7828. Second = ICK_HLSLVector_Conversion;
  7829. }
  7830. }
  7831. }
  7832. standard->Second = Second;
  7833. standard->ComponentConversion = ComponentConversion;
  7834. // For conversion which change to RValue but targeting reference type
  7835. // Hold the conversion to codeGen
  7836. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  7837. standard->First = ICK_Identity;
  7838. standard->Second = ICK_Identity;
  7839. }
  7840. }
  7841. AssignOpt(Remarks, remarks);
  7842. return true;
  7843. }
  7844. bool HLSLExternalSource::ValidateTypeRequirements(
  7845. SourceLocation loc,
  7846. ArBasicKind elementKind,
  7847. ArTypeObjectKind objectKind,
  7848. bool requiresIntegrals,
  7849. bool requiresNumerics)
  7850. {
  7851. if (objectKind == AR_TOBJ_DEPENDENT)
  7852. return true;
  7853. if (elementKind == AR_BASIC_DEPENDENT)
  7854. return true;
  7855. if (requiresIntegrals || requiresNumerics)
  7856. {
  7857. if (!IsObjectKindPrimitiveAggregate(objectKind))
  7858. {
  7859. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  7860. return false;
  7861. }
  7862. }
  7863. if (requiresIntegrals)
  7864. {
  7865. if (!IsBasicKindIntegral(elementKind))
  7866. {
  7867. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  7868. return false;
  7869. }
  7870. }
  7871. else if (requiresNumerics)
  7872. {
  7873. if (!IsBasicKindNumeric(elementKind))
  7874. {
  7875. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  7876. return false;
  7877. }
  7878. }
  7879. return true;
  7880. }
  7881. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  7882. {
  7883. bool isValid = true;
  7884. if (IsBuiltInObjectType(type)) {
  7885. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  7886. isValid = false;
  7887. }
  7888. if (kind == AR_TOBJ_COMPOUND) {
  7889. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  7890. isValid = false;
  7891. }
  7892. return isValid;
  7893. }
  7894. HRESULT HLSLExternalSource::CombineDimensions(
  7895. QualType leftType, QualType rightType, QualType *resultType,
  7896. ImplicitConversionKind &convKind, TYPE_CONVERSION_REMARKS &Remarks)
  7897. {
  7898. ArTypeInfo leftInfo, rightInfo;
  7899. CollectInfo(leftType, &leftInfo);
  7900. CollectInfo(rightType, &rightInfo);
  7901. // Prefer larger, or left if same.
  7902. if (leftInfo.uTotalElts >= rightInfo.uTotalElts) {
  7903. if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7904. *resultType = leftType;
  7905. else if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7906. *resultType = rightType;
  7907. else
  7908. return E_FAIL;
  7909. } else {
  7910. if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7911. *resultType = rightType;
  7912. else if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7913. *resultType = leftType;
  7914. else
  7915. return E_FAIL;
  7916. }
  7917. return S_OK;
  7918. }
  7919. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  7920. /// <param name="OpLoc">Source location for operator.</param>
  7921. /// <param name="Opc">Kind of binary operator.</param>
  7922. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  7923. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  7924. /// <param name="ResultTy">Result type for operator expression.</param>
  7925. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  7926. /// <param name="CompResultTy">Type of computation result.</param>
  7927. void HLSLExternalSource::CheckBinOpForHLSL(
  7928. SourceLocation OpLoc,
  7929. BinaryOperatorKind Opc,
  7930. ExprResult& LHS,
  7931. ExprResult& RHS,
  7932. QualType& ResultTy,
  7933. QualType& CompLHSTy,
  7934. QualType& CompResultTy)
  7935. {
  7936. // At the start, none of the output types should be valid.
  7937. DXASSERT_NOMSG(ResultTy.isNull());
  7938. DXASSERT_NOMSG(CompLHSTy.isNull());
  7939. DXASSERT_NOMSG(CompResultTy.isNull());
  7940. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7941. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7942. // If either expression is invalid to begin with, propagate that.
  7943. if (LHS.isInvalid() || RHS.isInvalid()) {
  7944. return;
  7945. }
  7946. // If there is a dependent type we will use that as the result type
  7947. if (LHS.get()->getType()->isDependentType() || RHS.get()->getType()->isDependentType()) {
  7948. if (LHS.get()->getType()->isDependentType())
  7949. ResultTy = LHS.get()->getType();
  7950. else
  7951. ResultTy = RHS.get()->getType();
  7952. if (BinaryOperatorKindIsCompoundAssignment(Opc))
  7953. CompResultTy = ResultTy;
  7954. return;
  7955. }
  7956. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  7957. // Handle Assign and Comma operators and return
  7958. switch (Opc)
  7959. {
  7960. case BO_AddAssign:
  7961. case BO_AndAssign:
  7962. case BO_DivAssign:
  7963. case BO_MulAssign:
  7964. case BO_RemAssign:
  7965. case BO_ShlAssign:
  7966. case BO_ShrAssign:
  7967. case BO_SubAssign:
  7968. case BO_OrAssign:
  7969. case BO_XorAssign: {
  7970. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  7971. Sema & S);
  7972. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7973. return;
  7974. }
  7975. } break;
  7976. case BO_Assign: {
  7977. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7978. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7979. return;
  7980. }
  7981. bool complained = false;
  7982. ResultTy = LHS.get()->getType();
  7983. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  7984. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  7985. Sema::AssignmentAction::AA_Assigning, &complained)) {
  7986. return;
  7987. }
  7988. StandardConversionSequence standard;
  7989. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  7990. ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7991. return;
  7992. }
  7993. if (RHS.get()->isLValue()) {
  7994. standard.First = ICK_Lvalue_To_Rvalue;
  7995. }
  7996. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  7997. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  7998. return;
  7999. }
  8000. break;
  8001. case BO_Comma:
  8002. // C performs conversions, C++ doesn't but still checks for type completeness.
  8003. // There are also diagnostics for improper comma use.
  8004. // In the HLSL case these cases don't apply or simply aren't surfaced.
  8005. ResultTy = RHS.get()->getType();
  8006. return;
  8007. default:
  8008. // Only assign and comma operations handled.
  8009. break;
  8010. }
  8011. // Leave this diagnostic for last to emulate fxc behavior.
  8012. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  8013. bool unsupportedBoolLvalue = isCompoundAssignment &&
  8014. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  8015. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  8016. // Turn operand inputs into r-values.
  8017. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  8018. if (!isCompoundAssignment) {
  8019. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  8020. }
  8021. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  8022. if (LHS.isInvalid() || RHS.isInvalid()) {
  8023. return;
  8024. }
  8025. // Gather type info
  8026. QualType leftType = GetStructuralForm(LHS.get()->getType());
  8027. QualType rightType = GetStructuralForm(RHS.get()->getType());
  8028. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  8029. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  8030. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  8031. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  8032. // Validate type requirements
  8033. {
  8034. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  8035. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  8036. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  8037. return;
  8038. }
  8039. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  8040. return;
  8041. }
  8042. }
  8043. if (unsupportedBoolLvalue) {
  8044. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  8045. return;
  8046. }
  8047. // We don't support binary operators on built-in object types other than assignment or commas.
  8048. {
  8049. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  8050. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  8051. bool isValid;
  8052. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  8053. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  8054. isValid = false;
  8055. }
  8056. if (!isValid) {
  8057. return;
  8058. }
  8059. }
  8060. // We don't support equality comparisons on arrays.
  8061. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  8062. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  8063. return;
  8064. }
  8065. // Combine element types for computation.
  8066. ArBasicKind resultElementKind = leftElementKind;
  8067. {
  8068. if (BinaryOperatorKindIsLogical(Opc)) {
  8069. resultElementKind = AR_BASIC_BOOL;
  8070. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  8071. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  8072. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  8073. return;
  8074. }
  8075. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  8076. (resultElementKind == AR_BASIC_LITERAL_INT ||
  8077. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  8078. rightElementKind != AR_BASIC_LITERAL_INT &&
  8079. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  8080. // For case like 1<<x.
  8081. m_sema->Diag(OpLoc, diag::warn_hlsl_ambiguous_literal_shift);
  8082. if (rightElementKind == AR_BASIC_UINT32)
  8083. resultElementKind = AR_BASIC_UINT32;
  8084. else
  8085. resultElementKind = AR_BASIC_INT32;
  8086. } else if (resultElementKind == AR_BASIC_BOOL &&
  8087. BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  8088. resultElementKind = AR_BASIC_INT32;
  8089. }
  8090. // The following combines the selected/combined element kind above with
  8091. // the dimensions that are legal to implicitly cast. This means that
  8092. // element kind may be taken from one side and the dimensions from the
  8093. // other.
  8094. if (!isCompoundAssignment) {
  8095. // Legal dimension combinations are identical, splat, and truncation.
  8096. // ResultTy will be set to whichever type can be converted to, if legal,
  8097. // with preference for leftType if both are possible.
  8098. if (FAILED(CombineDimensions(LHS.get()->getType(), RHS.get()->getType(), &ResultTy))) {
  8099. // Just choose leftType, and allow ValidateCast to catch this later
  8100. ResultTy = LHS.get()->getType();
  8101. }
  8102. } else {
  8103. ResultTy = LHS.get()->getType();
  8104. }
  8105. // Here, element kind is combined with dimensions for computation type, if different.
  8106. if (resultElementKind != GetTypeElementKind(ResultTy)) {
  8107. UINT rowCount, colCount;
  8108. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8109. ResultTy = NewSimpleAggregateType(GetTypeObjectKind(ResultTy), resultElementKind, 0, rowCount, colCount);
  8110. }
  8111. }
  8112. bool bFailedFirstRHSCast = false;
  8113. // Perform necessary conversion sequences for LHS and RHS
  8114. if (RHS.get()->getType() != ResultTy) {
  8115. StandardConversionSequence standard;
  8116. // Suppress type narrowing or truncation warnings for RHS on bitwise shift, since we only care about the LHS type.
  8117. bool bSuppressWarnings = BinaryOperatorKindIsBitwiseShift(Opc);
  8118. // Suppress errors on compound assignment, since we will validate the cast to the final type later.
  8119. bool bSuppressErrors = isCompoundAssignment;
  8120. // Suppress errors if either operand has a dependent type.
  8121. if (RHS.get()->getType()->isDependentType() || ResultTy->isDependentType())
  8122. bSuppressErrors = true;
  8123. // If compound assignment, suppress errors until later, but report warning (vector truncation/type narrowing) here.
  8124. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, bSuppressWarnings, bSuppressErrors, &standard)) {
  8125. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8126. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8127. } else if (!isCompoundAssignment) {
  8128. // If compound assignment, validate cast from RHS directly to LHS later, otherwise, fail here.
  8129. ResultTy = QualType();
  8130. return;
  8131. } else {
  8132. bFailedFirstRHSCast = true;
  8133. }
  8134. }
  8135. if (isCompoundAssignment) {
  8136. CompResultTy = ResultTy;
  8137. CompLHSTy = CompResultTy;
  8138. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  8139. // then converts to the result type and then assigns.
  8140. //
  8141. // So int + float promotes the int to float, does a floating-point addition,
  8142. // then the result becomes and int and is assigned.
  8143. ResultTy = LHSTypeAsPossibleLValue;
  8144. // Validate remainder of cast from computation type to final result type
  8145. StandardConversionSequence standard;
  8146. if (!ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8147. ResultTy = QualType();
  8148. return;
  8149. }
  8150. DXASSERT_LOCALVAR(bFailedFirstRHSCast, !bFailedFirstRHSCast,
  8151. "otherwise, hit compound assign case that failed RHS -> CompResultTy cast, but succeeded RHS -> LHS cast.");
  8152. } else if (LHS.get()->getType() != ResultTy) {
  8153. StandardConversionSequence standard;
  8154. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8155. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8156. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8157. } else {
  8158. ResultTy = QualType();
  8159. return;
  8160. }
  8161. }
  8162. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  8163. {
  8164. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  8165. // Return bool vector for vector types.
  8166. if (IsVectorType(m_sema, ResultTy)) {
  8167. UINT rowCount, colCount;
  8168. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8169. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  8170. } else if (IsMatrixType(m_sema, ResultTy)) {
  8171. UINT rowCount, colCount;
  8172. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8173. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  8174. } else
  8175. ResultTy = m_context->BoolTy.withConst();
  8176. }
  8177. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  8178. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  8179. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  8180. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  8181. return;
  8182. }
  8183. }
  8184. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  8185. if (resultElementKind == AR_BASIC_FLOAT64) {
  8186. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  8187. return;
  8188. }
  8189. }
  8190. }
  8191. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  8192. /// <param name="OpLoc">Source location for operator.</param>
  8193. /// <param name="Opc">Kind of operator.</param>
  8194. /// <param name="InputExpr">Input expression to the operator.</param>
  8195. /// <param name="VK">Value kind for resulting expression.</param>
  8196. /// <param name="OK">Object kind for resulting expression.</param>
  8197. /// <returns>The result type for the expression.</returns>
  8198. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  8199. SourceLocation OpLoc,
  8200. UnaryOperatorKind Opc,
  8201. ExprResult& InputExpr,
  8202. ExprValueKind& VK,
  8203. ExprObjectKind& OK)
  8204. {
  8205. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  8206. if (InputExpr.isInvalid())
  8207. return QualType();
  8208. // Reject unsupported operators * and &
  8209. switch (Opc) {
  8210. case UO_AddrOf:
  8211. case UO_Deref:
  8212. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  8213. return QualType();
  8214. default:
  8215. // Only * and & covered.
  8216. break;
  8217. }
  8218. Expr* expr = InputExpr.get();
  8219. if (expr->isTypeDependent())
  8220. return m_context->DependentTy;
  8221. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  8222. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  8223. if (elementKind == AR_BASIC_ENUM) {
  8224. bool isInc = IsIncrementOp(Opc);
  8225. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  8226. return QualType();
  8227. }
  8228. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  8229. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  8230. return QualType();
  8231. } else {
  8232. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  8233. if (InputExpr.isInvalid()) return QualType();
  8234. }
  8235. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  8236. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  8237. return QualType();
  8238. }
  8239. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  8240. InputExpr = PromoteToIntIfBool(InputExpr);
  8241. expr = InputExpr.get();
  8242. elementKind = GetTypeElementKind(expr->getType());
  8243. }
  8244. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  8245. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  8246. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  8247. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  8248. return QualType();
  8249. }
  8250. if (Opc == UnaryOperatorKind::UO_Minus) {
  8251. if (IS_BASIC_UINT(Opc)) {
  8252. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  8253. }
  8254. }
  8255. // By default, the result type is the operand type.
  8256. // Logical not however should cast to a bool.
  8257. QualType resultType = expr->getType();
  8258. if (Opc == UnaryOperatorKind::UO_LNot) {
  8259. UINT rowCount, colCount;
  8260. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  8261. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  8262. StandardConversionSequence standard;
  8263. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  8264. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  8265. return QualType();
  8266. }
  8267. // Cast argument.
  8268. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8269. if (result.isUsable()) {
  8270. InputExpr = result.get();
  8271. }
  8272. }
  8273. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  8274. if (isPrefix) {
  8275. VK = VK_LValue;
  8276. return resultType;
  8277. }
  8278. else {
  8279. VK = VK_RValue;
  8280. return resultType.getUnqualifiedType();
  8281. }
  8282. }
  8283. clang::QualType HLSLExternalSource::CheckVectorConditional(
  8284. _In_ ExprResult &Cond,
  8285. _In_ ExprResult &LHS,
  8286. _In_ ExprResult &RHS,
  8287. _In_ SourceLocation QuestionLoc)
  8288. {
  8289. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  8290. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  8291. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  8292. // If either expression is invalid to begin with, propagate that.
  8293. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  8294. return QualType();
  8295. }
  8296. // Gather type info
  8297. QualType condType = GetStructuralForm(Cond.get()->getType());
  8298. QualType leftType = GetStructuralForm(LHS.get()->getType());
  8299. QualType rightType = GetStructuralForm(RHS.get()->getType());
  8300. // If any type is dependent, we will use that as the type to return.
  8301. if (leftType->isDependentType())
  8302. return leftType;
  8303. if (rightType->isDependentType())
  8304. return rightType;
  8305. if (condType->isDependentType())
  8306. return condType;
  8307. ArBasicKind condElementKind = GetTypeElementKind(condType);
  8308. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  8309. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  8310. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  8311. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  8312. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  8313. QualType ResultTy = leftType;
  8314. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  8315. if (!condIsSimple) {
  8316. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  8317. return QualType();
  8318. }
  8319. UINT rowCountCond, colCountCond;
  8320. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  8321. bool leftIsSimple =
  8322. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  8323. leftObjectKind == AR_TOBJ_MATRIX;
  8324. bool rightIsSimple =
  8325. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  8326. rightObjectKind == AR_TOBJ_MATRIX;
  8327. if (!leftIsSimple || !rightIsSimple) {
  8328. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  8329. if (leftType == rightType) {
  8330. return leftType;
  8331. }
  8332. }
  8333. // NOTE: Limiting this operator to working only on basic numeric types.
  8334. // This is due to extremely limited (and even broken) support for any other case.
  8335. // In the future we may decide to support more cases.
  8336. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  8337. return QualType();
  8338. }
  8339. // Types should be only scalar, vector, or matrix after this point.
  8340. ArBasicKind resultElementKind = leftElementKind;
  8341. // Combine LHS and RHS element types for computation.
  8342. if (leftElementKind != rightElementKind) {
  8343. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  8344. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  8345. return QualType();
  8346. }
  8347. }
  8348. // Restore left/right type to original to avoid stripping attributed type or typedef type
  8349. leftType = LHS.get()->getType();
  8350. rightType = RHS.get()->getType();
  8351. // Combine LHS and RHS dimensions
  8352. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  8353. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  8354. return QualType();
  8355. }
  8356. UINT rowCount, colCount;
  8357. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8358. // If result is scalar, use condition dimensions.
  8359. // Otherwise, condition must either match or is scalar, then use result dimensions
  8360. if (rowCount * colCount == 1) {
  8361. rowCount = rowCountCond;
  8362. colCount = colCountCond;
  8363. }
  8364. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  8365. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  8366. return QualType();
  8367. }
  8368. // Here, element kind is combined with dimensions for result type.
  8369. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8370. // Cast condition to RValue
  8371. if (Cond.get()->isLValue())
  8372. Cond.set(CreateLValueToRValueCast(Cond.get()));
  8373. // Convert condition component type to bool, using result component dimensions
  8374. if (condElementKind != AR_BASIC_BOOL) {
  8375. QualType boolType = NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8376. StandardConversionSequence standard;
  8377. if (ValidateCast(SourceLocation(), Cond.get(), boolType, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8378. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8379. Cond = m_sema->PerformImplicitConversion(Cond.get(), boolType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8380. }
  8381. else {
  8382. return QualType();
  8383. }
  8384. }
  8385. // TODO: Is this correct? Does fxc support lvalue return here?
  8386. // Cast LHS/RHS to RValue
  8387. if (LHS.get()->isLValue())
  8388. LHS.set(CreateLValueToRValueCast(LHS.get()));
  8389. if (RHS.get()->isLValue())
  8390. RHS.set(CreateLValueToRValueCast(RHS.get()));
  8391. if (leftType != ResultTy) {
  8392. StandardConversionSequence standard;
  8393. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8394. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8395. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8396. }
  8397. else {
  8398. return QualType();
  8399. }
  8400. }
  8401. if (rightType != ResultTy) {
  8402. StandardConversionSequence standard;
  8403. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8404. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8405. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8406. }
  8407. else {
  8408. return QualType();
  8409. }
  8410. }
  8411. return ResultTy;
  8412. }
  8413. // Apply type specifier sign to the given QualType.
  8414. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  8415. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  8416. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  8417. _In_ clang::SourceLocation Loc) {
  8418. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  8419. return type;
  8420. }
  8421. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  8422. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  8423. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  8424. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  8425. return type;
  8426. }
  8427. // check if element type is unsigned and check if such vector exists
  8428. // If not create a new one, Make a QualType of the new kind
  8429. ArBasicKind elementKind = GetTypeElementKind(type);
  8430. // Only ints can have signed/unsigend ty
  8431. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  8432. return type;
  8433. }
  8434. else {
  8435. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  8436. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  8437. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  8438. // Get new vector types for a given TypeSpecifierSign.
  8439. if (objKind == AR_TOBJ_VECTOR) {
  8440. UINT colCount = GetHLSLVecSize(type);
  8441. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  8442. return m_context->getTypeDeclType(qts);
  8443. } else if (objKind == AR_TOBJ_MATRIX) {
  8444. UINT rowCount, colCount;
  8445. GetRowsAndCols(type, rowCount, colCount);
  8446. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  8447. return m_context->getTypeDeclType(qts);
  8448. } else {
  8449. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  8450. return m_scalarTypes[newScalarType];
  8451. }
  8452. }
  8453. }
  8454. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  8455. FunctionTemplateDecl *FunctionTemplate,
  8456. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8457. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8458. {
  8459. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  8460. // Get information about the function we have.
  8461. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  8462. if (!functionMethod) {
  8463. // standalone function.
  8464. return Sema::TemplateDeductionResult::TDK_Invalid;
  8465. }
  8466. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  8467. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  8468. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  8469. QualType functionTemplateTypeArg {};
  8470. if (ExplicitTemplateArgs != nullptr && ExplicitTemplateArgs->size() == 1) {
  8471. const TemplateArgument &firstTemplateArg = (*ExplicitTemplateArgs)[0].getArgument();
  8472. if (firstTemplateArg.getKind() == TemplateArgument::ArgKind::Type)
  8473. functionTemplateTypeArg = firstTemplateArg.getAsType();
  8474. }
  8475. // Handle subscript overloads.
  8476. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  8477. {
  8478. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  8479. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  8480. if (!findResult.Found())
  8481. {
  8482. // This might be a nested type. Do a lookup on the parent.
  8483. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  8484. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  8485. {
  8486. return Sema::TemplateDeductionResult::TDK_Invalid;
  8487. }
  8488. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  8489. if (!findResult.Found())
  8490. {
  8491. return Sema::TemplateDeductionResult::TDK_Invalid;
  8492. }
  8493. DXASSERT(
  8494. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  8495. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  8496. "otherwise FindStructBasicType should have failed - no other types are allowed");
  8497. objectElement = GetFirstElementTypeFromDecl(
  8498. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  8499. }
  8500. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  8501. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8502. FunctionTemplate->getCanonicalDecl());
  8503. return Sema::TemplateDeductionResult::TDK_Success;
  8504. }
  8505. // Reject overload lookups that aren't identifier-based.
  8506. if (!FunctionTemplate->getDeclName().isIdentifier())
  8507. {
  8508. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8509. }
  8510. // Find the table of intrinsics based on the object type.
  8511. const HLSL_INTRINSIC* intrinsics = nullptr;
  8512. size_t intrinsicCount = 0;
  8513. const char* objectName = nullptr;
  8514. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  8515. // user-defined template object.
  8516. if (objectName == nullptr && intrinsics == nullptr) {
  8517. return Sema::TemplateDeductionResult::TDK_Invalid;
  8518. }
  8519. DXASSERT(objectName != nullptr &&
  8520. (intrinsics != nullptr || m_intrinsicTables.size() > 0),
  8521. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  8522. "or the parser let a user-defined template object through");
  8523. // Look for an intrinsic for which we can match arguments.
  8524. std::vector<QualType> argTypes;
  8525. StringRef nameIdentifier = FunctionTemplate->getName();
  8526. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  8527. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  8528. while (cursor != end)
  8529. {
  8530. size_t badArgIdx;
  8531. if (!MatchArguments(*cursor, objectElement, functionTemplateTypeArg, Args, &argTypes, badArgIdx))
  8532. {
  8533. ++cursor;
  8534. continue;
  8535. }
  8536. // Currently only intrinsic we allow for explicit template arguments are
  8537. // for Load/Store for ByteAddressBuffer/RWByteAddressBuffer
  8538. // Check Explicit template arguments
  8539. UINT intrinsicOp = (*cursor)->Op;
  8540. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  8541. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  8542. bool IsBAB =
  8543. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  8544. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  8545. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  8546. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  8547. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  8548. bool isLegalTemplate = false;
  8549. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  8550. auto TemplateDiag = diag::err_hlsl_intrinsic_template_arg_unsupported;
  8551. if (ExplicitTemplateArgs->size() >= 1 && (IsBABLoad || IsBABStore)) {
  8552. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_requires_2018;
  8553. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  8554. if (Is2018) {
  8555. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_numeric;
  8556. if (ExplicitTemplateArgs->size() == 1
  8557. && !functionTemplateTypeArg.isNull()
  8558. && hlsl::IsHLSLNumericOrAggregateOfNumericType(functionTemplateTypeArg)) {
  8559. isLegalTemplate = true;
  8560. }
  8561. }
  8562. }
  8563. if (!isLegalTemplate) {
  8564. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  8565. return Sema::TemplateDeductionResult::TDK_Invalid;
  8566. }
  8567. } else if (IsBABStore) {
  8568. // Prior to HLSL 2018, Store operation only stored scalar uint.
  8569. if (!Is2018) {
  8570. if (GetNumElements(argTypes[2]) != 1) {
  8571. getSema()->Diag(Args[1]->getLocStart(),
  8572. diag::err_ovl_no_viable_member_function_in_call)
  8573. << intrinsicName;
  8574. return Sema::TemplateDeductionResult::TDK_Invalid;
  8575. }
  8576. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  8577. 32, /*signed*/ false);
  8578. }
  8579. }
  8580. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes.data(), argTypes.size());
  8581. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8582. FunctionTemplate->getCanonicalDecl());
  8583. if (!IsValidateObjectElement(*cursor, objectElement)) {
  8584. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  8585. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  8586. }
  8587. return Sema::TemplateDeductionResult::TDK_Success;
  8588. }
  8589. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8590. }
  8591. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  8592. {
  8593. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  8594. }
  8595. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  8596. QualType DestType,
  8597. Sema::CheckedConversionKind CCK,
  8598. const SourceRange &OpRange, unsigned &msg,
  8599. CastKind &Kind, CXXCastPath &BasePath,
  8600. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  8601. _Inout_opt_ StandardConversionSequence* standard)
  8602. {
  8603. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  8604. bool explicitConversion
  8605. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  8606. bool suppressWarnings = explicitConversion || SuppressWarnings;
  8607. SourceLocation loc = OpRange.getBegin();
  8608. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  8609. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  8610. // so do this here until we figure out why this is needed.
  8611. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  8612. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  8613. }
  8614. return true;
  8615. }
  8616. // ValidateCast includes its own error messages.
  8617. msg = 0;
  8618. return false;
  8619. }
  8620. /// <summary>
  8621. /// Checks if a subscript index argument can be initialized from the given expression.
  8622. /// </summary>
  8623. /// <param name="SrcExpr">Source expression used as argument.</param>
  8624. /// <param name="DestType">Parameter type to initialize.</param>
  8625. /// <remarks>
  8626. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  8627. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  8628. /// </remarks>
  8629. ImplicitConversionSequence
  8630. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  8631. clang::QualType DestType) {
  8632. DXASSERT_NOMSG(SrcExpr != nullptr);
  8633. DXASSERT_NOMSG(!DestType.isNull());
  8634. unsigned int msg = 0;
  8635. CastKind kind;
  8636. CXXCastPath path;
  8637. ImplicitConversionSequence sequence;
  8638. sequence.setStandard();
  8639. ExprResult sourceExpr(SrcExpr);
  8640. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  8641. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8642. SrcExpr->getType(), DestType);
  8643. } else if (!TryStaticCastForHLSL(
  8644. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  8645. msg, kind, path, ListInitializationFalse,
  8646. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  8647. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8648. SrcExpr->getType(), DestType);
  8649. }
  8650. return sequence;
  8651. }
  8652. template <typename T>
  8653. static
  8654. bool IsValueInRange(T value, T minValue, T maxValue) {
  8655. return minValue <= value && value <= maxValue;
  8656. }
  8657. #define D3DX_16F_MAX 6.550400e+004 // max value
  8658. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  8659. static
  8660. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  8661. {
  8662. DXASSERT_NOMSG(minValue != nullptr);
  8663. DXASSERT_NOMSG(maxValue != nullptr);
  8664. switch (basicKind) {
  8665. case AR_BASIC_MIN10FLOAT:
  8666. case AR_BASIC_MIN16FLOAT:
  8667. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  8668. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8669. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  8670. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  8671. default:
  8672. // No other float types.
  8673. break;
  8674. }
  8675. DXASSERT(false, "unreachable");
  8676. *minValue = 0; *maxValue = 0;
  8677. return;
  8678. }
  8679. static
  8680. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  8681. {
  8682. DXASSERT_NOMSG(maxValue != nullptr);
  8683. switch (basicKind) {
  8684. case AR_BASIC_BOOL: *maxValue = 1; return;
  8685. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  8686. case AR_BASIC_MIN16UINT:
  8687. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  8688. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  8689. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  8690. default:
  8691. // No other unsigned int types.
  8692. break;
  8693. }
  8694. DXASSERT(false, "unreachable");
  8695. *maxValue = 0;
  8696. return;
  8697. }
  8698. static
  8699. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  8700. {
  8701. DXASSERT_NOMSG(minValue != nullptr);
  8702. DXASSERT_NOMSG(maxValue != nullptr);
  8703. switch (basicKind) {
  8704. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  8705. case AR_BASIC_MIN12INT:
  8706. case AR_BASIC_MIN16INT:
  8707. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  8708. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  8709. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  8710. default:
  8711. // No other signed int types.
  8712. break;
  8713. }
  8714. DXASSERT(false, "unreachable");
  8715. *minValue = 0; *maxValue = 0;
  8716. return;
  8717. }
  8718. static
  8719. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  8720. {
  8721. if (IS_BASIC_FLOAT(basicKind)) {
  8722. double val;
  8723. if (value.isInt()) {
  8724. val = value.getInt().getLimitedValue();
  8725. } else if (value.isFloat()) {
  8726. llvm::APFloat floatValue = value.getFloat();
  8727. if (!floatValue.isFinite()) {
  8728. return false;
  8729. }
  8730. llvm::APFloat valueFloat = value.getFloat();
  8731. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  8732. val = value.getFloat().convertToFloat();
  8733. }
  8734. else {
  8735. val = value.getFloat().convertToDouble();
  8736. }
  8737. } else {
  8738. return false;
  8739. }
  8740. double minValue, maxValue;
  8741. GetFloatLimits(basicKind, &minValue, &maxValue);
  8742. return IsValueInRange(val, minValue, maxValue);
  8743. }
  8744. else if (IS_BASIC_SINT(basicKind)) {
  8745. if (!value.isInt()) {
  8746. return false;
  8747. }
  8748. int64_t val = value.getInt().getSExtValue();
  8749. int64_t minValue, maxValue;
  8750. GetSignedLimits(basicKind, &minValue, &maxValue);
  8751. return IsValueInRange(val, minValue, maxValue);
  8752. }
  8753. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  8754. if (!value.isInt()) {
  8755. return false;
  8756. }
  8757. uint64_t val = value.getInt().getLimitedValue();
  8758. uint64_t maxValue;
  8759. GetUnsignedLimit(basicKind, &maxValue);
  8760. return IsValueInRange(val, (uint64_t)0, maxValue);
  8761. }
  8762. else {
  8763. return false;
  8764. }
  8765. }
  8766. static
  8767. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  8768. {
  8769. DXASSERT_NOMSG(!targetType.isNull());
  8770. DXASSERT_NOMSG(sourceExpr != nullptr);
  8771. Expr::EvalResult evalResult;
  8772. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  8773. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  8774. return IsValueInBasicRange(targetKind, evalResult.Val);
  8775. }
  8776. }
  8777. return false;
  8778. }
  8779. bool HLSLExternalSource::ValidateCast(
  8780. SourceLocation OpLoc,
  8781. _In_ Expr* sourceExpr,
  8782. QualType target,
  8783. bool explicitConversion,
  8784. bool suppressWarnings,
  8785. bool suppressErrors,
  8786. _Inout_opt_ StandardConversionSequence* standard)
  8787. {
  8788. DXASSERT_NOMSG(sourceExpr != nullptr);
  8789. if (OpLoc.isInvalid())
  8790. OpLoc = sourceExpr->getExprLoc();
  8791. QualType source = sourceExpr->getType();
  8792. TYPE_CONVERSION_REMARKS remarks = TYPE_CONVERSION_NONE;
  8793. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  8794. {
  8795. //
  8796. // Check whether the lack of explicit-ness matters.
  8797. //
  8798. // Setting explicitForDiagnostics to true in that case will avoid the message
  8799. // saying anything about the implicit nature of the cast, when adding the
  8800. // explicit cast won't make a difference.
  8801. //
  8802. bool explicitForDiagnostics = explicitConversion;
  8803. if (explicitConversion == false)
  8804. {
  8805. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  8806. {
  8807. // Can't convert either way - implicit/explicit doesn't matter.
  8808. explicitForDiagnostics = true;
  8809. }
  8810. }
  8811. if (!suppressErrors)
  8812. {
  8813. bool IsOutputParameter = false;
  8814. if (clang::DeclRefExpr *OutFrom = dyn_cast<clang::DeclRefExpr>(sourceExpr)) {
  8815. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(OutFrom->getDecl())) {
  8816. IsOutputParameter = Param->isModifierOut();
  8817. }
  8818. }
  8819. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  8820. << explicitForDiagnostics << IsOutputParameter << source << target;
  8821. }
  8822. return false;
  8823. }
  8824. if (!suppressWarnings)
  8825. {
  8826. if (!explicitConversion)
  8827. {
  8828. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  8829. {
  8830. // This is a much more restricted version of the analysis does
  8831. // StandardConversionSequence::getNarrowingKind
  8832. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  8833. {
  8834. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  8835. }
  8836. }
  8837. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  8838. {
  8839. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  8840. }
  8841. }
  8842. }
  8843. return true;
  8844. }
  8845. ////////////////////////////////////////////////////////////////////////////////
  8846. // Functions exported from this translation unit. //
  8847. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  8848. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  8849. SourceLocation OpLoc,
  8850. UnaryOperatorKind Opc,
  8851. ExprResult& InputExpr,
  8852. ExprValueKind& VK,
  8853. ExprObjectKind& OK)
  8854. {
  8855. ExternalSemaSource* externalSource = self.getExternalSource();
  8856. if (externalSource == nullptr) {
  8857. return QualType();
  8858. }
  8859. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8860. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  8861. }
  8862. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  8863. void hlsl::CheckBinOpForHLSL(Sema& self,
  8864. SourceLocation OpLoc,
  8865. BinaryOperatorKind Opc,
  8866. ExprResult& LHS,
  8867. ExprResult& RHS,
  8868. QualType& ResultTy,
  8869. QualType& CompLHSTy,
  8870. QualType& CompResultTy)
  8871. {
  8872. ExternalSemaSource* externalSource = self.getExternalSource();
  8873. if (externalSource == nullptr) {
  8874. return;
  8875. }
  8876. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8877. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  8878. }
  8879. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  8880. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  8881. {
  8882. DXASSERT_NOMSG(Template != nullptr);
  8883. ExternalSemaSource* externalSource = self.getExternalSource();
  8884. if (externalSource == nullptr) {
  8885. return false;
  8886. }
  8887. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8888. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  8889. }
  8890. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  8891. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  8892. FunctionTemplateDecl *FunctionTemplate,
  8893. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8894. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8895. {
  8896. return HLSLExternalSource::FromSema(self)
  8897. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  8898. }
  8899. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  8900. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  8901. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  8902. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  8903. self->Diag(condExpr->getLocStart(),
  8904. diag::err_hlsl_control_flow_cond_not_scalar)
  8905. << StmtName;
  8906. return;
  8907. }
  8908. condExpr = IC->getSubExpr();
  8909. }
  8910. }
  8911. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  8912. {
  8913. // TODO: handle shorthand cases.
  8914. return left.size() == 0 || right.size() == 0 || left.equals(right);
  8915. }
  8916. void hlsl::DiagnosePackingOffset(
  8917. clang::Sema* self,
  8918. SourceLocation loc,
  8919. clang::QualType type,
  8920. int componentOffset)
  8921. {
  8922. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  8923. if (componentOffset > 0) {
  8924. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8925. ArBasicKind element = source->GetTypeElementKind(type);
  8926. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  8927. // Only perform some simple validation for now.
  8928. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  8929. int count = GetElementCount(type);
  8930. if (count > (4 - componentOffset)) {
  8931. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  8932. }
  8933. }
  8934. }
  8935. }
  8936. void hlsl::DiagnoseRegisterType(
  8937. clang::Sema* self,
  8938. clang::SourceLocation loc,
  8939. clang::QualType type,
  8940. char registerType)
  8941. {
  8942. // Register type can be zero if only a register space was provided.
  8943. if (registerType == 0)
  8944. return;
  8945. if (registerType >= 'A' && registerType <= 'Z')
  8946. registerType = registerType + ('a' - 'A');
  8947. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8948. ArBasicKind element = source->GetTypeElementKind(type);
  8949. StringRef expected("none");
  8950. bool isValid = true;
  8951. bool isWarning = false;
  8952. switch (element)
  8953. {
  8954. case AR_BASIC_BOOL:
  8955. case AR_BASIC_LITERAL_FLOAT:
  8956. case AR_BASIC_FLOAT16:
  8957. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8958. case AR_BASIC_FLOAT32:
  8959. case AR_BASIC_FLOAT64:
  8960. case AR_BASIC_LITERAL_INT:
  8961. case AR_BASIC_INT8:
  8962. case AR_BASIC_UINT8:
  8963. case AR_BASIC_INT16:
  8964. case AR_BASIC_UINT16:
  8965. case AR_BASIC_INT32:
  8966. case AR_BASIC_UINT32:
  8967. case AR_BASIC_INT64:
  8968. case AR_BASIC_UINT64:
  8969. case AR_BASIC_MIN10FLOAT:
  8970. case AR_BASIC_MIN16FLOAT:
  8971. case AR_BASIC_MIN12INT:
  8972. case AR_BASIC_MIN16INT:
  8973. case AR_BASIC_MIN16UINT:
  8974. expected = "'b', 'c', or 'i'";
  8975. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i';
  8976. break;
  8977. case AR_OBJECT_TEXTURE1D:
  8978. case AR_OBJECT_TEXTURE1D_ARRAY:
  8979. case AR_OBJECT_TEXTURE2D:
  8980. case AR_OBJECT_TEXTURE2D_ARRAY:
  8981. case AR_OBJECT_TEXTURE3D:
  8982. case AR_OBJECT_TEXTURECUBE:
  8983. case AR_OBJECT_TEXTURECUBE_ARRAY:
  8984. case AR_OBJECT_TEXTURE2DMS:
  8985. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  8986. expected = "'t' or 's'";
  8987. isValid = registerType == 't' || registerType == 's';
  8988. break;
  8989. case AR_OBJECT_SAMPLER:
  8990. case AR_OBJECT_SAMPLER1D:
  8991. case AR_OBJECT_SAMPLER2D:
  8992. case AR_OBJECT_SAMPLER3D:
  8993. case AR_OBJECT_SAMPLERCUBE:
  8994. case AR_OBJECT_SAMPLERCOMPARISON:
  8995. expected = "'s' or 't'";
  8996. isValid = registerType == 's' || registerType == 't';
  8997. break;
  8998. case AR_OBJECT_BUFFER:
  8999. expected = "'t'";
  9000. isValid = registerType == 't';
  9001. break;
  9002. case AR_OBJECT_POINTSTREAM:
  9003. case AR_OBJECT_LINESTREAM:
  9004. case AR_OBJECT_TRIANGLESTREAM:
  9005. isValid = false;
  9006. isWarning = true;
  9007. break;
  9008. case AR_OBJECT_INPUTPATCH:
  9009. case AR_OBJECT_OUTPUTPATCH:
  9010. isValid = false;
  9011. isWarning = true;
  9012. break;
  9013. case AR_OBJECT_RWTEXTURE1D:
  9014. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  9015. case AR_OBJECT_RWTEXTURE2D:
  9016. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  9017. case AR_OBJECT_RWTEXTURE3D:
  9018. case AR_OBJECT_RWBUFFER:
  9019. expected = "'u'";
  9020. isValid = registerType == 'u';
  9021. break;
  9022. case AR_OBJECT_BYTEADDRESS_BUFFER:
  9023. case AR_OBJECT_STRUCTURED_BUFFER:
  9024. expected = "'t'";
  9025. isValid = registerType == 't';
  9026. break;
  9027. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  9028. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  9029. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  9030. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  9031. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  9032. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  9033. expected = "'u'";
  9034. isValid = registerType == 'u';
  9035. break;
  9036. case AR_OBJECT_CONSTANT_BUFFER:
  9037. expected = "'b'";
  9038. isValid = registerType == 'b';
  9039. break;
  9040. case AR_OBJECT_TEXTURE_BUFFER:
  9041. expected = "'t'";
  9042. isValid = registerType == 't';
  9043. break;
  9044. case AR_OBJECT_ROVBUFFER:
  9045. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  9046. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  9047. case AR_OBJECT_ROVTEXTURE1D:
  9048. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  9049. case AR_OBJECT_ROVTEXTURE2D:
  9050. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  9051. case AR_OBJECT_ROVTEXTURE3D:
  9052. case AR_OBJECT_FEEDBACKTEXTURE2D:
  9053. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  9054. expected = "'u'";
  9055. isValid = registerType == 'u';
  9056. break;
  9057. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  9058. isWarning = true;
  9059. break; // So we don't care what you tried to bind it to
  9060. default: // Other types have no associated registers.
  9061. break;
  9062. }
  9063. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  9064. // a warning instead.
  9065. if (!isValid) {
  9066. unsigned DiagID = isWarning ? diag::warn_hlsl_incorrect_bind_semantic : diag::err_hlsl_incorrect_bind_semantic;
  9067. self->Diag(loc, DiagID) << expected;
  9068. }
  9069. }
  9070. struct NameLookup {
  9071. FunctionDecl *Found;
  9072. FunctionDecl *Other;
  9073. };
  9074. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  9075. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  9076. FunctionDecl *pFoundDecl = nullptr;
  9077. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  9078. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  9079. if (!pFnDecl) continue;
  9080. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  9081. if (pFoundDecl) {
  9082. return NameLookup{ pFoundDecl, pFnDecl };
  9083. }
  9084. pFoundDecl = pFnDecl;
  9085. }
  9086. return NameLookup{ pFoundDecl, nullptr };
  9087. }
  9088. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  9089. DXASSERT_NOMSG(self != nullptr);
  9090. // Don't bother with global validation if compilation has already failed.
  9091. if (self->getDiagnostics().hasErrorOccurred()) {
  9092. return;
  9093. }
  9094. // Check RT shader if available for their payload use and match payload access
  9095. // against availiable payload modifiers.
  9096. // We have to do it late because we could have payload access in a called function
  9097. // and have to check the callgraph if the root shader has the right access
  9098. // rights to the payload structure.
  9099. if (self->getLangOpts().IsHLSLLibrary) {
  9100. if (self->getLangOpts().EnablePayloadAccessQualifiers) {
  9101. ASTContext &ctx = self->getASTContext();
  9102. TranslationUnitDecl *TU = ctx.getTranslationUnitDecl();
  9103. DiagnoseRaytracingPayloadAccess(*self, TU);
  9104. }
  9105. }
  9106. // Don't check entry function for library.
  9107. if (self->getLangOpts().IsHLSLLibrary) {
  9108. // TODO: validate no recursion start from every function.
  9109. return;
  9110. }
  9111. // TODO: make these error 'real' errors rather than on-the-fly things
  9112. // Validate that the entry point is available.
  9113. DiagnosticsEngine &Diags = self->getDiagnostics();
  9114. FunctionDecl *pEntryPointDecl = nullptr;
  9115. FunctionDecl *pPatchFnDecl = nullptr;
  9116. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  9117. if (!EntryPointName.empty()) {
  9118. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  9119. if (NL.Found && NL.Other) {
  9120. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  9121. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  9122. // string, and so ambiguous points will produce an error earlier on.
  9123. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9124. "ambiguous entry point function");
  9125. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  9126. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  9127. return;
  9128. }
  9129. pEntryPointDecl = NL.Found;
  9130. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  9131. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9132. "missing entry point definition");
  9133. Diags.Report(id);
  9134. return;
  9135. }
  9136. }
  9137. // Validate that there is no recursion; start with the entry function.
  9138. // NOTE: the information gathered here could be used to bypass code generation
  9139. // on functions that are unreachable (as an early form of dead code elimination).
  9140. if (pEntryPointDecl) {
  9141. const auto *shaderModel =
  9142. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  9143. if (shaderModel->IsGS()) {
  9144. // Validate that GS has the maxvertexcount attribute
  9145. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  9146. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9147. << "GS"
  9148. << "maxvertexcount";
  9149. return;
  9150. }
  9151. } else if (shaderModel->IsHS()) {
  9152. if (const HLSLPatchConstantFuncAttr *Attr =
  9153. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  9154. NameLookup NL = GetSingleFunctionDeclByName(
  9155. self, Attr->getFunctionName(), /*checkPatch*/ true);
  9156. if (!NL.Found || !NL.Found->hasBody()) {
  9157. unsigned id =
  9158. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9159. "missing patch function definition");
  9160. Diags.Report(id);
  9161. return;
  9162. }
  9163. pPatchFnDecl = NL.Found;
  9164. } else {
  9165. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9166. << "HS"
  9167. << "patchconstantfunc";
  9168. return;
  9169. }
  9170. } else if (shaderModel->IsMS()) {
  9171. // Validate that MS has the numthreads attribute
  9172. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  9173. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9174. << "MS"
  9175. << "numthreads";
  9176. return;
  9177. }
  9178. // Validate that MS has the outputtopology attribute
  9179. if (!pEntryPointDecl->hasAttr<HLSLOutputTopologyAttr>()) {
  9180. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9181. << "MS"
  9182. << "outputtopology";
  9183. return;
  9184. }
  9185. } else if (shaderModel->IsAS()) {
  9186. // Validate that AS has the numthreads attribute
  9187. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  9188. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9189. << "AS"
  9190. << "numthreads";
  9191. return;
  9192. }
  9193. }
  9194. hlsl::CallGraphWithRecurseGuard CG;
  9195. CG.BuildForEntry(pEntryPointDecl);
  9196. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  9197. if (pResult) {
  9198. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9199. "recursive functions not allowed");
  9200. Diags.Report(pResult->getSourceRange().getBegin(), id);
  9201. }
  9202. if (pPatchFnDecl) {
  9203. CG.BuildForEntry(pPatchFnDecl);
  9204. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  9205. if (pPatchFnDecl) {
  9206. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9207. "recursive functions not allowed (via patch function)");
  9208. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  9209. }
  9210. }
  9211. }
  9212. }
  9213. void hlsl::DiagnosePayloadAccessQualifierAnnotations(
  9214. Sema &S, Declarator& D, const QualType& T, const std::vector<hlsl::UnusualAnnotation *>& annotations) {
  9215. auto &&iter = annotations.begin();
  9216. auto &&end = annotations.end();
  9217. hlsl::PayloadAccessAnnotation *readAnnotation = nullptr;
  9218. hlsl::PayloadAccessAnnotation *writeAnnotation = nullptr;
  9219. for (; iter != end; ++iter) {
  9220. switch ((*iter)->getKind()) {
  9221. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  9222. hlsl::PayloadAccessAnnotation *annotation =
  9223. cast<hlsl::PayloadAccessAnnotation>(*iter);
  9224. if (annotation->qualifier == DXIL::PayloadAccessQualifier::Read) {
  9225. if (!readAnnotation)
  9226. readAnnotation = annotation;
  9227. else {
  9228. S.Diag(annotation->Loc,
  9229. diag::err_hlsl_payload_access_qualifier_multiple_defined)
  9230. << "read";
  9231. return;
  9232. }
  9233. } else if (annotation->qualifier == DXIL::PayloadAccessQualifier::Write) {
  9234. if (!writeAnnotation)
  9235. writeAnnotation = annotation;
  9236. else {
  9237. S.Diag(annotation->Loc,
  9238. diag::err_hlsl_payload_access_qualifier_multiple_defined)
  9239. << "write";
  9240. return;
  9241. }
  9242. }
  9243. break;
  9244. }
  9245. default:
  9246. // Ignore all other annotations here.
  9247. break;
  9248. }
  9249. }
  9250. struct PayloadAccessQualifierInformation{
  9251. bool anyhit = false;
  9252. bool closesthit = false;
  9253. bool miss = false;
  9254. bool caller = false;
  9255. } readQualContains, writeQualContains;
  9256. auto collectInformationAboutShaderStages =
  9257. [&](hlsl::PayloadAccessAnnotation *annotation,
  9258. PayloadAccessQualifierInformation &info) {
  9259. for (auto shaderType : annotation->ShaderStages) {
  9260. if (shaderType == DXIL::PayloadAccessShaderStage::Anyhit)
  9261. info.anyhit = true;
  9262. else if (shaderType == DXIL::PayloadAccessShaderStage::Closesthit)
  9263. info.closesthit = true;
  9264. else if (shaderType == DXIL::PayloadAccessShaderStage::Miss)
  9265. info.miss = true;
  9266. else if (shaderType == DXIL::PayloadAccessShaderStage::Caller)
  9267. info.caller = true;
  9268. }
  9269. return true;
  9270. };
  9271. if (readAnnotation) {
  9272. if (!collectInformationAboutShaderStages(readAnnotation, readQualContains))
  9273. return;
  9274. }
  9275. if (writeAnnotation) {
  9276. if (!collectInformationAboutShaderStages(writeAnnotation, writeQualContains))
  9277. return;
  9278. }
  9279. if (writeAnnotation) {
  9280. // Note: keep the following two checks separated to diagnose both
  9281. // stages (closesthit and miss)
  9282. // If closesthit/miss writes a value the caller must consume it.
  9283. if (writeQualContains.miss) {
  9284. if (!readAnnotation || !readQualContains.caller) {
  9285. S.Diag(writeAnnotation->Loc,
  9286. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9287. << D.getIdentifier()
  9288. << "write"
  9289. << "miss"
  9290. << "consumer";
  9291. }
  9292. }
  9293. if (writeQualContains.closesthit) {
  9294. if (!readAnnotation || !readQualContains.caller) {
  9295. S.Diag(writeAnnotation->Loc,
  9296. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9297. << D.getIdentifier()
  9298. << "write"
  9299. << "closesthit"
  9300. << "consumer";
  9301. }
  9302. }
  9303. // If anyhit writes, we need at least one consumer
  9304. if (writeQualContains.anyhit && !readAnnotation) {
  9305. S.Diag(writeAnnotation->Loc,
  9306. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9307. << D.getIdentifier()
  9308. << "write"
  9309. << "anyhit"
  9310. << "consumer";
  9311. }
  9312. // If the caller writes, we need at least one consumer
  9313. if (writeQualContains.caller && !readAnnotation) {
  9314. S.Diag(writeAnnotation->Loc,
  9315. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9316. << D.getIdentifier()
  9317. << "write"
  9318. << "caller"
  9319. << "consumer";
  9320. }
  9321. }
  9322. // Validate the read qualifer if present.
  9323. if (readAnnotation) {
  9324. // Note: keep the following two checks separated to diagnose both
  9325. // stages (closesthit and miss)
  9326. // If closeshit/miss consume a value we need a producer.
  9327. // Valid producers are the caller and anyhit.
  9328. if (readQualContains.miss) {
  9329. if (!writeAnnotation ||
  9330. !(writeQualContains.anyhit || writeQualContains.caller)) {
  9331. S.Diag(readAnnotation->Loc,
  9332. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9333. << D.getIdentifier()
  9334. << "read"
  9335. << "miss"
  9336. << "producer";
  9337. }
  9338. }
  9339. // If closeshit/miss consume a value we need a producer.
  9340. // Valid producers are the caller and anyhit.
  9341. if (readQualContains.closesthit) {
  9342. if (!writeAnnotation ||
  9343. !(writeQualContains.anyhit || writeQualContains.caller)) {
  9344. S.Diag(readAnnotation->Loc,
  9345. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9346. << D.getIdentifier()
  9347. << "read"
  9348. << "closesthit"
  9349. << "producer";
  9350. }
  9351. }
  9352. // If anyhit consumes the value we need a producer.
  9353. // Valid producers are the caller and antoher anyhit.
  9354. if (readQualContains.anyhit) {
  9355. if (!writeAnnotation ||
  9356. !(writeQualContains.anyhit || writeQualContains.caller)) {
  9357. S.Diag(readAnnotation->Loc,
  9358. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9359. << D.getIdentifier()
  9360. << "read"
  9361. << "anyhit"
  9362. << "producer";
  9363. }
  9364. }
  9365. // If the caller consumes the value we need a valid producer.
  9366. if (readQualContains.caller && !writeAnnotation) {
  9367. S.Diag(readAnnotation->Loc,
  9368. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9369. << D.getIdentifier()
  9370. << "read"
  9371. << "caller"
  9372. << "producer";
  9373. }
  9374. }
  9375. }
  9376. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  9377. Sema& S,
  9378. std::vector<hlsl::UnusualAnnotation *>& annotations)
  9379. {
  9380. bool packoffsetOverriddenReported = false;
  9381. auto && iter = annotations.begin();
  9382. auto && end = annotations.end();
  9383. for (; iter != end; ++iter) {
  9384. switch ((*iter)->getKind()) {
  9385. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9386. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  9387. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  9388. if (!packoffsetOverriddenReported) {
  9389. auto newIter = iter;
  9390. ++newIter;
  9391. while (newIter != end) {
  9392. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  9393. if (other != nullptr &&
  9394. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  9395. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  9396. packoffsetOverriddenReported = true;
  9397. break;
  9398. }
  9399. ++newIter;
  9400. }
  9401. }
  9402. break;
  9403. }
  9404. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9405. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  9406. // Check whether this will conflict with other register assignments of the same type.
  9407. auto newIter = iter;
  9408. ++newIter;
  9409. while (newIter != end) {
  9410. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  9411. // Same register bank and profile, but different number.
  9412. if (other != nullptr &&
  9413. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  9414. other->RegisterType == registerAssignment->RegisterType &&
  9415. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  9416. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  9417. // Obvious conflict - report it up front.
  9418. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  9419. }
  9420. ++newIter;
  9421. }
  9422. break;
  9423. }
  9424. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9425. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  9426. // No common validation to be performed.
  9427. break;
  9428. }
  9429. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  9430. // Validation happens sperately
  9431. break;
  9432. }
  9433. }
  9434. }
  9435. }
  9436. clang::OverloadingResult
  9437. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  9438. clang::OverloadCandidateSet &set,
  9439. clang::OverloadCandidateSet::iterator &Best) {
  9440. return HLSLExternalSource::FromSema(&S)
  9441. ->GetBestViableFunction(Loc, set, Best);
  9442. }
  9443. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  9444. const InitializedEntity &Entity,
  9445. const InitializationKind &Kind,
  9446. MultiExprArg Args,
  9447. bool TopLevelOfInitList,
  9448. InitializationSequence *initSequence) {
  9449. return HLSLExternalSource::FromSema(self)
  9450. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  9451. }
  9452. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  9453. const clang::InitListExpr *InitList) {
  9454. unsigned totalSize = 0;
  9455. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  9456. const clang::Expr *EltInit = InitList->getInit(i);
  9457. QualType EltInitTy = EltInit->getType();
  9458. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  9459. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  9460. } else {
  9461. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  9462. }
  9463. }
  9464. return totalSize;
  9465. }
  9466. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  9467. _In_ clang::Sema* sema,
  9468. _In_ const clang::InitListExpr *InitList,
  9469. _In_ const clang::QualType EltTy) {
  9470. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  9471. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  9472. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  9473. if (totalSize > 0 && (totalSize % eltSize)==0) {
  9474. return totalSize / eltSize;
  9475. } else {
  9476. return 0;
  9477. }
  9478. }
  9479. bool hlsl::IsConversionToLessOrEqualElements(
  9480. _In_ clang::Sema* self,
  9481. const clang::ExprResult& sourceExpr,
  9482. const clang::QualType& targetType,
  9483. bool explicitConversion)
  9484. {
  9485. return HLSLExternalSource::FromSema(self)
  9486. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  9487. }
  9488. ExprResult hlsl::LookupMatrixMemberExprForHLSL(
  9489. Sema* self,
  9490. Expr& BaseExpr,
  9491. DeclarationName MemberName,
  9492. bool IsArrow,
  9493. SourceLocation OpLoc,
  9494. SourceLocation MemberLoc)
  9495. {
  9496. return HLSLExternalSource::FromSema(self)
  9497. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9498. }
  9499. ExprResult hlsl::LookupVectorMemberExprForHLSL(
  9500. Sema* self,
  9501. Expr& BaseExpr,
  9502. DeclarationName MemberName,
  9503. bool IsArrow,
  9504. SourceLocation OpLoc,
  9505. SourceLocation MemberLoc)
  9506. {
  9507. return HLSLExternalSource::FromSema(self)
  9508. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9509. }
  9510. ExprResult hlsl::LookupArrayMemberExprForHLSL(
  9511. Sema* self,
  9512. Expr& BaseExpr,
  9513. DeclarationName MemberName,
  9514. bool IsArrow,
  9515. SourceLocation OpLoc,
  9516. SourceLocation MemberLoc)
  9517. {
  9518. return HLSLExternalSource::FromSema(self)
  9519. ->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9520. }
  9521. bool hlsl::LookupRecordMemberExprForHLSL(
  9522. Sema* self,
  9523. Expr& BaseExpr,
  9524. DeclarationName MemberName,
  9525. bool IsArrow,
  9526. SourceLocation OpLoc,
  9527. SourceLocation MemberLoc,
  9528. ExprResult &result)
  9529. {
  9530. HLSLExternalSource *source = HLSLExternalSource::FromSema(self);
  9531. switch (source->GetTypeObjectKind(BaseExpr.getType())) {
  9532. case AR_TOBJ_MATRIX:
  9533. result = source->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9534. return true;
  9535. case AR_TOBJ_VECTOR:
  9536. result = source->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9537. return true;
  9538. case AR_TOBJ_ARRAY:
  9539. result = source->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9540. return true;
  9541. default:
  9542. return false;
  9543. }
  9544. return false;
  9545. }
  9546. clang::ExprResult hlsl::MaybeConvertMemberAccess(
  9547. _In_ clang::Sema* self,
  9548. _In_ clang::Expr* E)
  9549. {
  9550. return HLSLExternalSource::FromSema(self)->MaybeConvertMemberAccess(E);
  9551. }
  9552. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  9553. QualType DestType,
  9554. Sema::CheckedConversionKind CCK,
  9555. const SourceRange &OpRange, unsigned &msg,
  9556. CastKind &Kind, CXXCastPath &BasePath,
  9557. bool ListInitialization,
  9558. bool SuppressDiagnostics,
  9559. _Inout_opt_ StandardConversionSequence* standard)
  9560. {
  9561. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  9562. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  9563. SuppressDiagnostics, SuppressDiagnostics, standard);
  9564. }
  9565. clang::ExprResult hlsl::PerformHLSLConversion(
  9566. _In_ clang::Sema* self,
  9567. _In_ clang::Expr* From,
  9568. _In_ clang::QualType targetType,
  9569. _In_ const clang::StandardConversionSequence &SCS,
  9570. _In_ clang::Sema::CheckedConversionKind CCK)
  9571. {
  9572. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  9573. }
  9574. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  9575. _In_ clang::Sema* self,
  9576. _In_ clang::Expr* SrcExpr,
  9577. clang::QualType DestType)
  9578. {
  9579. return HLSLExternalSource::FromSema(self)
  9580. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  9581. }
  9582. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  9583. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  9584. {
  9585. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  9586. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  9587. if (hlslSource->Initialize(context)) {
  9588. context.setExternalSource(externalSource);
  9589. }
  9590. }
  9591. ////////////////////////////////////////////////////////////////////////////////
  9592. // FlattenedTypeIterator implementation //
  9593. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  9594. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  9595. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9596. {
  9597. if (pushTrackerForType(type, nullptr)) {
  9598. while (!m_typeTrackers.empty() && !considerLeaf())
  9599. consumeLeaf();
  9600. }
  9601. }
  9602. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  9603. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  9604. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9605. {
  9606. if (!args.empty()) {
  9607. MultiExprArg::iterator ii = args.begin();
  9608. MultiExprArg::iterator ie = args.end();
  9609. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  9610. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9611. if (!considerLeaf()) {
  9612. m_typeTrackers.clear();
  9613. }
  9614. }
  9615. }
  9616. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  9617. QualType FlattenedTypeIterator::getCurrentElement() const
  9618. {
  9619. return m_typeTrackers.back().Type;
  9620. }
  9621. /// <summary>Get the number of repeated current elements.</summary>
  9622. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  9623. {
  9624. const FlattenedTypeTracker& back = m_typeTrackers.back();
  9625. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  9626. }
  9627. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  9628. bool FlattenedTypeIterator::hasCurrentElement() const
  9629. {
  9630. return m_typeTrackers.size() > 0;
  9631. }
  9632. /// <summary>Consumes count elements on this iterator.</summary>
  9633. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  9634. {
  9635. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9636. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  9637. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9638. if (tracker.IterKind == FK_IncompleteArray)
  9639. {
  9640. tracker.Count += count;
  9641. m_springLoaded = true;
  9642. }
  9643. else
  9644. {
  9645. tracker.Count -= count;
  9646. m_springLoaded = false;
  9647. if (m_typeTrackers.back().Count == 0)
  9648. {
  9649. advanceLeafTracker();
  9650. }
  9651. }
  9652. }
  9653. unsigned int FlattenedTypeIterator::countRemaining()
  9654. {
  9655. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  9656. size_t result = 0;
  9657. while (hasCurrentElement() && !m_springLoaded)
  9658. {
  9659. size_t pending = getCurrentElementSize();
  9660. result += pending;
  9661. advanceCurrentElement(pending);
  9662. }
  9663. return result;
  9664. }
  9665. void FlattenedTypeIterator::advanceLeafTracker()
  9666. {
  9667. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9668. for (;;)
  9669. {
  9670. consumeLeaf();
  9671. if (m_typeTrackers.empty()) {
  9672. return;
  9673. }
  9674. if (considerLeaf()) {
  9675. return;
  9676. }
  9677. }
  9678. }
  9679. bool FlattenedTypeIterator::considerLeaf()
  9680. {
  9681. if (m_typeTrackers.empty()) {
  9682. return false;
  9683. }
  9684. m_typeDepth++;
  9685. if (m_typeDepth > MaxTypeDepth) {
  9686. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  9687. m_typeTrackers.clear();
  9688. m_typeDepth--;
  9689. return false;
  9690. }
  9691. bool result = false;
  9692. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9693. tracker.IsConsidered = true;
  9694. switch (tracker.IterKind) {
  9695. case FlattenedIterKind::FK_Expressions:
  9696. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  9697. result = considerLeaf();
  9698. }
  9699. break;
  9700. case FlattenedIterKind::FK_Fields:
  9701. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  9702. result = considerLeaf();
  9703. }
  9704. break;
  9705. case FlattenedIterKind::FK_Bases:
  9706. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  9707. result = considerLeaf();
  9708. }
  9709. break;
  9710. case FlattenedIterKind::FK_IncompleteArray:
  9711. m_springLoaded = true; // fall through.
  9712. default:
  9713. case FlattenedIterKind::FK_Simple: {
  9714. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  9715. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  9716. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT &&
  9717. objectKind != ArTypeObjectKind::AR_TOBJ_STRING) {
  9718. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  9719. result = considerLeaf();
  9720. }
  9721. } else {
  9722. result = true;
  9723. }
  9724. }
  9725. }
  9726. m_typeDepth--;
  9727. return result;
  9728. }
  9729. void FlattenedTypeIterator::consumeLeaf()
  9730. {
  9731. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  9732. for (;;) {
  9733. if (m_typeTrackers.empty()) {
  9734. return;
  9735. }
  9736. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9737. // Reach a leaf which is not considered before.
  9738. // Stop here.
  9739. if (!tracker.IsConsidered) {
  9740. break;
  9741. }
  9742. switch (tracker.IterKind) {
  9743. case FlattenedIterKind::FK_Expressions:
  9744. ++tracker.CurrentExpr;
  9745. if (tracker.CurrentExpr == tracker.EndExpr) {
  9746. m_typeTrackers.pop_back();
  9747. topConsumed = false;
  9748. } else {
  9749. return;
  9750. }
  9751. break;
  9752. case FlattenedIterKind::FK_Fields:
  9753. ++tracker.CurrentField;
  9754. if (tracker.CurrentField == tracker.EndField) {
  9755. m_typeTrackers.pop_back();
  9756. topConsumed = false;
  9757. } else {
  9758. return;
  9759. }
  9760. break;
  9761. case FlattenedIterKind::FK_Bases:
  9762. ++tracker.CurrentBase;
  9763. if (tracker.CurrentBase == tracker.EndBase) {
  9764. m_typeTrackers.pop_back();
  9765. topConsumed = false;
  9766. } else {
  9767. return;
  9768. }
  9769. break;
  9770. case FlattenedIterKind::FK_IncompleteArray:
  9771. if (m_draining) {
  9772. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  9773. m_incompleteCount = tracker.Count;
  9774. m_typeTrackers.pop_back();
  9775. }
  9776. return;
  9777. default:
  9778. case FlattenedIterKind::FK_Simple: {
  9779. m_springLoaded = false;
  9780. if (!topConsumed) {
  9781. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  9782. --tracker.Count;
  9783. }
  9784. else {
  9785. topConsumed = false;
  9786. }
  9787. if (tracker.Count == 0) {
  9788. m_typeTrackers.pop_back();
  9789. } else {
  9790. return;
  9791. }
  9792. }
  9793. }
  9794. }
  9795. }
  9796. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  9797. {
  9798. Expr* e = *expression;
  9799. Stmt::StmtClass expressionClass = e->getStmtClass();
  9800. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  9801. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  9802. if (initExpr->getNumInits() == 0) {
  9803. return false;
  9804. }
  9805. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  9806. MultiExprArg::iterator ii = inits.begin();
  9807. MultiExprArg::iterator ie = inits.end();
  9808. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  9809. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9810. return true;
  9811. }
  9812. return pushTrackerForType(e->getType(), expression);
  9813. }
  9814. // TODO: improve this to provide a 'peek' at intermediate types,
  9815. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  9816. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  9817. {
  9818. if (type->isVoidType()) {
  9819. return false;
  9820. }
  9821. if (type->isFunctionType()) {
  9822. return false;
  9823. }
  9824. if (m_firstType.isNull()) {
  9825. m_firstType = type;
  9826. }
  9827. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  9828. QualType elementType;
  9829. unsigned int elementCount;
  9830. const RecordType* recordType;
  9831. RecordDecl::field_iterator fi, fe;
  9832. switch (objectKind)
  9833. {
  9834. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  9835. // TODO: handle multi-dimensional arrays
  9836. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  9837. elementCount = GetArraySize(type);
  9838. if (elementCount == 0) {
  9839. if (type->isIncompleteArrayType()) {
  9840. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  9841. return true;
  9842. }
  9843. return false;
  9844. }
  9845. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9846. elementType, elementCount, nullptr));
  9847. return true;
  9848. case ArTypeObjectKind::AR_TOBJ_BASIC:
  9849. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  9850. return true;
  9851. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  9852. recordType = type->getAsStructureType();
  9853. if (recordType == nullptr)
  9854. recordType = dyn_cast<RecordType>(type.getTypePtr());
  9855. fi = recordType->getDecl()->field_begin();
  9856. fe = recordType->getDecl()->field_end();
  9857. bool bAddTracker = false;
  9858. // Skip empty struct.
  9859. if (fi != fe) {
  9860. m_typeTrackers.push_back(
  9861. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9862. type = (*fi)->getType();
  9863. bAddTracker = true;
  9864. }
  9865. if (CXXRecordDecl *cxxRecordDecl =
  9866. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  9867. // We'll error elsewhere if the record has no definition,
  9868. // just don't attempt to use it.
  9869. if (cxxRecordDecl->hasDefinition()) {
  9870. CXXRecordDecl::base_class_iterator bi, be;
  9871. bi = cxxRecordDecl->bases_begin();
  9872. be = cxxRecordDecl->bases_end();
  9873. if (bi != be) {
  9874. // Add type tracker for base.
  9875. // Add base after child to make sure base considered first.
  9876. m_typeTrackers.push_back(
  9877. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  9878. bAddTracker = true;
  9879. }
  9880. }
  9881. }
  9882. return bAddTracker;
  9883. }
  9884. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  9885. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9886. m_source.GetMatrixOrVectorElementType(type),
  9887. GetElementCount(type), nullptr));
  9888. return true;
  9889. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  9890. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9891. m_source.GetMatrixOrVectorElementType(type),
  9892. GetHLSLVecSize(type), nullptr));
  9893. return true;
  9894. case ArTypeObjectKind::AR_TOBJ_OBJECT: {
  9895. if (m_source.IsSubobjectType(type)) {
  9896. // subobjects are initialized with initialization lists
  9897. recordType = type->getAsStructureType();
  9898. fi = recordType->getDecl()->field_begin();
  9899. fe = recordType->getDecl()->field_end();
  9900. m_typeTrackers.push_back(
  9901. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9902. return true;
  9903. }
  9904. else {
  9905. // Object have no sub-types.
  9906. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9907. type.getCanonicalType(), 1, expression));
  9908. return true;
  9909. }
  9910. }
  9911. case ArTypeObjectKind::AR_TOBJ_STRING: {
  9912. // Strings have no sub-types.
  9913. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9914. type.getCanonicalType(), 1, expression));
  9915. return true;
  9916. }
  9917. default:
  9918. DXASSERT(false, "unreachable");
  9919. return false;
  9920. }
  9921. }
  9922. FlattenedTypeIterator::ComparisonResult
  9923. FlattenedTypeIterator::CompareIterators(
  9924. HLSLExternalSource& source,
  9925. SourceLocation loc,
  9926. FlattenedTypeIterator& leftIter,
  9927. FlattenedTypeIterator& rightIter)
  9928. {
  9929. FlattenedTypeIterator::ComparisonResult result;
  9930. result.LeftCount = 0;
  9931. result.RightCount = 0;
  9932. result.AreElementsEqual = true; // Until proven otherwise.
  9933. result.CanConvertElements = true; // Until proven otherwise.
  9934. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  9935. {
  9936. Expr* actualExpr = rightIter.getExprOrNull();
  9937. bool hasExpr = actualExpr != nullptr;
  9938. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  9939. StandardConversionSequence standard;
  9940. ExprResult convertedExpr;
  9941. if (!source.CanConvert(loc,
  9942. hasExpr ? actualExpr : &scratchExpr,
  9943. leftIter.getCurrentElement(),
  9944. ExplicitConversionFalse,
  9945. nullptr,
  9946. &standard)) {
  9947. result.AreElementsEqual = false;
  9948. result.CanConvertElements = false;
  9949. break;
  9950. }
  9951. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  9952. {
  9953. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  9954. leftIter.getCurrentElement(),
  9955. standard,
  9956. Sema::AA_Casting,
  9957. Sema::CCK_ImplicitConversion);
  9958. }
  9959. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  9960. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  9961. {
  9962. result.AreElementsEqual = false;
  9963. }
  9964. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  9965. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  9966. // If we need to apply conversions to the expressions, then advance a single element.
  9967. if (hasExpr && convertedExpr.isUsable()) {
  9968. rightIter.replaceExpr(convertedExpr.get());
  9969. advance = 1;
  9970. }
  9971. // If both elements are unbound arrays, break out or we'll never finish
  9972. if (leftIter.getCurrentElementKind() == FK_IncompleteArray &&
  9973. rightIter.getCurrentElementKind() == FK_IncompleteArray)
  9974. break;
  9975. leftIter.advanceCurrentElement(advance);
  9976. rightIter.advanceCurrentElement(advance);
  9977. result.LeftCount += advance;
  9978. result.RightCount += advance;
  9979. }
  9980. result.LeftCount += leftIter.countRemaining();
  9981. result.RightCount += rightIter.countRemaining();
  9982. return result;
  9983. }
  9984. FlattenedTypeIterator::ComparisonResult
  9985. FlattenedTypeIterator::CompareTypes(
  9986. HLSLExternalSource& source,
  9987. SourceLocation leftLoc, SourceLocation rightLoc,
  9988. QualType left, QualType right)
  9989. {
  9990. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9991. FlattenedTypeIterator rightIter(rightLoc, right, source);
  9992. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9993. }
  9994. FlattenedTypeIterator::ComparisonResult
  9995. FlattenedTypeIterator::CompareTypesForInit(
  9996. HLSLExternalSource& source, QualType left, MultiExprArg args,
  9997. SourceLocation leftLoc, SourceLocation rightLoc)
  9998. {
  9999. FlattenedTypeIterator leftIter(leftLoc, left, source);
  10000. FlattenedTypeIterator rightIter(rightLoc, args, source);
  10001. return CompareIterators(source, leftLoc, leftIter, rightIter);
  10002. }
  10003. ////////////////////////////////////////////////////////////////////////////////
  10004. // Attribute processing support. //
  10005. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  10006. {
  10007. int64_t value = 0;
  10008. if (Attr.getNumArgs() > index)
  10009. {
  10010. Expr *E = nullptr;
  10011. if (!Attr.isArgExpr(index)) {
  10012. // For case arg is constant variable.
  10013. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  10014. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  10015. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  10016. Sema::LookupNameKind::LookupOrdinaryName));
  10017. if (!decl) {
  10018. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  10019. return value;
  10020. }
  10021. Expr *init = decl->getInit();
  10022. if (!init) {
  10023. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  10024. return value;
  10025. }
  10026. E = init;
  10027. } else
  10028. E = Attr.getArgAsExpr(index);
  10029. clang::APValue ArgNum;
  10030. bool displayError = false;
  10031. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  10032. {
  10033. displayError = true;
  10034. }
  10035. else
  10036. {
  10037. if (ArgNum.isInt())
  10038. {
  10039. value = ArgNum.getInt().getSExtValue();
  10040. }
  10041. else if (ArgNum.isFloat())
  10042. {
  10043. llvm::APSInt floatInt;
  10044. bool isPrecise;
  10045. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  10046. {
  10047. value = floatInt.getSExtValue();
  10048. }
  10049. else
  10050. {
  10051. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  10052. }
  10053. }
  10054. else
  10055. {
  10056. displayError = true;
  10057. }
  10058. if (value < 0)
  10059. {
  10060. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  10061. }
  10062. }
  10063. if (displayError)
  10064. {
  10065. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  10066. << Attr.getName() << AANT_ArgumentIntegerConstant
  10067. << E->getSourceRange();
  10068. }
  10069. }
  10070. return (int)value;
  10071. }
  10072. // TODO: support float arg directly.
  10073. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  10074. unsigned index = 0) {
  10075. int value = 0;
  10076. if (Attr.getNumArgs() > index) {
  10077. Expr *E = Attr.getArgAsExpr(index);
  10078. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  10079. llvm::APFloat flV = FL->getValue();
  10080. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  10081. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  10082. value = intV.getLimitedValue();
  10083. } else {
  10084. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  10085. value = intV.getLimitedValue();
  10086. }
  10087. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  10088. llvm::APInt intV =
  10089. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  10090. value = intV.getLimitedValue();
  10091. } else {
  10092. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  10093. << Attr.getName();
  10094. }
  10095. }
  10096. return value;
  10097. }
  10098. template <typename AttrType, typename EnumType,
  10099. bool (*ConvertStrToEnumType)(StringRef, EnumType &)>
  10100. static EnumType ValidateAttributeEnumArg(Sema &S, const AttributeList &Attr,
  10101. EnumType defaultValue,
  10102. unsigned index = 0) {
  10103. EnumType value(defaultValue);
  10104. StringRef Str = "";
  10105. SourceLocation ArgLoc;
  10106. if (Attr.getNumArgs() > index) {
  10107. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
  10108. return value;
  10109. if (!ConvertStrToEnumType(Str, value)) {
  10110. S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
  10111. << Attr.getName() << Str << ArgLoc;
  10112. }
  10113. return value;
  10114. }
  10115. return value;
  10116. }
  10117. static Stmt* IgnoreParensAndDecay(Stmt* S)
  10118. {
  10119. for (;;)
  10120. {
  10121. switch (S->getStmtClass())
  10122. {
  10123. case Stmt::ParenExprClass:
  10124. S = cast<ParenExpr>(S)->getSubExpr();
  10125. break;
  10126. case Stmt::ImplicitCastExprClass:
  10127. {
  10128. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  10129. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  10130. castExpr->getCastKind() != CK_NoOp &&
  10131. castExpr->getCastKind() != CK_LValueToRValue)
  10132. {
  10133. return S;
  10134. }
  10135. S = castExpr->getSubExpr();
  10136. }
  10137. break;
  10138. default:
  10139. return S;
  10140. }
  10141. }
  10142. }
  10143. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  10144. {
  10145. DXASSERT_NOMSG(E != nullptr);
  10146. Expr* subscriptExpr = E->getIdx();
  10147. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  10148. if (subscriptExpr == nullptr ||
  10149. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  10150. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  10151. {
  10152. S.Diag(
  10153. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  10154. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  10155. return nullptr;
  10156. }
  10157. return E->getBase();
  10158. }
  10159. static bool IsValidClipPlaneDecl(Decl* D)
  10160. {
  10161. Decl::Kind kind = D->getKind();
  10162. if (kind == Decl::Var)
  10163. {
  10164. VarDecl* varDecl = cast<VarDecl>(D);
  10165. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  10166. varDecl->getType().isConstQualified())
  10167. {
  10168. return false;
  10169. }
  10170. return true;
  10171. }
  10172. else if (kind == Decl::Field)
  10173. {
  10174. return true;
  10175. }
  10176. return false;
  10177. }
  10178. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  10179. {
  10180. Stmt* cursor = E;
  10181. // clip plane expressions are a linear path, so no need to traverse the tree here.
  10182. while (cursor != nullptr)
  10183. {
  10184. bool supported = true;
  10185. cursor = IgnoreParensAndDecay(cursor);
  10186. switch (cursor->getStmtClass())
  10187. {
  10188. case Stmt::ArraySubscriptExprClass:
  10189. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  10190. if (cursor == nullptr)
  10191. {
  10192. // nullptr indicates failure, and the error message has already been printed out
  10193. return nullptr;
  10194. }
  10195. break;
  10196. case Stmt::DeclRefExprClass:
  10197. {
  10198. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  10199. Decl* decl = declRef->getDecl();
  10200. supported = IsValidClipPlaneDecl(decl);
  10201. cursor = supported ? nullptr : cursor;
  10202. }
  10203. break;
  10204. case Stmt::MemberExprClass:
  10205. {
  10206. MemberExpr* member = cast<MemberExpr>(cursor);
  10207. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  10208. cursor = supported ? member->getBase() : cursor;
  10209. }
  10210. break;
  10211. default:
  10212. supported = false;
  10213. break;
  10214. }
  10215. if (!supported)
  10216. {
  10217. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  10218. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  10219. return nullptr;
  10220. }
  10221. }
  10222. // Validate that the type is a float4.
  10223. QualType expressionType = E->getType();
  10224. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  10225. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  10226. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  10227. {
  10228. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  10229. return nullptr;
  10230. }
  10231. return E;
  10232. }
  10233. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  10234. {
  10235. Expr* clipExprs[6];
  10236. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  10237. {
  10238. if (A.getNumArgs() <= index)
  10239. {
  10240. clipExprs[index] = nullptr;
  10241. continue;
  10242. }
  10243. Expr *E = A.getArgAsExpr(index);
  10244. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  10245. }
  10246. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  10247. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  10248. A.getAttributeSpellingListIndex());
  10249. }
  10250. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  10251. {
  10252. int argValue = ValidateAttributeIntArg(S, Attr);
  10253. // Default value is 0 (full unroll).
  10254. if (Attr.getNumArgs() == 0) argValue = 0;
  10255. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  10256. argValue, Attr.getAttributeSpellingListIndex());
  10257. }
  10258. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  10259. {
  10260. Stmt::StmtClass stClass = St->getStmtClass();
  10261. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  10262. {
  10263. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  10264. << Attr.getName();
  10265. }
  10266. }
  10267. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  10268. {
  10269. Stmt::StmtClass stClass = St->getStmtClass();
  10270. if (stClass != Stmt::SwitchStmtClass)
  10271. {
  10272. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  10273. << Attr.getName();
  10274. }
  10275. }
  10276. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  10277. {
  10278. Stmt::StmtClass stClass = St->getStmtClass();
  10279. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  10280. {
  10281. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  10282. << Attr.getName();
  10283. }
  10284. }
  10285. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  10286. {
  10287. // values is an optional comma-separated list of potential values.
  10288. if (A.getNumArgs() <= index)
  10289. return StringRef();
  10290. Expr* E = A.getArgAsExpr(index);
  10291. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  10292. {
  10293. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  10294. << A.getName();
  10295. return StringRef();
  10296. }
  10297. StringLiteral* sl = cast<StringLiteral>(E);
  10298. StringRef result = sl->getString();
  10299. // Return result with no additional validation.
  10300. if (values == nullptr)
  10301. {
  10302. return result;
  10303. }
  10304. const char* value = values;
  10305. while (*value != '\0')
  10306. {
  10307. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  10308. // Look for a match.
  10309. const char* argData = result.data();
  10310. size_t argDataLen = result.size();
  10311. while (argDataLen != 0 && *argData == *value && *value)
  10312. {
  10313. ++argData;
  10314. ++value;
  10315. --argDataLen;
  10316. }
  10317. // Match found if every input character matched.
  10318. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  10319. {
  10320. return result;
  10321. }
  10322. // Move to next separator.
  10323. while (*value != '\0' && *value != ',')
  10324. {
  10325. ++value;
  10326. }
  10327. // Move to the start of the next item if any.
  10328. if (*value == ',') value++;
  10329. }
  10330. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  10331. // No match found.
  10332. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  10333. << A.getName() << values;
  10334. return StringRef();
  10335. }
  10336. static
  10337. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  10338. {
  10339. if (D->isFunctionOrFunctionTemplate())
  10340. {
  10341. return true;
  10342. }
  10343. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  10344. return false;
  10345. }
  10346. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  10347. {
  10348. DXASSERT_NOMSG(D != nullptr);
  10349. DXASSERT_NOMSG(!A.isInvalid());
  10350. Attr* declAttr = nullptr;
  10351. Handled = true;
  10352. switch (A.getKind())
  10353. {
  10354. case AttributeList::AT_HLSLIn:
  10355. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  10356. A.getAttributeSpellingListIndex());
  10357. break;
  10358. case AttributeList::AT_HLSLOut:
  10359. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  10360. A.getAttributeSpellingListIndex());
  10361. break;
  10362. case AttributeList::AT_HLSLInOut:
  10363. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  10364. A.getAttributeSpellingListIndex());
  10365. break;
  10366. case AttributeList::AT_HLSLNoInterpolation:
  10367. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  10368. A.getAttributeSpellingListIndex());
  10369. break;
  10370. case AttributeList::AT_HLSLLinear:
  10371. case AttributeList::AT_HLSLCenter:
  10372. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  10373. A.getAttributeSpellingListIndex());
  10374. break;
  10375. case AttributeList::AT_HLSLNoPerspective:
  10376. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  10377. A.getAttributeSpellingListIndex());
  10378. break;
  10379. case AttributeList::AT_HLSLSample:
  10380. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  10381. A.getAttributeSpellingListIndex());
  10382. break;
  10383. case AttributeList::AT_HLSLCentroid:
  10384. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  10385. A.getAttributeSpellingListIndex());
  10386. break;
  10387. case AttributeList::AT_HLSLPrecise:
  10388. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  10389. A.getAttributeSpellingListIndex());
  10390. break;
  10391. case AttributeList::AT_HLSLShared:
  10392. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  10393. A.getAttributeSpellingListIndex());
  10394. break;
  10395. case AttributeList::AT_HLSLGroupShared:
  10396. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  10397. A.getAttributeSpellingListIndex());
  10398. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  10399. VD->setType(S.Context.getAddrSpaceQualType(VD->getType(), DXIL::kTGSMAddrSpace));
  10400. }
  10401. break;
  10402. case AttributeList::AT_HLSLUniform:
  10403. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  10404. A.getAttributeSpellingListIndex());
  10405. break;
  10406. case AttributeList::AT_HLSLColumnMajor:
  10407. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  10408. A.getAttributeSpellingListIndex());
  10409. break;
  10410. case AttributeList::AT_HLSLRowMajor:
  10411. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  10412. A.getAttributeSpellingListIndex());
  10413. break;
  10414. case AttributeList::AT_HLSLUnorm:
  10415. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  10416. A.getAttributeSpellingListIndex());
  10417. break;
  10418. case AttributeList::AT_HLSLSnorm:
  10419. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  10420. A.getAttributeSpellingListIndex());
  10421. break;
  10422. case AttributeList::AT_HLSLPoint:
  10423. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  10424. A.getAttributeSpellingListIndex());
  10425. break;
  10426. case AttributeList::AT_HLSLLine:
  10427. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  10428. A.getAttributeSpellingListIndex());
  10429. break;
  10430. case AttributeList::AT_HLSLLineAdj:
  10431. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  10432. A.getAttributeSpellingListIndex());
  10433. break;
  10434. case AttributeList::AT_HLSLTriangle:
  10435. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  10436. A.getAttributeSpellingListIndex());
  10437. break;
  10438. case AttributeList::AT_HLSLTriangleAdj:
  10439. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  10440. A.getAttributeSpellingListIndex());
  10441. break;
  10442. case AttributeList::AT_HLSLGloballyCoherent:
  10443. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  10444. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10445. break;
  10446. case AttributeList::AT_HLSLIndices:
  10447. declAttr = ::new (S.Context) HLSLIndicesAttr(
  10448. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10449. break;
  10450. case AttributeList::AT_HLSLVertices:
  10451. declAttr = ::new (S.Context) HLSLVerticesAttr(
  10452. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10453. break;
  10454. case AttributeList::AT_HLSLPrimitives:
  10455. declAttr = ::new (S.Context) HLSLPrimitivesAttr(
  10456. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10457. break;
  10458. case AttributeList::AT_HLSLPayload:
  10459. declAttr = ::new (S.Context) HLSLPayloadAttr(
  10460. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10461. break;
  10462. case AttributeList::AT_HLSLRayPayload:
  10463. declAttr = ::new (S.Context) HLSLRayPayloadAttr(
  10464. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10465. break;
  10466. default:
  10467. Handled = false;
  10468. break;
  10469. }
  10470. if (declAttr != nullptr)
  10471. {
  10472. DXASSERT_NOMSG(Handled);
  10473. D->addAttr(declAttr);
  10474. return;
  10475. }
  10476. Handled = true;
  10477. switch (A.getKind())
  10478. {
  10479. // These apply to statements, not declarations. The warning messages clarify this properly.
  10480. case AttributeList::AT_HLSLUnroll:
  10481. case AttributeList::AT_HLSLAllowUAVCondition:
  10482. case AttributeList::AT_HLSLLoop:
  10483. case AttributeList::AT_HLSLFastOpt:
  10484. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  10485. << A.getName();
  10486. return;
  10487. case AttributeList::AT_HLSLBranch:
  10488. case AttributeList::AT_HLSLFlatten:
  10489. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  10490. << A.getName();
  10491. return;
  10492. case AttributeList::AT_HLSLForceCase:
  10493. case AttributeList::AT_HLSLCall:
  10494. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  10495. << A.getName();
  10496. return;
  10497. // These are the cases that actually apply to declarations.
  10498. case AttributeList::AT_HLSLClipPlanes:
  10499. declAttr = HandleClipPlanes(S, A);
  10500. break;
  10501. case AttributeList::AT_HLSLDomain:
  10502. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  10503. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  10504. break;
  10505. case AttributeList::AT_HLSLEarlyDepthStencil:
  10506. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10507. break;
  10508. case AttributeList::AT_HLSLInstance:
  10509. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  10510. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10511. break;
  10512. case AttributeList::AT_HLSLMaxTessFactor:
  10513. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  10514. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  10515. break;
  10516. case AttributeList::AT_HLSLNumThreads:
  10517. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  10518. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  10519. A.getAttributeSpellingListIndex());
  10520. break;
  10521. case AttributeList::AT_HLSLRootSignature:
  10522. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  10523. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  10524. A.getAttributeSpellingListIndex());
  10525. break;
  10526. case AttributeList::AT_HLSLOutputControlPoints:
  10527. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  10528. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10529. break;
  10530. case AttributeList::AT_HLSLOutputTopology:
  10531. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  10532. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  10533. break;
  10534. case AttributeList::AT_HLSLPartitioning:
  10535. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  10536. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  10537. break;
  10538. case AttributeList::AT_HLSLPatchConstantFunc:
  10539. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  10540. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  10541. break;
  10542. case AttributeList::AT_HLSLShader:
  10543. declAttr = ::new (S.Context) HLSLShaderAttr(
  10544. A.getRange(), S.Context,
  10545. ValidateAttributeStringArg(
  10546. S, A,
  10547. "compute,vertex,pixel,hull,domain,geometry,raygeneration,"
  10548. "intersection,anyhit,closesthit,miss,callable,mesh,amplification"),
  10549. A.getAttributeSpellingListIndex());
  10550. break;
  10551. case AttributeList::AT_HLSLMaxVertexCount:
  10552. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  10553. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10554. break;
  10555. case AttributeList::AT_HLSLExperimental:
  10556. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  10557. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  10558. A.getAttributeSpellingListIndex());
  10559. break;
  10560. case AttributeList::AT_NoInline:
  10561. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10562. break;
  10563. case AttributeList::AT_HLSLExport:
  10564. declAttr = ::new (S.Context) HLSLExportAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10565. break;
  10566. case AttributeList::AT_HLSLWaveSensitive:
  10567. declAttr = ::new (S.Context) HLSLWaveSensitiveAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10568. break;
  10569. case AttributeList::AT_HLSLWaveSize:
  10570. declAttr = ::new (S.Context) HLSLWaveSizeAttr(A.getRange(), S.Context,
  10571. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10572. break;
  10573. default:
  10574. Handled = false;
  10575. break; // SPIRV Change: was return;
  10576. }
  10577. if (declAttr != nullptr)
  10578. {
  10579. DXASSERT_NOMSG(Handled);
  10580. D->addAttr(declAttr);
  10581. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  10582. // and prevent code generation.
  10583. ValidateAttributeTargetIsFunction(S, D, A);
  10584. return; // SPIRV Change
  10585. }
  10586. // SPIRV Change Starts
  10587. Handled = true;
  10588. switch (A.getKind())
  10589. {
  10590. case AttributeList::AT_VKBuiltIn:
  10591. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  10592. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation,BaseVertex,BaseInstance,DrawIndex,DeviceIndex,ViewportMaskNV"),
  10593. A.getAttributeSpellingListIndex());
  10594. break;
  10595. case AttributeList::AT_VKLocation:
  10596. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  10597. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10598. break;
  10599. case AttributeList::AT_VKIndex:
  10600. declAttr = ::new (S.Context) VKIndexAttr(A.getRange(), S.Context,
  10601. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10602. break;
  10603. case AttributeList::AT_VKBinding:
  10604. declAttr = ::new (S.Context) VKBindingAttr(
  10605. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10606. A.getNumArgs() < 2 ? INT_MIN : ValidateAttributeIntArg(S, A, 1),
  10607. A.getAttributeSpellingListIndex());
  10608. break;
  10609. case AttributeList::AT_VKCounterBinding:
  10610. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  10611. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10612. break;
  10613. case AttributeList::AT_VKPushConstant:
  10614. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  10615. A.getAttributeSpellingListIndex());
  10616. break;
  10617. case AttributeList::AT_VKOffset:
  10618. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  10619. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10620. break;
  10621. case AttributeList::AT_VKImageFormat: {
  10622. VKImageFormatAttr::ImageFormatType Kind = ValidateAttributeEnumArg<
  10623. VKImageFormatAttr, VKImageFormatAttr::ImageFormatType,
  10624. VKImageFormatAttr::ConvertStrToImageFormatType>(
  10625. S, A, VKImageFormatAttr::ImageFormatType::unknown);
  10626. declAttr = ::new (S.Context) VKImageFormatAttr(
  10627. A.getRange(), S.Context, Kind, A.getAttributeSpellingListIndex());
  10628. break;
  10629. }
  10630. case AttributeList::AT_VKInputAttachmentIndex:
  10631. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  10632. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10633. A.getAttributeSpellingListIndex());
  10634. break;
  10635. case AttributeList::AT_VKConstantId:
  10636. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  10637. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10638. break;
  10639. case AttributeList::AT_VKPostDepthCoverage:
  10640. declAttr = ::new (S.Context) VKPostDepthCoverageAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10641. break;
  10642. case AttributeList::AT_VKShaderRecordNV:
  10643. declAttr = ::new (S.Context) VKShaderRecordNVAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10644. break;
  10645. case AttributeList::AT_VKShaderRecordEXT:
  10646. declAttr = ::new (S.Context) VKShaderRecordEXTAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10647. break;
  10648. default:
  10649. Handled = false;
  10650. return;
  10651. }
  10652. if (declAttr != nullptr)
  10653. {
  10654. DXASSERT_NOMSG(Handled);
  10655. D->addAttr(declAttr);
  10656. }
  10657. // SPIRV Change Ends
  10658. }
  10659. /// <summary>Processes an attribute for a statement.</summary>
  10660. /// <param name="S">Sema with context.</param>
  10661. /// <param name="St">Statement annotated.</param>
  10662. /// <param name="A">Single parsed attribute to process.</param>
  10663. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  10664. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  10665. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  10666. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  10667. {
  10668. // | Construct | Allowed Attributes |
  10669. // +------------------+--------------------------------------------+
  10670. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  10671. // | if | branch, flatten |
  10672. // | switch | branch, flatten, forcecase, call |
  10673. Attr * result = nullptr;
  10674. Handled = true;
  10675. switch (A.getKind())
  10676. {
  10677. case AttributeList::AT_HLSLUnroll:
  10678. ValidateAttributeOnLoop(S, St, A);
  10679. result = HandleUnrollAttribute(S, A);
  10680. break;
  10681. case AttributeList::AT_HLSLAllowUAVCondition:
  10682. ValidateAttributeOnLoop(S, St, A);
  10683. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  10684. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10685. break;
  10686. case AttributeList::AT_HLSLLoop:
  10687. ValidateAttributeOnLoop(S, St, A);
  10688. result = ::new (S.Context) HLSLLoopAttr(
  10689. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10690. break;
  10691. case AttributeList::AT_HLSLFastOpt:
  10692. ValidateAttributeOnLoop(S, St, A);
  10693. result = ::new (S.Context) HLSLFastOptAttr(
  10694. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10695. break;
  10696. case AttributeList::AT_HLSLBranch:
  10697. ValidateAttributeOnSwitchOrIf(S, St, A);
  10698. result = ::new (S.Context) HLSLBranchAttr(
  10699. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10700. break;
  10701. case AttributeList::AT_HLSLFlatten:
  10702. ValidateAttributeOnSwitchOrIf(S, St, A);
  10703. result = ::new (S.Context) HLSLFlattenAttr(
  10704. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10705. break;
  10706. case AttributeList::AT_HLSLForceCase:
  10707. ValidateAttributeOnSwitch(S, St, A);
  10708. result = ::new (S.Context) HLSLForceCaseAttr(
  10709. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10710. break;
  10711. case AttributeList::AT_HLSLCall:
  10712. ValidateAttributeOnSwitch(S, St, A);
  10713. result = ::new (S.Context) HLSLCallAttr(
  10714. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10715. break;
  10716. default:
  10717. Handled = false;
  10718. break;
  10719. }
  10720. return result;
  10721. }
  10722. ////////////////////////////////////////////////////////////////////////////////
  10723. // Implementation of Sema members. //
  10724. Decl* Sema::ActOnStartHLSLBuffer(
  10725. Scope* bufferScope,
  10726. bool cbuffer, SourceLocation KwLoc,
  10727. IdentifierInfo *Ident, SourceLocation IdentLoc,
  10728. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  10729. SourceLocation LBrace)
  10730. {
  10731. // For anonymous namespace, take the location of the left brace.
  10732. DeclContext* lexicalParent = getCurLexicalContext();
  10733. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10734. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  10735. Ident, IdentLoc, BufferAttributes, LBrace);
  10736. // Keep track of the currently active buffer.
  10737. HLSLBuffers.push_back(result);
  10738. // Validate unusual annotations and emit diagnostics.
  10739. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  10740. auto && unusualIter = BufferAttributes.begin();
  10741. auto && unusualEnd = BufferAttributes.end();
  10742. char expectedRegisterType = cbuffer ? 'b' : 't';
  10743. for (; unusualIter != unusualEnd; ++unusualIter) {
  10744. switch ((*unusualIter)->getKind()) {
  10745. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10746. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  10747. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  10748. break;
  10749. }
  10750. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10751. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  10752. if (registerAssignment->isSpaceOnly())
  10753. continue;
  10754. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  10755. Diag(registerAssignment->Loc, diag::err_hlsl_incorrect_bind_semantic) << (cbuffer ? "'b'" : "'t'");
  10756. } else if (registerAssignment->ShaderProfile.size() > 0) {
  10757. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  10758. }
  10759. break;
  10760. }
  10761. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10762. // Ignore semantic declarations.
  10763. break;
  10764. }
  10765. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  10766. hlsl::PayloadAccessAnnotation* annotation = cast<hlsl::PayloadAccessAnnotation>(*unusualIter);
  10767. Diag( annotation->Loc, diag::err_hlsl_unsupported_payload_access_qualifier);
  10768. break;
  10769. }
  10770. }
  10771. }
  10772. PushOnScopeChains(result, bufferScope);
  10773. PushDeclContext(bufferScope, result);
  10774. ActOnDocumentableDecl(result);
  10775. return result;
  10776. }
  10777. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  10778. {
  10779. DXASSERT_NOMSG(Dcl != nullptr);
  10780. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10781. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  10782. HLSLBuffers.pop_back();
  10783. PopDeclContext();
  10784. }
  10785. Decl* Sema::getActiveHLSLBuffer() const
  10786. {
  10787. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  10788. }
  10789. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  10790. DeclGroupPtrTy &dcl, bool iscbuf) {
  10791. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10792. HLSLBuffers.pop_back();
  10793. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10794. Decl *decl = dcl.get().getSingleDecl();
  10795. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  10796. IdentifierInfo *Ident = namedDecl->getIdentifier();
  10797. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  10798. SourceLocation Loc = decl->getLocation();
  10799. // Prevent array type in template. The only way to specify an array in the template type
  10800. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  10801. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  10802. QualType declType = cast<VarDecl>(namedDecl)->getType();
  10803. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  10804. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  10805. declType = arrayType->getElementType();
  10806. }
  10807. // Check to make that sure only structs are allowed as parameter types for
  10808. // ConstantBuffer and TextureBuffer.
  10809. if (!declType->isStructureType()) {
  10810. Diag(decl->getLocStart(),
  10811. diag::err_hlsl_typeintemplateargument_requires_struct)
  10812. << declType;
  10813. return nullptr;
  10814. }
  10815. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  10816. DeclContext *lexicalParent = getCurLexicalContext();
  10817. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10818. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  10819. KwLoc, Ident, Loc, hlslAttrs, Loc);
  10820. // set relation
  10821. namedDecl->setDeclContext(result);
  10822. result->addDecl(namedDecl);
  10823. // move attribute from constant to constant buffer
  10824. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  10825. namedDecl->setUnusualAnnotations(hlslAttrs);
  10826. return result;
  10827. }
  10828. bool Sema::IsOnHLSLBufferView() {
  10829. // nullptr will not pushed for cbuffer.
  10830. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  10831. }
  10832. void Sema::ActOnStartHLSLBufferView() {
  10833. // Push nullptr to mark HLSLBufferView.
  10834. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10835. HLSLBuffers.emplace_back(nullptr);
  10836. }
  10837. HLSLBufferDecl::HLSLBufferDecl(
  10838. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  10839. IdentifierInfo *Id, SourceLocation IdLoc,
  10840. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10841. SourceLocation LBrace)
  10842. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  10843. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  10844. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  10845. if (!BufferAttributes.empty()) {
  10846. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10847. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  10848. }
  10849. }
  10850. HLSLBufferDecl *
  10851. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  10852. bool constantbuffer, SourceLocation KwLoc,
  10853. IdentifierInfo *Id, SourceLocation IdLoc,
  10854. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10855. SourceLocation LBrace) {
  10856. DeclContext *DC = C.getTranslationUnitDecl();
  10857. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  10858. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  10859. if (DC != lexicalParent) {
  10860. result->setLexicalDeclContext(lexicalParent);
  10861. }
  10862. return result;
  10863. }
  10864. const char *HLSLBufferDecl::getDeclKindName() const {
  10865. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  10866. "ConstantBuffer"};
  10867. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  10868. return HLSLBufferNames[index];
  10869. }
  10870. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  10871. assert(NewDecl != nullptr);
  10872. if (!getLangOpts().HLSL) {
  10873. return;
  10874. }
  10875. if (!D.UnusualAnnotations.empty()) {
  10876. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10877. getASTContext(), D.UnusualAnnotations.data(),
  10878. D.UnusualAnnotations.size()));
  10879. D.UnusualAnnotations.clear();
  10880. }
  10881. }
  10882. /// Checks whether a usage attribute is compatible with those seen so far and
  10883. /// maintains history.
  10884. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  10885. bool &usageOut) {
  10886. switch (kind) {
  10887. case AttributeList::AT_HLSLIn:
  10888. if (usageIn)
  10889. return false;
  10890. usageIn = true;
  10891. break;
  10892. case AttributeList::AT_HLSLOut:
  10893. if (usageOut)
  10894. return false;
  10895. usageOut = true;
  10896. break;
  10897. default:
  10898. assert(kind == AttributeList::AT_HLSLInOut);
  10899. if (usageOut || usageIn)
  10900. return false;
  10901. usageIn = usageOut = true;
  10902. break;
  10903. }
  10904. return true;
  10905. }
  10906. // Diagnose valid/invalid modifiers for HLSL.
  10907. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC, Expr *BitWidth,
  10908. TypeSourceInfo *TInfo, bool isParameter) {
  10909. assert(getLangOpts().HLSL &&
  10910. "otherwise this is called without checking language first");
  10911. // NOTE: some tests may declare templates.
  10912. if (DC->isDependentContext()) return true;
  10913. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  10914. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  10915. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  10916. bool result = true;
  10917. bool isTypedef = storage == DeclSpec::SCS_typedef;
  10918. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  10919. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  10920. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->isNamespace() || DC->getDeclKind() == Decl::HLSLBuffer);
  10921. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  10922. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  10923. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  10924. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  10925. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  10926. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  10927. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  10928. // Function declarations are not allowed in parameter declaration
  10929. // TODO : Remove this check once we support function declarations/pointers in HLSL
  10930. if (isParameter && isFunction) {
  10931. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  10932. D.setInvalidType();
  10933. return false;
  10934. }
  10935. assert(
  10936. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  10937. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  10938. (isParameter ? 1 : 0))
  10939. && "exactly one type of declarator is being processed");
  10940. // qt/pType captures either the type being modified, or the return type in the
  10941. // case of a function (or method).
  10942. QualType qt = TInfo->getType();
  10943. const Type* pType = qt.getTypePtrOrNull();
  10944. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  10945. // Early checks - these are not simple attribution errors, but constructs that
  10946. // are fundamentally unsupported,
  10947. // and so we avoid errors that might indicate they can be repaired.
  10948. if (DC->isRecord()) {
  10949. unsigned int nestedDiagId = 0;
  10950. if (isTypedef) {
  10951. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  10952. }
  10953. if (isField && pType && pType->isIncompleteArrayType()) {
  10954. nestedDiagId = diag::err_hlsl_unsupported_incomplete_array;
  10955. }
  10956. if (nestedDiagId) {
  10957. Diag(D.getLocStart(), nestedDiagId);
  10958. D.setInvalidType();
  10959. return false;
  10960. }
  10961. }
  10962. // String and subobject declarations are supported only as top level global variables.
  10963. // Const and static modifiers are implied - add them if missing.
  10964. if ((hlsl::IsStringType(qt) || hlslSource->IsSubobjectType(qt)) && !D.isInvalidType()) {
  10965. // string are supported only as top level global variables
  10966. if (!DC->isTranslationUnit()) {
  10967. Diag(D.getLocStart(), diag::err_hlsl_object_not_global) << (int)hlsl::IsStringType(qt);
  10968. result = false;
  10969. }
  10970. if (isExtern) {
  10971. Diag(D.getLocStart(), diag::err_hlsl_object_extern_not_supported) << (int)hlsl::IsStringType(qt);
  10972. result = false;
  10973. }
  10974. const char *PrevSpec = nullptr;
  10975. unsigned DiagID = 0;
  10976. if (!isStatic) {
  10977. D.getMutableDeclSpec().SetStorageClassSpec(*this, DeclSpec::SCS_static, D.getLocStart(), PrevSpec, DiagID, Context.getPrintingPolicy());
  10978. isStatic = true;
  10979. }
  10980. if (!isConst) {
  10981. D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, D.getLocStart(), PrevSpec, DiagID, getLangOpts());
  10982. isConst = true;
  10983. }
  10984. }
  10985. const char* declarationType =
  10986. (isLocalVar) ? "local variable" :
  10987. (isTypedef) ? "typedef" :
  10988. (isFunction) ? "function" :
  10989. (isMethod) ? "method" :
  10990. (isGlobal) ? "global variable" :
  10991. (isParameter) ? "parameter" :
  10992. (isField) ? "field" : "<unknown>";
  10993. if (pType && D.isFunctionDeclarator()) {
  10994. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  10995. if (pFP) {
  10996. qt = pFP->getReturnType();
  10997. pType = qt.getTypePtrOrNull();
  10998. // prohibit string as a return type
  10999. if (hlsl::IsStringType(qt)) {
  11000. static const unsigned selectReturnValueIdx = 2;
  11001. Diag(D.getLocStart(), diag::err_hlsl_unsupported_string_decl) << selectReturnValueIdx;
  11002. D.setInvalidType();
  11003. }
  11004. }
  11005. }
  11006. // Check for deprecated effect object type here, warn, and invalidate decl
  11007. bool bDeprecatedEffectObject = false;
  11008. bool bIsObject = false;
  11009. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  11010. bIsObject = true;
  11011. if (bDeprecatedEffectObject) {
  11012. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  11013. D.setInvalidType();
  11014. return false;
  11015. }
  11016. // Add methods if not ready.
  11017. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  11018. } else if (qt->isArrayType()) {
  11019. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  11020. while (eltQt->isArrayType())
  11021. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  11022. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  11023. // Add methods if not ready.
  11024. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  11025. bIsObject = true;
  11026. }
  11027. }
  11028. if (isExtern) {
  11029. if (!(isFunction || isGlobal)) {
  11030. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  11031. << declarationType;
  11032. result = false;
  11033. }
  11034. }
  11035. if (isStatic) {
  11036. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  11037. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  11038. << declarationType;
  11039. result = false;
  11040. }
  11041. }
  11042. if (isVolatile) {
  11043. if (!(isLocalVar || isTypedef)) {
  11044. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  11045. << declarationType;
  11046. result = false;
  11047. }
  11048. }
  11049. if (isConst) {
  11050. if (isField && !isStatic) {
  11051. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  11052. << declarationType;
  11053. result = false;
  11054. }
  11055. }
  11056. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  11057. if (hasSignSpec) {
  11058. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  11059. // vectors or matrices can only have unsigned integer types.
  11060. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  11061. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  11062. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  11063. << g_ArBasicTypeNames[basicKind];
  11064. result = false;
  11065. }
  11066. }
  11067. else {
  11068. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  11069. result = false;
  11070. }
  11071. }
  11072. // Validate attributes
  11073. clang::AttributeList
  11074. *pUniform = nullptr,
  11075. *pUsage = nullptr,
  11076. *pNoInterpolation = nullptr,
  11077. *pLinear = nullptr,
  11078. *pNoPerspective = nullptr,
  11079. *pSample = nullptr,
  11080. *pCentroid = nullptr,
  11081. *pCenter = nullptr,
  11082. *pAnyLinear = nullptr, // first linear attribute found
  11083. *pTopology = nullptr,
  11084. *pMeshModifier = nullptr;
  11085. bool usageIn = false;
  11086. bool usageOut = false;
  11087. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  11088. pAttr != NULL; pAttr = pAttr->getNext()) {
  11089. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  11090. continue;
  11091. switch (pAttr->getKind()) {
  11092. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  11093. break;
  11094. case AttributeList::AT_HLSLShared:
  11095. if (!isGlobal) {
  11096. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11097. << pAttr->getName() << declarationType << pAttr->getRange();
  11098. result = false;
  11099. }
  11100. if (isStatic) {
  11101. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11102. << "'static'" << pAttr->getName() << declarationType
  11103. << pAttr->getRange();
  11104. result = false;
  11105. }
  11106. break;
  11107. case AttributeList::AT_HLSLGroupShared:
  11108. if (!isGlobal) {
  11109. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11110. << pAttr->getName() << declarationType << pAttr->getRange();
  11111. result = false;
  11112. }
  11113. if (isExtern) {
  11114. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11115. << "'extern'" << pAttr->getName() << declarationType
  11116. << pAttr->getRange();
  11117. result = false;
  11118. }
  11119. break;
  11120. case AttributeList::AT_HLSLGloballyCoherent:
  11121. if (!bIsObject) {
  11122. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11123. << pAttr->getName() << "non-UAV type";
  11124. result = false;
  11125. }
  11126. break;
  11127. case AttributeList::AT_HLSLUniform:
  11128. if (!(isGlobal || isParameter)) {
  11129. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11130. << pAttr->getName() << declarationType << pAttr->getRange();
  11131. result = false;
  11132. }
  11133. if (isStatic) {
  11134. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11135. << "'static'" << pAttr->getName() << declarationType
  11136. << pAttr->getRange();
  11137. result = false;
  11138. }
  11139. pUniform = pAttr;
  11140. break;
  11141. case AttributeList::AT_HLSLIn:
  11142. case AttributeList::AT_HLSLOut:
  11143. case AttributeList::AT_HLSLInOut:
  11144. if (!isParameter) {
  11145. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  11146. << pAttr->getName() << pAttr->getRange();
  11147. result = false;
  11148. }
  11149. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  11150. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  11151. << pAttr->getName() << pAttr->getRange();
  11152. result = false;
  11153. }
  11154. pUsage = pAttr;
  11155. break;
  11156. case AttributeList::AT_HLSLNoInterpolation:
  11157. if (!(isParameter || isField || isFunction)) {
  11158. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11159. << pAttr->getName() << declarationType << pAttr->getRange();
  11160. result = false;
  11161. }
  11162. if (pNoInterpolation) {
  11163. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11164. << pAttr->getName() << pAttr->getRange();
  11165. }
  11166. pNoInterpolation = pAttr;
  11167. break;
  11168. case AttributeList::AT_HLSLLinear:
  11169. case AttributeList::AT_HLSLCenter:
  11170. case AttributeList::AT_HLSLNoPerspective:
  11171. case AttributeList::AT_HLSLSample:
  11172. case AttributeList::AT_HLSLCentroid:
  11173. if (!(isParameter || isField || isFunction)) {
  11174. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11175. << pAttr->getName() << declarationType << pAttr->getRange();
  11176. result = false;
  11177. }
  11178. if (nullptr == pAnyLinear)
  11179. pAnyLinear = pAttr;
  11180. switch (pAttr->getKind()) {
  11181. case AttributeList::AT_HLSLLinear:
  11182. if (pLinear) {
  11183. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11184. << pAttr->getName() << pAttr->getRange();
  11185. }
  11186. pLinear = pAttr;
  11187. break;
  11188. case AttributeList::AT_HLSLCenter:
  11189. if (pCenter) {
  11190. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11191. << pAttr->getName() << pAttr->getRange();
  11192. }
  11193. pCenter = pAttr;
  11194. break;
  11195. case AttributeList::AT_HLSLNoPerspective:
  11196. if (pNoPerspective) {
  11197. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11198. << pAttr->getName() << pAttr->getRange();
  11199. }
  11200. pNoPerspective = pAttr;
  11201. break;
  11202. case AttributeList::AT_HLSLSample:
  11203. if (pSample) {
  11204. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11205. << pAttr->getName() << pAttr->getRange();
  11206. }
  11207. pSample = pAttr;
  11208. break;
  11209. case AttributeList::AT_HLSLCentroid:
  11210. if (pCentroid) {
  11211. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11212. << pAttr->getName() << pAttr->getRange();
  11213. }
  11214. pCentroid = pAttr;
  11215. break;
  11216. default:
  11217. // Only relevant to the four attribs included in this block.
  11218. break;
  11219. }
  11220. break;
  11221. case AttributeList::AT_HLSLPoint:
  11222. case AttributeList::AT_HLSLLine:
  11223. case AttributeList::AT_HLSLLineAdj:
  11224. case AttributeList::AT_HLSLTriangle:
  11225. case AttributeList::AT_HLSLTriangleAdj:
  11226. if (!(isParameter)) {
  11227. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11228. << pAttr->getName() << declarationType << pAttr->getRange();
  11229. result = false;
  11230. }
  11231. if (pTopology) {
  11232. if (pTopology->getKind() == pAttr->getKind()) {
  11233. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11234. << pAttr->getName() << pAttr->getRange();
  11235. } else {
  11236. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11237. << pAttr->getName() << pTopology->getName()
  11238. << declarationType << pAttr->getRange();
  11239. result = false;
  11240. }
  11241. }
  11242. pTopology = pAttr;
  11243. break;
  11244. case AttributeList::AT_HLSLExport:
  11245. if (!isFunction) {
  11246. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11247. << pAttr->getName() << declarationType << pAttr->getRange();
  11248. result = false;
  11249. }
  11250. if (isStatic) {
  11251. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11252. << "'static'" << pAttr->getName() << declarationType
  11253. << pAttr->getRange();
  11254. result = false;
  11255. }
  11256. break;
  11257. case AttributeList::AT_HLSLIndices:
  11258. case AttributeList::AT_HLSLVertices:
  11259. case AttributeList::AT_HLSLPrimitives:
  11260. case AttributeList::AT_HLSLPayload:
  11261. if (!(isParameter)) {
  11262. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11263. << pAttr->getName() << declarationType << pAttr->getRange();
  11264. result = false;
  11265. }
  11266. if (pMeshModifier) {
  11267. if (pMeshModifier->getKind() == pAttr->getKind()) {
  11268. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11269. << pAttr->getName() << pAttr->getRange();
  11270. } else {
  11271. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11272. << pAttr->getName() << pMeshModifier->getName()
  11273. << declarationType << pAttr->getRange();
  11274. result = false;
  11275. }
  11276. }
  11277. pMeshModifier = pAttr;
  11278. break;
  11279. default:
  11280. break;
  11281. }
  11282. }
  11283. if (pNoInterpolation && pAnyLinear) {
  11284. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  11285. << pNoInterpolation->getName() << pAnyLinear->getName()
  11286. << declarationType << pNoInterpolation->getRange();
  11287. result = false;
  11288. }
  11289. if (pSample && pCentroid) {
  11290. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  11291. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  11292. }
  11293. if (pCenter && pCentroid) {
  11294. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  11295. << pCenter->getName() << pCentroid->getName() << pCenter->getRange();
  11296. }
  11297. if (pSample && pCenter) {
  11298. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  11299. << pCenter->getName() << pSample->getName() << pCenter->getRange();
  11300. }
  11301. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  11302. pNoInterpolation ? pNoInterpolation : pTopology);
  11303. if (pUniform && pNonUniformAttr) {
  11304. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  11305. << pNonUniformAttr->getName()
  11306. << pUniform->getName() << declarationType << pUniform->getRange();
  11307. result = false;
  11308. }
  11309. if (pAnyLinear && pTopology) {
  11310. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  11311. << pTopology->getName()
  11312. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  11313. result = false;
  11314. }
  11315. if (pNoInterpolation && pTopology) {
  11316. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  11317. << pTopology->getName()
  11318. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  11319. result = false;
  11320. }
  11321. if (pUniform && pUsage) {
  11322. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  11323. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  11324. << pUsage->getName() << pUniform->getName() << declarationType
  11325. << pUniform->getRange();
  11326. result = false;
  11327. }
  11328. }
  11329. if (pMeshModifier) {
  11330. if (pMeshModifier->getKind() == AttributeList::Kind::AT_HLSLPayload) {
  11331. if (!usageIn) {
  11332. Diag(D.getLocStart(), diag::err_hlsl_missing_in_attr)
  11333. << pMeshModifier->getName();
  11334. result = false;
  11335. }
  11336. } else {
  11337. if (!usageOut) {
  11338. Diag(D.getLocStart(), diag::err_hlsl_missing_out_attr)
  11339. << pMeshModifier->getName();
  11340. result = false;
  11341. }
  11342. }
  11343. }
  11344. // Validate that stream-ouput objects are marked as inout
  11345. if (isParameter && !(usageIn && usageOut) &&
  11346. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  11347. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  11348. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  11349. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  11350. result = false;
  11351. }
  11352. // SPIRV change starts
  11353. #ifdef ENABLE_SPIRV_CODEGEN
  11354. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  11355. if (!getLangOpts().SPIRV) {
  11356. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  11357. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  11358. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  11359. << g_ArBasicTypeNames[basicKind];
  11360. result = false;
  11361. }
  11362. }
  11363. #endif // ENABLE_SPIRV_CODEGEN
  11364. // SPIRV change ends
  11365. // Disallow bitfields
  11366. if (BitWidth) {
  11367. Diag(BitWidth->getExprLoc(), diag::err_hlsl_bitfields);
  11368. result = false;
  11369. }
  11370. // Validate unusual annotations.
  11371. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  11372. if (isField)
  11373. hlsl::DiagnosePayloadAccessQualifierAnnotations(*this, D, qt,
  11374. D.UnusualAnnotations);
  11375. auto && unusualIter = D.UnusualAnnotations.begin();
  11376. auto && unusualEnd = D.UnusualAnnotations.end();
  11377. for (; unusualIter != unusualEnd; ++unusualIter) {
  11378. switch ((*unusualIter)->getKind()) {
  11379. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  11380. hlsl::ConstantPacking *constantPacking =
  11381. cast<hlsl::ConstantPacking>(*unusualIter);
  11382. if (!isGlobal || HLSLBuffers.size() == 0) {
  11383. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  11384. continue;
  11385. }
  11386. if (constantPacking->ComponentOffset > 0) {
  11387. // Validate that this will fit.
  11388. if (!qt.isNull()) {
  11389. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  11390. constantPacking->ComponentOffset);
  11391. }
  11392. }
  11393. break;
  11394. }
  11395. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  11396. hlsl::RegisterAssignment *registerAssignment =
  11397. cast<hlsl::RegisterAssignment>(*unusualIter);
  11398. if (registerAssignment->IsValid) {
  11399. if (!qt.isNull()) {
  11400. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  11401. registerAssignment->RegisterType);
  11402. }
  11403. }
  11404. break;
  11405. }
  11406. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  11407. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  11408. if (isTypedef || isLocalVar) {
  11409. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  11410. << "semantic" << declarationType;
  11411. }
  11412. break;
  11413. }
  11414. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  11415. hlsl::PayloadAccessAnnotation *annotation = cast<hlsl::PayloadAccessAnnotation>(*unusualIter);
  11416. if (!isField) {
  11417. Diag(annotation->Loc, diag::err_hlsl_unsupported_payload_access_qualifier);
  11418. }
  11419. break;
  11420. }
  11421. }
  11422. }
  11423. if (!result) {
  11424. D.setInvalidType();
  11425. }
  11426. return result;
  11427. }
  11428. // Diagnose HLSL types on lookup
  11429. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  11430. const DeclarationNameInfo declName = R.getLookupNameInfo();
  11431. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  11432. if (idInfo) {
  11433. StringRef nameIdentifier = idInfo->getName();
  11434. HLSLScalarType parsedType;
  11435. int rowCount, colCount;
  11436. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  11437. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  11438. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  11439. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  11440. }
  11441. }
  11442. return true;
  11443. }
  11444. static QualType getUnderlyingType(QualType Type)
  11445. {
  11446. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  11447. {
  11448. if (const TypedefNameDecl* pDecl = TD->getDecl())
  11449. Type = pDecl->getUnderlyingType();
  11450. else
  11451. break;
  11452. }
  11453. return Type;
  11454. }
  11455. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  11456. /// <param name="self">Sema with context.</param>
  11457. /// <param name="type">QualType to inspect.</param>
  11458. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  11459. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  11460. void hlsl::GetHLSLAttributedTypes(
  11461. _In_ clang::Sema *self, clang::QualType type,
  11462. _Inout_opt_ const clang::AttributedType **ppMatrixOrientation,
  11463. _Inout_opt_ const clang::AttributedType **ppNorm,
  11464. _Inout_opt_ const clang::AttributedType **ppGLC) {
  11465. AssignOpt<const clang::AttributedType *>(nullptr, ppMatrixOrientation);
  11466. AssignOpt<const clang::AttributedType *>(nullptr, ppNorm);
  11467. AssignOpt<const clang::AttributedType *>(nullptr, ppGLC);
  11468. // Note: we clear output pointers once set so we can stop searching
  11469. QualType Desugared = getUnderlyingType(type);
  11470. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  11471. while (AT && (ppMatrixOrientation || ppNorm || ppGLC)) {
  11472. AttributedType::Kind Kind = AT->getAttrKind();
  11473. if (Kind == AttributedType::attr_hlsl_row_major ||
  11474. Kind == AttributedType::attr_hlsl_column_major)
  11475. {
  11476. if (ppMatrixOrientation)
  11477. {
  11478. *ppMatrixOrientation = AT;
  11479. ppMatrixOrientation = nullptr;
  11480. }
  11481. }
  11482. else if (Kind == AttributedType::attr_hlsl_unorm ||
  11483. Kind == AttributedType::attr_hlsl_snorm)
  11484. {
  11485. if (ppNorm)
  11486. {
  11487. *ppNorm = AT;
  11488. ppNorm = nullptr;
  11489. }
  11490. }
  11491. else if (Kind == AttributedType::attr_hlsl_globallycoherent) {
  11492. if (ppGLC) {
  11493. *ppGLC = AT;
  11494. ppGLC = nullptr;
  11495. }
  11496. }
  11497. Desugared = getUnderlyingType(AT->getEquivalentType());
  11498. AT = dyn_cast<AttributedType>(Desugared);
  11499. }
  11500. // Unwrap component type on vector or matrix and check snorm/unorm
  11501. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  11502. AT = dyn_cast<AttributedType>(Desugared);
  11503. while (AT && ppNorm) {
  11504. AttributedType::Kind Kind = AT->getAttrKind();
  11505. if (Kind == AttributedType::attr_hlsl_unorm ||
  11506. Kind == AttributedType::attr_hlsl_snorm)
  11507. {
  11508. *ppNorm = AT;
  11509. ppNorm = nullptr;
  11510. }
  11511. Desugared = getUnderlyingType(AT->getEquivalentType());
  11512. AT = dyn_cast<AttributedType>(Desugared);
  11513. }
  11514. }
  11515. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  11516. /// <param name="self">Sema with context.</param>
  11517. /// <param name="type">QualType to check.</param>
  11518. bool hlsl::IsMatrixType(
  11519. _In_ clang::Sema* self,
  11520. _In_ clang::QualType type)
  11521. {
  11522. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  11523. }
  11524. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  11525. /// <param name="self">Sema with context.</param>
  11526. /// <param name="type">QualType to check.</param>
  11527. bool hlsl::IsVectorType(
  11528. _In_ clang::Sema* self,
  11529. _In_ clang::QualType type)
  11530. {
  11531. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  11532. }
  11533. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  11534. /// <param name="self">Sema with context.</param>
  11535. /// <param name="type">Matrix or Vector type.</param>
  11536. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  11537. _In_ clang::QualType type)
  11538. {
  11539. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  11540. // without losing the AttributedType on the template parameter
  11541. if (const Type* pType = type.getTypePtrOrNull()) {
  11542. // A non-dependent template specialization type is always "sugar",
  11543. // typically for a RecordType. For example, a class template
  11544. // specialization type of @c vector<int> will refer to a tag type for
  11545. // the instantiation @c std::vector<int, std::allocator<int>>.
  11546. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  11547. // If we have enough arguments, pull them from the template directly, rather than doing
  11548. // the extra lookups.
  11549. if (pTemplate->getNumArgs() > 0)
  11550. return pTemplate->getArg(0).getAsType();
  11551. QualType templateRecord = pTemplate->desugar();
  11552. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  11553. if (pTemplateRecordType) {
  11554. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  11555. if (pTemplateTagType) {
  11556. const ClassTemplateSpecializationDecl *specializationDecl =
  11557. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  11558. pTemplateTagType->getDecl());
  11559. if (specializationDecl) {
  11560. return specializationDecl->getTemplateArgs()[0].getAsType();
  11561. }
  11562. }
  11563. }
  11564. }
  11565. }
  11566. return QualType();
  11567. }
  11568. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  11569. /// <param name="self">Sema with context.</param>
  11570. /// <param name="type">Input type.</param>
  11571. clang::QualType hlsl::GetOriginalElementType(
  11572. _In_ clang::Sema* self,
  11573. _In_ clang::QualType type)
  11574. {
  11575. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  11576. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  11577. return GetOriginalMatrixOrVectorElementType(type);
  11578. }
  11579. return type;
  11580. }
  11581. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  11582. switch (A->getKind()) {
  11583. // Parameter modifiers
  11584. case clang::attr::HLSLIn:
  11585. Out << "in ";
  11586. break;
  11587. case clang::attr::HLSLInOut:
  11588. Out << "inout ";
  11589. break;
  11590. case clang::attr::HLSLOut:
  11591. Out << "out ";
  11592. break;
  11593. // Interpolation modifiers
  11594. case clang::attr::HLSLLinear:
  11595. Out << "linear ";
  11596. break;
  11597. case clang::attr::HLSLCenter:
  11598. Out << "center ";
  11599. break;
  11600. case clang::attr::HLSLCentroid:
  11601. Out << "centroid ";
  11602. break;
  11603. case clang::attr::HLSLNoInterpolation:
  11604. Out << "nointerpolation ";
  11605. break;
  11606. case clang::attr::HLSLNoPerspective:
  11607. Out << "noperspective ";
  11608. break;
  11609. case clang::attr::HLSLSample:
  11610. Out << "sample ";
  11611. break;
  11612. // Function attributes
  11613. case clang::attr::HLSLClipPlanes:
  11614. {
  11615. Attr * noconst = const_cast<Attr*>(A);
  11616. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  11617. if (!ACast->getClipPlane1())
  11618. break;
  11619. Indent(Indentation, Out);
  11620. Out << "[clipplanes(";
  11621. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  11622. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  11623. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  11624. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  11625. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  11626. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  11627. Out << ")]\n";
  11628. break;
  11629. }
  11630. case clang::attr::HLSLDomain:
  11631. {
  11632. Attr * noconst = const_cast<Attr*>(A);
  11633. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  11634. Indent(Indentation, Out);
  11635. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  11636. break;
  11637. }
  11638. case clang::attr::HLSLEarlyDepthStencil:
  11639. Indent(Indentation, Out);
  11640. Out << "[earlydepthstencil]\n";
  11641. break;
  11642. case clang::attr::HLSLInstance: //TODO - test
  11643. {
  11644. Attr * noconst = const_cast<Attr*>(A);
  11645. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  11646. Indent(Indentation, Out);
  11647. Out << "[instance(" << ACast->getCount() << ")]\n";
  11648. break;
  11649. }
  11650. case clang::attr::HLSLMaxTessFactor: //TODO - test
  11651. {
  11652. Attr * noconst = const_cast<Attr*>(A);
  11653. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  11654. Indent(Indentation, Out);
  11655. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  11656. break;
  11657. }
  11658. case clang::attr::HLSLNumThreads: //TODO - test
  11659. {
  11660. Attr * noconst = const_cast<Attr*>(A);
  11661. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  11662. Indent(Indentation, Out);
  11663. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  11664. break;
  11665. }
  11666. case clang::attr::HLSLRootSignature:
  11667. {
  11668. Attr * noconst = const_cast<Attr*>(A);
  11669. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  11670. Indent(Indentation, Out);
  11671. Out << "[RootSignature(\"" << ACast->getSignatureName() << "\")]\n";
  11672. break;
  11673. }
  11674. case clang::attr::HLSLOutputControlPoints:
  11675. {
  11676. Attr * noconst = const_cast<Attr*>(A);
  11677. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  11678. Indent(Indentation, Out);
  11679. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  11680. break;
  11681. }
  11682. case clang::attr::HLSLOutputTopology:
  11683. {
  11684. Attr * noconst = const_cast<Attr*>(A);
  11685. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  11686. Indent(Indentation, Out);
  11687. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  11688. break;
  11689. }
  11690. case clang::attr::HLSLPartitioning:
  11691. {
  11692. Attr * noconst = const_cast<Attr*>(A);
  11693. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  11694. Indent(Indentation, Out);
  11695. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  11696. break;
  11697. }
  11698. case clang::attr::HLSLPatchConstantFunc:
  11699. {
  11700. Attr * noconst = const_cast<Attr*>(A);
  11701. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  11702. Indent(Indentation, Out);
  11703. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  11704. break;
  11705. }
  11706. case clang::attr::HLSLShader:
  11707. {
  11708. Attr * noconst = const_cast<Attr*>(A);
  11709. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  11710. Indent(Indentation, Out);
  11711. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  11712. break;
  11713. }
  11714. case clang::attr::HLSLExperimental:
  11715. {
  11716. Attr * noconst = const_cast<Attr*>(A);
  11717. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  11718. Indent(Indentation, Out);
  11719. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  11720. break;
  11721. }
  11722. case clang::attr::HLSLMaxVertexCount:
  11723. {
  11724. Attr * noconst = const_cast<Attr*>(A);
  11725. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  11726. Indent(Indentation, Out);
  11727. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  11728. break;
  11729. }
  11730. case clang::attr::NoInline:
  11731. Indent(Indentation, Out);
  11732. Out << "[noinline]\n";
  11733. break;
  11734. case clang::attr::HLSLExport:
  11735. Indent(Indentation, Out);
  11736. Out << "export\n";
  11737. break;
  11738. // Statement attributes
  11739. case clang::attr::HLSLAllowUAVCondition:
  11740. Indent(Indentation, Out);
  11741. Out << "[allow_uav_condition]\n";
  11742. break;
  11743. case clang::attr::HLSLBranch:
  11744. Indent(Indentation, Out);
  11745. Out << "[branch]\n";
  11746. break;
  11747. case clang::attr::HLSLCall:
  11748. Indent(Indentation, Out);
  11749. Out << "[call]\n";
  11750. break;
  11751. case clang::attr::HLSLFastOpt:
  11752. Indent(Indentation, Out);
  11753. Out << "[fastopt]\n";
  11754. break;
  11755. case clang::attr::HLSLFlatten:
  11756. Indent(Indentation, Out);
  11757. Out << "[flatten]\n";
  11758. break;
  11759. case clang::attr::HLSLForceCase:
  11760. Indent(Indentation, Out);
  11761. Out << "[forcecase]\n";
  11762. break;
  11763. case clang::attr::HLSLLoop:
  11764. Indent(Indentation, Out);
  11765. Out << "[loop]\n";
  11766. break;
  11767. case clang::attr::HLSLUnroll:
  11768. {
  11769. Attr * noconst = const_cast<Attr*>(A);
  11770. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  11771. Indent(Indentation, Out);
  11772. if (ACast->getCount() == 0)
  11773. Out << "[unroll]\n";
  11774. else
  11775. Out << "[unroll(" << ACast->getCount() << ")]\n";
  11776. break;
  11777. }
  11778. case clang::attr::HLSLWaveSize:
  11779. {
  11780. Attr * noconst = const_cast<Attr*>(A);
  11781. HLSLWaveSizeAttr *ACast = static_cast<HLSLWaveSizeAttr*>(noconst);
  11782. Indent(Indentation, Out);
  11783. Out << "[wavesize(" << ACast->getSize() << ")]\n";
  11784. break;
  11785. }
  11786. // Variable modifiers
  11787. case clang::attr::HLSLGroupShared:
  11788. Out << "groupshared ";
  11789. break;
  11790. case clang::attr::HLSLPrecise:
  11791. Out << "precise ";
  11792. break;
  11793. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  11794. break;
  11795. case clang::attr::HLSLShared:
  11796. Out << "shared ";
  11797. break;
  11798. case clang::attr::HLSLUniform:
  11799. Out << "uniform ";
  11800. break;
  11801. // These four cases are printed in TypePrinter::printAttributedBefore
  11802. case clang::attr::HLSLColumnMajor:
  11803. case clang::attr::HLSLRowMajor:
  11804. case clang::attr::HLSLSnorm:
  11805. case clang::attr::HLSLUnorm:
  11806. break;
  11807. case clang::attr::HLSLPoint:
  11808. Out << "point ";
  11809. break;
  11810. case clang::attr::HLSLLine:
  11811. Out << "line ";
  11812. break;
  11813. case clang::attr::HLSLLineAdj:
  11814. Out << "lineadj ";
  11815. break;
  11816. case clang::attr::HLSLTriangle:
  11817. Out << "triangle ";
  11818. break;
  11819. case clang::attr::HLSLTriangleAdj:
  11820. Out << "triangleadj ";
  11821. break;
  11822. case clang::attr::HLSLGloballyCoherent:
  11823. Out << "globallycoherent ";
  11824. break;
  11825. case clang::attr::HLSLIndices:
  11826. Out << "indices ";
  11827. break;
  11828. case clang::attr::HLSLVertices:
  11829. Out << "vertices ";
  11830. break;
  11831. case clang::attr::HLSLPrimitives:
  11832. Out << "primitives ";
  11833. break;
  11834. case clang::attr::HLSLPayload:
  11835. Out << "payload ";
  11836. break;
  11837. default:
  11838. A->printPretty(Out, Policy);
  11839. break;
  11840. }
  11841. }
  11842. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  11843. switch (AttrKind){
  11844. case clang::attr::HLSLAllowUAVCondition:
  11845. case clang::attr::HLSLBranch:
  11846. case clang::attr::HLSLCall:
  11847. case clang::attr::HLSLCentroid:
  11848. case clang::attr::HLSLClipPlanes:
  11849. case clang::attr::HLSLColumnMajor:
  11850. case clang::attr::HLSLDomain:
  11851. case clang::attr::HLSLEarlyDepthStencil:
  11852. case clang::attr::HLSLFastOpt:
  11853. case clang::attr::HLSLFlatten:
  11854. case clang::attr::HLSLForceCase:
  11855. case clang::attr::HLSLGroupShared:
  11856. case clang::attr::HLSLIn:
  11857. case clang::attr::HLSLInOut:
  11858. case clang::attr::HLSLInstance:
  11859. case clang::attr::HLSLLinear:
  11860. case clang::attr::HLSLCenter:
  11861. case clang::attr::HLSLLoop:
  11862. case clang::attr::HLSLMaxTessFactor:
  11863. case clang::attr::HLSLNoInterpolation:
  11864. case clang::attr::HLSLNoPerspective:
  11865. case clang::attr::HLSLNumThreads:
  11866. case clang::attr::HLSLRootSignature:
  11867. case clang::attr::HLSLOut:
  11868. case clang::attr::HLSLOutputControlPoints:
  11869. case clang::attr::HLSLOutputTopology:
  11870. case clang::attr::HLSLPartitioning:
  11871. case clang::attr::HLSLPatchConstantFunc:
  11872. case clang::attr::HLSLMaxVertexCount:
  11873. case clang::attr::HLSLPrecise:
  11874. case clang::attr::HLSLRowMajor:
  11875. case clang::attr::HLSLSample:
  11876. case clang::attr::HLSLSemantic:
  11877. case clang::attr::HLSLShared:
  11878. case clang::attr::HLSLSnorm:
  11879. case clang::attr::HLSLUniform:
  11880. case clang::attr::HLSLUnorm:
  11881. case clang::attr::HLSLUnroll:
  11882. case clang::attr::HLSLPoint:
  11883. case clang::attr::HLSLLine:
  11884. case clang::attr::HLSLLineAdj:
  11885. case clang::attr::HLSLTriangle:
  11886. case clang::attr::HLSLTriangleAdj:
  11887. case clang::attr::HLSLGloballyCoherent:
  11888. case clang::attr::HLSLIndices:
  11889. case clang::attr::HLSLVertices:
  11890. case clang::attr::HLSLPrimitives:
  11891. case clang::attr::HLSLPayload:
  11892. case clang::attr::NoInline:
  11893. case clang::attr::HLSLExport:
  11894. case clang::attr::HLSLWaveSensitive:
  11895. case clang::attr::HLSLWaveSize:
  11896. case clang::attr::VKBinding:
  11897. case clang::attr::VKBuiltIn:
  11898. case clang::attr::VKConstantId:
  11899. case clang::attr::VKCounterBinding:
  11900. case clang::attr::VKIndex:
  11901. case clang::attr::VKInputAttachmentIndex:
  11902. case clang::attr::VKLocation:
  11903. case clang::attr::VKOffset:
  11904. case clang::attr::VKPushConstant:
  11905. case clang::attr::VKShaderRecordNV:
  11906. case clang::attr::VKShaderRecordEXT:
  11907. return true;
  11908. default:
  11909. // Only HLSL/VK Attributes return true. Only used for printPretty(), which doesn't support them.
  11910. break;
  11911. }
  11912. return false;
  11913. }
  11914. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  11915. if (ClipPlane) {
  11916. Out << ", ";
  11917. ClipPlane->printPretty(Out, 0, Policy);
  11918. }
  11919. }
  11920. bool hlsl::IsObjectType(
  11921. _In_ clang::Sema* self,
  11922. _In_ clang::QualType type,
  11923. _Inout_opt_ bool *isDeprecatedEffectObject)
  11924. {
  11925. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  11926. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  11927. if (isDeprecatedEffectObject)
  11928. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  11929. return true;
  11930. }
  11931. if (isDeprecatedEffectObject)
  11932. *isDeprecatedEffectObject = false;
  11933. return false;
  11934. }
  11935. bool hlsl::CanConvert(
  11936. _In_ clang::Sema* self,
  11937. clang::SourceLocation loc,
  11938. _In_ clang::Expr* sourceExpr,
  11939. clang::QualType target,
  11940. bool explicitConversion,
  11941. _Inout_opt_ clang::StandardConversionSequence* standard)
  11942. {
  11943. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  11944. }
  11945. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  11946. {
  11947. for (unsigned i = 0; i != Indentation; ++i)
  11948. Out << " ";
  11949. }
  11950. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  11951. {
  11952. DXASSERT_NOMSG(self != nullptr);
  11953. DXASSERT_NOMSG(table != nullptr);
  11954. HLSLExternalSource* source = (HLSLExternalSource*)self;
  11955. source->RegisterIntrinsicTable(table);
  11956. }
  11957. clang::QualType hlsl::CheckVectorConditional(
  11958. _In_ clang::Sema* self,
  11959. _In_ clang::ExprResult &Cond,
  11960. _In_ clang::ExprResult &LHS,
  11961. _In_ clang::ExprResult &RHS,
  11962. _In_ clang::SourceLocation QuestionLoc)
  11963. {
  11964. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  11965. }
  11966. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  11967. UINT count;
  11968. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  11969. }
  11970. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  11971. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  11972. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  11973. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  11974. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  11975. llvm::APSInt index;
  11976. if (RHS->EvaluateAsInt(index, Context)) {
  11977. int64_t intIndex = index.getLimitedValue();
  11978. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  11979. if (IsVectorType(this, LHSQualType)) {
  11980. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  11981. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  11982. // we also have to check the first subscript oprator by recursively calling
  11983. // this funciton for the first CXXOperatorCallExpr
  11984. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  11985. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  11986. }
  11987. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  11988. Diag(RHS->getExprLoc(),
  11989. diag::err_hlsl_vector_element_index_out_of_bounds)
  11990. << (int)intIndex;
  11991. }
  11992. }
  11993. else if (IsMatrixType(this, LHSQualType)) {
  11994. uint32_t rowCount, colCount;
  11995. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  11996. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  11997. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  11998. << (int)intIndex;
  11999. }
  12000. }
  12001. }
  12002. }
  12003. clang::QualType ApplyTypeSpecSignToParsedType(
  12004. _In_ clang::Sema* self,
  12005. _In_ clang::QualType &type,
  12006. _In_ clang::TypeSpecifierSign TSS,
  12007. _In_ clang::SourceLocation Loc
  12008. )
  12009. {
  12010. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  12011. }