SemaHLSL.cpp 413 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030
  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/dxcapi.internal.h"
  35. #include "dxc/HlslIntrinsicOp.h"
  36. #include "gen_intrin_main_tables_15.h"
  37. #include "dxc/HLSL/HLOperations.h"
  38. #include "dxc/HLSL/DxilShaderModel.h"
  39. #include <array>
  40. enum ArBasicKind {
  41. AR_BASIC_BOOL,
  42. AR_BASIC_LITERAL_FLOAT,
  43. AR_BASIC_FLOAT16,
  44. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  45. AR_BASIC_FLOAT32,
  46. AR_BASIC_FLOAT64,
  47. AR_BASIC_LITERAL_INT,
  48. AR_BASIC_INT8,
  49. AR_BASIC_UINT8,
  50. AR_BASIC_INT16,
  51. AR_BASIC_UINT16,
  52. AR_BASIC_INT32,
  53. AR_BASIC_UINT32,
  54. AR_BASIC_INT64,
  55. AR_BASIC_UINT64,
  56. AR_BASIC_MIN10FLOAT,
  57. AR_BASIC_MIN16FLOAT,
  58. AR_BASIC_MIN12INT,
  59. AR_BASIC_MIN16INT,
  60. AR_BASIC_MIN16UINT,
  61. AR_BASIC_ENUM,
  62. AR_BASIC_COUNT,
  63. //
  64. // Pseudo-entries for intrinsic tables and such.
  65. //
  66. AR_BASIC_NONE,
  67. AR_BASIC_UNKNOWN,
  68. AR_BASIC_NOCAST,
  69. //
  70. // The following pseudo-entries represent higher-level
  71. // object types that are treated as units.
  72. //
  73. AR_BASIC_POINTER,
  74. AR_BASIC_ENUM_CLASS,
  75. AR_OBJECT_NULL,
  76. AR_OBJECT_STRING,
  77. // AR_OBJECT_TEXTURE,
  78. AR_OBJECT_TEXTURE1D,
  79. AR_OBJECT_TEXTURE1D_ARRAY,
  80. AR_OBJECT_TEXTURE2D,
  81. AR_OBJECT_TEXTURE2D_ARRAY,
  82. AR_OBJECT_TEXTURE3D,
  83. AR_OBJECT_TEXTURECUBE,
  84. AR_OBJECT_TEXTURECUBE_ARRAY,
  85. AR_OBJECT_TEXTURE2DMS,
  86. AR_OBJECT_TEXTURE2DMS_ARRAY,
  87. AR_OBJECT_SAMPLER,
  88. AR_OBJECT_SAMPLER1D,
  89. AR_OBJECT_SAMPLER2D,
  90. AR_OBJECT_SAMPLER3D,
  91. AR_OBJECT_SAMPLERCUBE,
  92. AR_OBJECT_SAMPLERCOMPARISON,
  93. AR_OBJECT_BUFFER,
  94. //
  95. // View objects are only used as variable/types within the Effects
  96. // framework, for example in calls to OMSetRenderTargets.
  97. //
  98. AR_OBJECT_RENDERTARGETVIEW,
  99. AR_OBJECT_DEPTHSTENCILVIEW,
  100. //
  101. // Shader objects are only used as variable/types within the Effects
  102. // framework, for example as a result of CompileShader().
  103. //
  104. AR_OBJECT_COMPUTESHADER,
  105. AR_OBJECT_DOMAINSHADER,
  106. AR_OBJECT_GEOMETRYSHADER,
  107. AR_OBJECT_HULLSHADER,
  108. AR_OBJECT_PIXELSHADER,
  109. AR_OBJECT_VERTEXSHADER,
  110. AR_OBJECT_PIXELFRAGMENT,
  111. AR_OBJECT_VERTEXFRAGMENT,
  112. AR_OBJECT_STATEBLOCK,
  113. AR_OBJECT_RASTERIZER,
  114. AR_OBJECT_DEPTHSTENCIL,
  115. AR_OBJECT_BLEND,
  116. AR_OBJECT_POINTSTREAM,
  117. AR_OBJECT_LINESTREAM,
  118. AR_OBJECT_TRIANGLESTREAM,
  119. AR_OBJECT_INPUTPATCH,
  120. AR_OBJECT_OUTPUTPATCH,
  121. AR_OBJECT_RWTEXTURE1D,
  122. AR_OBJECT_RWTEXTURE1D_ARRAY,
  123. AR_OBJECT_RWTEXTURE2D,
  124. AR_OBJECT_RWTEXTURE2D_ARRAY,
  125. AR_OBJECT_RWTEXTURE3D,
  126. AR_OBJECT_RWBUFFER,
  127. AR_OBJECT_BYTEADDRESS_BUFFER,
  128. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  129. AR_OBJECT_STRUCTURED_BUFFER,
  130. AR_OBJECT_RWSTRUCTURED_BUFFER,
  131. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  132. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  133. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  134. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  135. AR_OBJECT_CONSTANT_BUFFER,
  136. AR_OBJECT_TEXTURE_BUFFER,
  137. AR_OBJECT_ROVBUFFER,
  138. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  139. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  140. AR_OBJECT_ROVTEXTURE1D,
  141. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  142. AR_OBJECT_ROVTEXTURE2D,
  143. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  144. AR_OBJECT_ROVTEXTURE3D,
  145. // SPIRV change starts
  146. #ifdef ENABLE_SPIRV_CODEGEN
  147. AR_OBJECT_VK_SUBPASS_INPUT,
  148. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  149. #endif // ENABLE_SPIRV_CODEGEN
  150. // SPIRV change ends
  151. AR_OBJECT_INNER, // Used for internal type object
  152. AR_OBJECT_LEGACY_EFFECT,
  153. AR_OBJECT_WAVE,
  154. AR_OBJECT_RAY_DESC,
  155. AR_OBJECT_ACCELARATION_STRUCT,
  156. AR_OBJECT_USER_DEFINED_TYPE,
  157. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  158. AR_BASIC_MAXIMUM_COUNT
  159. };
  160. #define AR_BASIC_TEXTURE_MS_CASES \
  161. case AR_OBJECT_TEXTURE2DMS: \
  162. case AR_OBJECT_TEXTURE2DMS_ARRAY
  163. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  164. case AR_OBJECT_TEXTURE1D: \
  165. case AR_OBJECT_TEXTURE1D_ARRAY: \
  166. case AR_OBJECT_TEXTURE2D: \
  167. case AR_OBJECT_TEXTURE2D_ARRAY: \
  168. case AR_OBJECT_TEXTURE3D: \
  169. case AR_OBJECT_TEXTURECUBE: \
  170. case AR_OBJECT_TEXTURECUBE_ARRAY
  171. #define AR_BASIC_TEXTURE_CASES \
  172. AR_BASIC_TEXTURE_MS_CASES: \
  173. AR_BASIC_NON_TEXTURE_MS_CASES
  174. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  175. case AR_OBJECT_SAMPLER: \
  176. case AR_OBJECT_SAMPLER1D: \
  177. case AR_OBJECT_SAMPLER2D: \
  178. case AR_OBJECT_SAMPLER3D: \
  179. case AR_OBJECT_SAMPLERCUBE
  180. #define AR_BASIC_ROBJECT_CASES \
  181. case AR_OBJECT_BLEND: \
  182. case AR_OBJECT_RASTERIZER: \
  183. case AR_OBJECT_DEPTHSTENCIL: \
  184. case AR_OBJECT_STATEBLOCK
  185. //
  186. // Properties of entries in the ArBasicKind enumeration.
  187. // These properties are intended to allow easy identification
  188. // of classes of basic kinds. More specific checks on the
  189. // actual kind values could then be done.
  190. //
  191. // The first four bits are used as a subtype indicator,
  192. // such as bit count for primitive kinds or specific
  193. // types for non-primitive-data kinds.
  194. #define BPROP_SUBTYPE_MASK 0x0000000f
  195. // Bit counts must be ordered from smaller to larger.
  196. #define BPROP_BITS0 0x00000000
  197. #define BPROP_BITS8 0x00000001
  198. #define BPROP_BITS10 0x00000002
  199. #define BPROP_BITS12 0x00000003
  200. #define BPROP_BITS16 0x00000004
  201. #define BPROP_BITS32 0x00000005
  202. #define BPROP_BITS64 0x00000006
  203. #define BPROP_BITS_NON_PRIM 0x00000007
  204. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  205. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  206. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  207. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  208. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  209. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  210. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  211. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  212. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  213. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  214. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  215. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  216. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  217. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  218. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  219. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  220. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  221. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  222. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  223. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  224. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  225. #define BPROP_ENUM 0x00800000 // Whether the type is a enum
  226. #define GET_BPROP_PRIM_KIND(_Props) \
  227. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  228. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  229. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  230. #define IS_BPROP_PRIMITIVE(_Props) \
  231. (((_Props) & BPROP_PRIMITIVE) != 0)
  232. #define IS_BPROP_BOOL(_Props) \
  233. (((_Props) & BPROP_BOOLEAN) != 0)
  234. #define IS_BPROP_FLOAT(_Props) \
  235. (((_Props) & BPROP_FLOATING) != 0)
  236. #define IS_BPROP_SINT(_Props) \
  237. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  238. BPROP_INTEGER)
  239. #define IS_BPROP_UINT(_Props) \
  240. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  241. (BPROP_INTEGER | BPROP_UNSIGNED))
  242. #define IS_BPROP_AINT(_Props) \
  243. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  244. #define IS_BPROP_STREAM(_Props) \
  245. (((_Props) & BPROP_STREAM) != 0)
  246. #define IS_BPROP_SAMPLER(_Props) \
  247. (((_Props) & BPROP_SAMPLER) != 0)
  248. #define IS_BPROP_TEXTURE(_Props) \
  249. (((_Props) & BPROP_TEXTURE) != 0)
  250. #define IS_BPROP_OBJECT(_Props) \
  251. (((_Props) & BPROP_OBJECT) != 0)
  252. #define IS_BPROP_MIN_PRECISION(_Props) \
  253. (((_Props) & BPROP_MIN_PRECISION) != 0)
  254. #define IS_BPROP_UNSIGNABLE(_Props) \
  255. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  256. #define IS_BPROP_ENUM(_Props) \
  257. (((_Props) & BPROP_ENUM) != 0)
  258. const UINT g_uBasicKindProps[] =
  259. {
  260. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  261. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  262. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  263. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  264. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  265. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  266. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  267. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  268. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  269. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  270. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  271. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  272. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  273. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  274. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  275. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  276. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  277. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  278. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  279. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  280. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  281. BPROP_OTHER, // AR_BASIC_COUNT
  282. //
  283. // Pseudo-entries for intrinsic tables and such.
  284. //
  285. 0, // AR_BASIC_NONE
  286. BPROP_OTHER, // AR_BASIC_UNKNOWN
  287. BPROP_OTHER, // AR_BASIC_NOCAST
  288. //
  289. // The following pseudo-entries represent higher-level
  290. // object types that are treated as units.
  291. //
  292. BPROP_POINTER, // AR_BASIC_POINTER
  293. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  294. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  295. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  296. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  297. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  298. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  299. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  300. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  301. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  302. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  303. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  304. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  305. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  306. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  307. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  308. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  309. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  310. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  311. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  312. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  313. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  314. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  315. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  316. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  317. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  318. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  319. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  320. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  321. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  322. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  323. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  324. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  325. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  326. BPROP_OBJECT, // AR_OBJECT_BLEND
  327. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  328. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  329. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  330. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  331. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  332. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  333. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  334. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  335. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  336. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  337. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  338. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  339. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  340. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  341. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  342. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  343. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  344. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  345. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  346. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  347. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  348. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  349. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  350. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  351. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  352. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  353. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  354. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  355. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  356. // SPIRV change starts
  357. #ifdef ENABLE_SPIRV_CODEGEN
  358. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  359. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  360. #endif // ENABLE_SPIRV_CODEGEN
  361. // SPIRV change ends
  362. BPROP_OBJECT, // AR_OBJECT_INNER
  363. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  364. BPROP_OBJECT, // AR_OBJECT_WAVE
  365. LICOMPTYPE_RAYDESC, // AR_OBJECT_RAY_DESC
  366. LICOMPTYPE_ACCELERATION_STRUCT, // AR_OBJECT_ACCELARATION_STRUCT
  367. LICOMPTYPE_USER_DEFINED_TYPE, // AR_OBJECT_USER_DEFINED_TYPE
  368. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  369. // AR_BASIC_MAXIMUM_COUNT
  370. };
  371. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  372. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  373. #define GET_BASIC_BITS(_Kind) \
  374. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  375. #define GET_BASIC_PRIM_KIND(_Kind) \
  376. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  377. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  378. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  379. #define IS_BASIC_PRIMITIVE(_Kind) \
  380. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  381. #define IS_BASIC_BOOL(_Kind) \
  382. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  383. #define IS_BASIC_FLOAT(_Kind) \
  384. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  385. #define IS_BASIC_SINT(_Kind) \
  386. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  387. #define IS_BASIC_UINT(_Kind) \
  388. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  389. #define IS_BASIC_AINT(_Kind) \
  390. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  391. #define IS_BASIC_STREAM(_Kind) \
  392. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  393. #define IS_BASIC_SAMPLER(_Kind) \
  394. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  395. #define IS_BASIC_TEXTURE(_Kind) \
  396. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  397. #define IS_BASIC_OBJECT(_Kind) \
  398. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  399. #define IS_BASIC_MIN_PRECISION(_Kind) \
  400. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  401. #define IS_BASIC_UNSIGNABLE(_Kind) \
  402. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  403. #define IS_BASIC_ENUM(_Kind) \
  404. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  405. #define BITWISE_ENUM_OPS(_Type) \
  406. inline _Type operator|(_Type F1, _Type F2) \
  407. { \
  408. return (_Type)((UINT)F1 | (UINT)F2); \
  409. } \
  410. inline _Type operator&(_Type F1, _Type F2) \
  411. { \
  412. return (_Type)((UINT)F1 & (UINT)F2); \
  413. } \
  414. inline _Type& operator|=(_Type& F1, _Type F2) \
  415. { \
  416. F1 = F1 | F2; \
  417. return F1; \
  418. } \
  419. inline _Type& operator&=(_Type& F1, _Type F2) \
  420. { \
  421. F1 = F1 & F2; \
  422. return F1; \
  423. } \
  424. inline _Type& operator&=(_Type& F1, UINT F2) \
  425. { \
  426. F1 = (_Type)((UINT)F1 & F2); \
  427. return F1; \
  428. }
  429. enum ArTypeObjectKind {
  430. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  431. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  432. AR_TOBJ_BASIC, // Represents a primitive type.
  433. AR_TOBJ_COMPOUND, // Represents a struct or class.
  434. AR_TOBJ_INTERFACE, // Represents an interface.
  435. AR_TOBJ_POINTER, // Represents a pointer to another type.
  436. AR_TOBJ_OBJECT, // Represents a built-in object.
  437. AR_TOBJ_ARRAY, // Represents an array of other types.
  438. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  439. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  440. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  441. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  442. // indexer object used to implement .mips[1].
  443. };
  444. enum TYPE_CONVERSION_FLAGS
  445. {
  446. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  447. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  448. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  449. };
  450. enum TYPE_CONVERSION_REMARKS
  451. {
  452. TYPE_CONVERSION_NONE = 0x00000000,
  453. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  454. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  455. TYPE_CONVERSION_TO_VOID = 0x00000004,
  456. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  457. };
  458. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  459. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  460. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  461. #define AR_TPROP_VOID 0x0000000000000001
  462. #define AR_TPROP_CONST 0x0000000000000002
  463. #define AR_TPROP_IMP_CONST 0x0000000000000004
  464. #define AR_TPROP_OBJECT 0x0000000000000008
  465. #define AR_TPROP_SCALAR 0x0000000000000010
  466. #define AR_TPROP_UNSIGNED 0x0000000000000020
  467. #define AR_TPROP_NUMERIC 0x0000000000000040
  468. #define AR_TPROP_INTEGRAL 0x0000000000000080
  469. #define AR_TPROP_FLOATING 0x0000000000000100
  470. #define AR_TPROP_LITERAL 0x0000000000000200
  471. #define AR_TPROP_POINTER 0x0000000000000400
  472. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  473. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  474. #define AR_TPROP_INH_IFACE 0x0000000000002000
  475. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  476. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  477. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  478. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  479. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  480. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  481. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  482. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  483. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  484. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  485. #define AR_TPROP_INDEXABLE 0x0000000001000000
  486. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  487. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  488. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  489. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  490. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  491. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  492. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  493. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  494. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  495. #define AR_TPROP_ALL 0xffffffffffffffff
  496. #define AR_TPROP_HAS_OBJECTS \
  497. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  498. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  499. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  500. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  501. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  502. #define AR_TPROP_HAS_BASIC_RESOURCES \
  503. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  504. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  505. AR_TPROP_HAS_UAVS)
  506. #define AR_TPROP_UNION_BITS \
  507. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  508. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  509. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  510. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  511. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  512. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  513. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  514. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  515. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  516. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  517. #define AR_TINFO_PACK_SCALAR 0x00000010
  518. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  519. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  520. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  521. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  522. #define AR_TINFO_PACK_CBUFFER 0
  523. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  524. #define AR_TINFO_SIMPLE_OBJECTS \
  525. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  526. struct ArTypeInfo {
  527. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  528. ArBasicKind EltKind; // The primitive type of elements in this type.
  529. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  530. UINT uRows;
  531. UINT uCols;
  532. UINT uTotalElts;
  533. };
  534. using namespace clang;
  535. using namespace clang::sema;
  536. using namespace hlsl;
  537. extern const char *HLSLScalarTypeNames[];
  538. static const int FirstTemplateDepth = 0;
  539. static const int FirstParamPosition = 0;
  540. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  541. static const bool InheritedFalse = false; // template parameter default value is not inherited.
  542. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  543. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  544. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  545. static const bool DelayTypeCreationFalse = false; // immediately create a type when the declaration is created
  546. static const unsigned int NoQuals = 0; // no qualifiers in effect
  547. static const SourceLocation NoLoc; // no source location attribution available
  548. static const SourceRange NoRange; // no source range attribution available
  549. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  550. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  551. static const bool IsConstexprFalse = false; // function is not constexpr
  552. static const bool ListInitializationFalse = false;// not performing a list initialization
  553. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  554. static const bool SuppressWarningsTrue = true; // suppress warning diagnostics
  555. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  556. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  557. static const int OneRow = 1; // a single row for a type
  558. static const bool MipsFalse = false; // a type does not support the .mips member
  559. static const bool MipsTrue = true; // a type supports the .mips member
  560. static const bool SampleFalse = false; // a type does not support the .sample member
  561. static const bool SampleTrue = true; // a type supports the .sample member
  562. static const size_t MaxVectorSize = 4; // maximum size for a vector
  563. static
  564. QualType GetOrCreateTemplateSpecialization(
  565. ASTContext& context,
  566. Sema& sema,
  567. _In_ ClassTemplateDecl* templateDecl,
  568. ArrayRef<TemplateArgument> templateArgs
  569. )
  570. {
  571. DXASSERT_NOMSG(templateDecl);
  572. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  573. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  574. for (const TemplateArgument& Arg : templateArgs) {
  575. if (Arg.getKind() == TemplateArgument::Type) {
  576. // the class template need to use CanonicalType
  577. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  578. }else
  579. templateArgsForDecl.emplace_back(Arg);
  580. }
  581. // First, try looking up existing specialization
  582. void* InsertPos = nullptr;
  583. ClassTemplateSpecializationDecl* specializationDecl =
  584. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  585. if (specializationDecl) {
  586. // Instantiate the class template if not yet.
  587. if (specializationDecl->getInstantiatedFrom().isNull()) {
  588. // InstantiateClassTemplateSpecialization returns true if it finds an
  589. // error.
  590. DXVERIFY_NOMSG(false ==
  591. sema.InstantiateClassTemplateSpecialization(
  592. NoLoc, specializationDecl,
  593. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  594. true));
  595. }
  596. return context.getTemplateSpecializationType(
  597. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  598. context.getTypeDeclType(specializationDecl));
  599. }
  600. specializationDecl = ClassTemplateSpecializationDecl::Create(
  601. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  602. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  603. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  604. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  605. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  606. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  607. specializationDecl->setImplicit(true);
  608. QualType canonType = context.getTypeDeclType(specializationDecl);
  609. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  610. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  611. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  612. for (unsigned i = 0; i < templateArgs.size(); i++) {
  613. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  614. }
  615. return context.getTemplateSpecializationType(
  616. TemplateName(templateDecl), templateArgumentList, canonType);
  617. }
  618. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  619. static
  620. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  621. _In_ ClassTemplateDecl* matrixTemplateDecl,
  622. QualType elementType, uint64_t rowCount, uint64_t colCount)
  623. {
  624. DXASSERT_NOMSG(sema);
  625. TemplateArgument templateArgs[3] = {
  626. TemplateArgument(elementType),
  627. TemplateArgument(
  628. context,
  629. llvm::APSInt(
  630. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  631. context.IntTy),
  632. TemplateArgument(
  633. context,
  634. llvm::APSInt(
  635. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  636. context.IntTy)};
  637. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  638. #ifdef DBG
  639. // Verify that we can read the field member from the template record.
  640. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  641. "type of non-dependent specialization is not a RecordType");
  642. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  643. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  644. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  645. #endif
  646. return matrixSpecializationType;
  647. }
  648. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  649. static
  650. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  651. _In_ ClassTemplateDecl* vectorTemplateDecl,
  652. QualType elementType, uint64_t colCount)
  653. {
  654. DXASSERT_NOMSG(sema);
  655. DXASSERT_NOMSG(vectorTemplateDecl);
  656. TemplateArgument templateArgs[2] = {
  657. TemplateArgument(elementType),
  658. TemplateArgument(
  659. context,
  660. llvm::APSInt(
  661. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  662. context.IntTy)};
  663. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  664. #ifdef DBG
  665. // Verify that we can read the field member from the template record.
  666. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  667. "type of non-dependent specialization is not a RecordType");
  668. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  669. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  670. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  671. #endif
  672. return vectorSpecializationType;
  673. }
  674. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  675. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  676. static const unsigned kAtomicDstOperandIdx = 1;
  677. static const ArTypeObjectKind g_ScalarTT[] =
  678. {
  679. AR_TOBJ_SCALAR,
  680. AR_TOBJ_UNKNOWN
  681. };
  682. static const ArTypeObjectKind g_VectorTT[] =
  683. {
  684. AR_TOBJ_VECTOR,
  685. AR_TOBJ_UNKNOWN
  686. };
  687. static const ArTypeObjectKind g_MatrixTT[] =
  688. {
  689. AR_TOBJ_MATRIX,
  690. AR_TOBJ_UNKNOWN
  691. };
  692. static const ArTypeObjectKind g_AnyTT[] =
  693. {
  694. AR_TOBJ_SCALAR,
  695. AR_TOBJ_VECTOR,
  696. AR_TOBJ_MATRIX,
  697. AR_TOBJ_UNKNOWN
  698. };
  699. static const ArTypeObjectKind g_ObjectTT[] =
  700. {
  701. AR_TOBJ_OBJECT,
  702. AR_TOBJ_UNKNOWN
  703. };
  704. static const ArTypeObjectKind g_NullTT[] =
  705. {
  706. AR_TOBJ_VOID,
  707. AR_TOBJ_UNKNOWN
  708. };
  709. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  710. {
  711. g_NullTT,
  712. g_ScalarTT,
  713. g_VectorTT,
  714. g_MatrixTT,
  715. g_AnyTT,
  716. g_ObjectTT,
  717. };
  718. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  719. //
  720. // The first one is used to name the representative group, so make
  721. // sure its name will make sense in error messages.
  722. //
  723. static const ArBasicKind g_BoolCT[] =
  724. {
  725. AR_BASIC_BOOL,
  726. AR_BASIC_UNKNOWN
  727. };
  728. static const ArBasicKind g_IntCT[] =
  729. {
  730. AR_BASIC_INT32,
  731. AR_BASIC_LITERAL_INT,
  732. AR_BASIC_UNKNOWN
  733. };
  734. static const ArBasicKind g_UIntCT[] =
  735. {
  736. AR_BASIC_UINT32,
  737. AR_BASIC_LITERAL_INT,
  738. AR_BASIC_UNKNOWN
  739. };
  740. // We use the first element for default if matching kind is missing in the list.
  741. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  742. static const ArBasicKind g_AnyIntCT[] =
  743. {
  744. AR_BASIC_INT32,
  745. AR_BASIC_INT16,
  746. AR_BASIC_UINT32,
  747. AR_BASIC_UINT16,
  748. AR_BASIC_INT64,
  749. AR_BASIC_UINT64,
  750. AR_BASIC_LITERAL_INT,
  751. AR_BASIC_UNKNOWN
  752. };
  753. static const ArBasicKind g_AnyInt32CT[] =
  754. {
  755. AR_BASIC_INT32,
  756. AR_BASIC_UINT32,
  757. AR_BASIC_LITERAL_INT,
  758. AR_BASIC_UNKNOWN
  759. };
  760. static const ArBasicKind g_UIntOnlyCT[] =
  761. {
  762. AR_BASIC_UINT32,
  763. AR_BASIC_UINT64,
  764. AR_BASIC_LITERAL_INT,
  765. AR_BASIC_NOCAST,
  766. AR_BASIC_UNKNOWN
  767. };
  768. static const ArBasicKind g_FloatCT[] =
  769. {
  770. AR_BASIC_FLOAT32,
  771. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  772. AR_BASIC_LITERAL_FLOAT,
  773. AR_BASIC_UNKNOWN
  774. };
  775. static const ArBasicKind g_AnyFloatCT[] =
  776. {
  777. AR_BASIC_FLOAT32,
  778. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  779. AR_BASIC_FLOAT16,
  780. AR_BASIC_FLOAT64,
  781. AR_BASIC_LITERAL_FLOAT,
  782. AR_BASIC_MIN10FLOAT,
  783. AR_BASIC_MIN16FLOAT,
  784. AR_BASIC_UNKNOWN
  785. };
  786. static const ArBasicKind g_FloatLikeCT[] =
  787. {
  788. AR_BASIC_FLOAT32,
  789. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  790. AR_BASIC_FLOAT16,
  791. AR_BASIC_LITERAL_FLOAT,
  792. AR_BASIC_MIN10FLOAT,
  793. AR_BASIC_MIN16FLOAT,
  794. AR_BASIC_UNKNOWN
  795. };
  796. static const ArBasicKind g_FloatDoubleCT[] =
  797. {
  798. AR_BASIC_FLOAT32,
  799. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  800. AR_BASIC_FLOAT64,
  801. AR_BASIC_LITERAL_FLOAT,
  802. AR_BASIC_UNKNOWN
  803. };
  804. static const ArBasicKind g_DoubleCT[] =
  805. {
  806. AR_BASIC_FLOAT64,
  807. AR_BASIC_LITERAL_FLOAT,
  808. AR_BASIC_UNKNOWN
  809. };
  810. static const ArBasicKind g_DoubleOnlyCT[] =
  811. {
  812. AR_BASIC_FLOAT64,
  813. AR_BASIC_NOCAST,
  814. AR_BASIC_UNKNOWN
  815. };
  816. static const ArBasicKind g_NumericCT[] =
  817. {
  818. AR_BASIC_LITERAL_FLOAT,
  819. AR_BASIC_FLOAT32,
  820. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  821. AR_BASIC_FLOAT16,
  822. AR_BASIC_FLOAT64,
  823. AR_BASIC_MIN10FLOAT,
  824. AR_BASIC_MIN16FLOAT,
  825. AR_BASIC_LITERAL_INT,
  826. AR_BASIC_INT16,
  827. AR_BASIC_INT32,
  828. AR_BASIC_UINT16,
  829. AR_BASIC_UINT32,
  830. AR_BASIC_MIN12INT,
  831. AR_BASIC_MIN16INT,
  832. AR_BASIC_MIN16UINT,
  833. AR_BASIC_INT64,
  834. AR_BASIC_UINT64,
  835. AR_BASIC_UNKNOWN
  836. };
  837. static const ArBasicKind g_Numeric32CT[] =
  838. {
  839. AR_BASIC_LITERAL_FLOAT,
  840. AR_BASIC_FLOAT32,
  841. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  842. AR_BASIC_LITERAL_INT,
  843. AR_BASIC_INT32,
  844. AR_BASIC_UINT32,
  845. AR_BASIC_UNKNOWN
  846. };
  847. static const ArBasicKind g_Numeric32OnlyCT[] =
  848. {
  849. AR_BASIC_LITERAL_FLOAT,
  850. AR_BASIC_FLOAT32,
  851. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  852. AR_BASIC_LITERAL_INT,
  853. AR_BASIC_INT32,
  854. AR_BASIC_UINT32,
  855. AR_BASIC_NOCAST,
  856. AR_BASIC_UNKNOWN
  857. };
  858. static const ArBasicKind g_AnyCT[] =
  859. {
  860. AR_BASIC_LITERAL_FLOAT,
  861. AR_BASIC_FLOAT32,
  862. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  863. AR_BASIC_FLOAT16,
  864. AR_BASIC_FLOAT64,
  865. AR_BASIC_MIN10FLOAT,
  866. AR_BASIC_MIN16FLOAT,
  867. AR_BASIC_LITERAL_INT,
  868. AR_BASIC_INT16,
  869. AR_BASIC_UINT16,
  870. AR_BASIC_INT32,
  871. AR_BASIC_UINT32,
  872. AR_BASIC_MIN12INT,
  873. AR_BASIC_MIN16INT,
  874. AR_BASIC_MIN16UINT,
  875. AR_BASIC_BOOL,
  876. AR_BASIC_INT64,
  877. AR_BASIC_UINT64,
  878. AR_BASIC_UNKNOWN
  879. };
  880. static const ArBasicKind g_Sampler1DCT[] =
  881. {
  882. AR_OBJECT_SAMPLER1D,
  883. AR_BASIC_UNKNOWN
  884. };
  885. static const ArBasicKind g_Sampler2DCT[] =
  886. {
  887. AR_OBJECT_SAMPLER2D,
  888. AR_BASIC_UNKNOWN
  889. };
  890. static const ArBasicKind g_Sampler3DCT[] =
  891. {
  892. AR_OBJECT_SAMPLER3D,
  893. AR_BASIC_UNKNOWN
  894. };
  895. static const ArBasicKind g_SamplerCUBECT[] =
  896. {
  897. AR_OBJECT_SAMPLERCUBE,
  898. AR_BASIC_UNKNOWN
  899. };
  900. static const ArBasicKind g_SamplerCmpCT[] =
  901. {
  902. AR_OBJECT_SAMPLERCOMPARISON,
  903. AR_BASIC_UNKNOWN
  904. };
  905. static const ArBasicKind g_SamplerCT[] =
  906. {
  907. AR_OBJECT_SAMPLER,
  908. AR_BASIC_UNKNOWN
  909. };
  910. static const ArBasicKind g_RayDescCT[] =
  911. {
  912. AR_OBJECT_RAY_DESC,
  913. AR_BASIC_UNKNOWN
  914. };
  915. static const ArBasicKind g_AccelarationStructCT[] =
  916. {
  917. AR_OBJECT_ACCELARATION_STRUCT,
  918. AR_BASIC_UNKNOWN
  919. };
  920. static const ArBasicKind g_UDTCT[] =
  921. {
  922. AR_OBJECT_USER_DEFINED_TYPE,
  923. AR_BASIC_UNKNOWN
  924. };
  925. static const ArBasicKind g_StringCT[] =
  926. {
  927. AR_OBJECT_STRING,
  928. AR_BASIC_UNKNOWN
  929. };
  930. static const ArBasicKind g_NullCT[] =
  931. {
  932. AR_OBJECT_NULL,
  933. AR_BASIC_UNKNOWN
  934. };
  935. static const ArBasicKind g_WaveCT[] =
  936. {
  937. AR_OBJECT_WAVE,
  938. AR_BASIC_UNKNOWN
  939. };
  940. static const ArBasicKind g_UInt64CT[] =
  941. {
  942. AR_BASIC_UINT64,
  943. AR_BASIC_UNKNOWN
  944. };
  945. static const ArBasicKind g_Float16CT[] =
  946. {
  947. AR_BASIC_FLOAT16,
  948. AR_BASIC_LITERAL_FLOAT,
  949. AR_BASIC_UNKNOWN
  950. };
  951. static const ArBasicKind g_Int16CT[] =
  952. {
  953. AR_BASIC_INT16,
  954. AR_BASIC_LITERAL_INT,
  955. AR_BASIC_UNKNOWN
  956. };
  957. static const ArBasicKind g_UInt16CT[] =
  958. {
  959. AR_BASIC_UINT16,
  960. AR_BASIC_LITERAL_INT,
  961. AR_BASIC_UNKNOWN
  962. };
  963. static const ArBasicKind g_Numeric16OnlyCT[] =
  964. {
  965. AR_BASIC_FLOAT16,
  966. AR_BASIC_INT16,
  967. AR_BASIC_UINT16,
  968. AR_BASIC_LITERAL_FLOAT,
  969. AR_BASIC_LITERAL_INT,
  970. AR_BASIC_NOCAST,
  971. AR_BASIC_UNKNOWN
  972. };
  973. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  974. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  975. {
  976. g_NullCT, // LICOMPTYPE_VOID
  977. g_BoolCT, // LICOMPTYPE_BOOL
  978. g_IntCT, // LICOMPTYPE_INT
  979. g_UIntCT, // LICOMPTYPE_UINT
  980. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  981. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  982. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  983. g_FloatCT, // LICOMPTYPE_FLOAT
  984. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  985. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  986. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  987. g_DoubleCT, // LICOMPTYPE_DOUBLE
  988. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  989. g_NumericCT, // LICOMPTYPE_NUMERIC
  990. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  991. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  992. g_AnyCT, // LICOMPTYPE_ANY
  993. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  994. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  995. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  996. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  997. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  998. g_SamplerCT, // LICOMPTYPE_SAMPLER
  999. g_StringCT, // LICOMPTYPE_STRING
  1000. g_WaveCT, // LICOMPTYPE_WAVE
  1001. g_UInt64CT, // LICOMPTYPE_UINT64
  1002. g_Float16CT, // LICOMPTYPE_FLOAT16
  1003. g_Int16CT, // LICOMPTYPE_INT16
  1004. g_UInt16CT, // LICOMPTYPE_UINT16
  1005. g_Numeric16OnlyCT, // LICOMPTYPE_NUMERIC16_ONLY
  1006. g_RayDescCT, // LICOMPTYPE_RAYDESC
  1007. g_AccelarationStructCT, // LICOMPTYPE_ACCELERATION_STRUCT,
  1008. g_UDTCT, // LICOMPTYPE_USER_DEFINED_TYPE
  1009. };
  1010. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT);
  1011. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  1012. // Basic kind objects that are represented as HLSL structures or templates.
  1013. static
  1014. const ArBasicKind g_ArBasicKindsAsTypes[] =
  1015. {
  1016. AR_OBJECT_BUFFER, // Buffer
  1017. // AR_OBJECT_TEXTURE,
  1018. AR_OBJECT_TEXTURE1D, // Texture1D
  1019. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1020. AR_OBJECT_TEXTURE2D, // Texture2D
  1021. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1022. AR_OBJECT_TEXTURE3D, // Texture3D
  1023. AR_OBJECT_TEXTURECUBE, // TextureCube
  1024. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1025. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1026. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1027. AR_OBJECT_SAMPLER,
  1028. //AR_OBJECT_SAMPLER1D,
  1029. //AR_OBJECT_SAMPLER2D,
  1030. //AR_OBJECT_SAMPLER3D,
  1031. //AR_OBJECT_SAMPLERCUBE,
  1032. AR_OBJECT_SAMPLERCOMPARISON,
  1033. AR_OBJECT_POINTSTREAM,
  1034. AR_OBJECT_LINESTREAM,
  1035. AR_OBJECT_TRIANGLESTREAM,
  1036. AR_OBJECT_INPUTPATCH,
  1037. AR_OBJECT_OUTPUTPATCH,
  1038. AR_OBJECT_RWTEXTURE1D,
  1039. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1040. AR_OBJECT_RWTEXTURE2D,
  1041. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1042. AR_OBJECT_RWTEXTURE3D,
  1043. AR_OBJECT_RWBUFFER,
  1044. AR_OBJECT_BYTEADDRESS_BUFFER,
  1045. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1046. AR_OBJECT_STRUCTURED_BUFFER,
  1047. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1048. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1049. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1050. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1051. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1052. AR_OBJECT_ROVBUFFER,
  1053. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1054. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1055. AR_OBJECT_ROVTEXTURE1D,
  1056. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1057. AR_OBJECT_ROVTEXTURE2D,
  1058. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1059. AR_OBJECT_ROVTEXTURE3D,
  1060. // SPIRV change starts
  1061. #ifdef ENABLE_SPIRV_CODEGEN
  1062. AR_OBJECT_VK_SUBPASS_INPUT,
  1063. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1064. #endif // ENABLE_SPIRV_CODEGEN
  1065. // SPIRV change ends
  1066. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1067. AR_OBJECT_WAVE,
  1068. AR_OBJECT_RAY_DESC,
  1069. AR_OBJECT_ACCELARATION_STRUCT,
  1070. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  1071. };
  1072. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1073. static
  1074. const uint8_t g_ArBasicKindsTemplateCount[] =
  1075. {
  1076. 1, // AR_OBJECT_BUFFER
  1077. // AR_OBJECT_TEXTURE,
  1078. 1, // AR_OBJECT_TEXTURE1D
  1079. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1080. 1, // AR_OBJECT_TEXTURE2D
  1081. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1082. 1, // AR_OBJECT_TEXTURE3D
  1083. 1, // AR_OBJECT_TEXTURECUBE
  1084. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1085. 2, // AR_OBJECT_TEXTURE2DMS
  1086. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1087. 0, // AR_OBJECT_SAMPLER
  1088. //AR_OBJECT_SAMPLER1D,
  1089. //AR_OBJECT_SAMPLER2D,
  1090. //AR_OBJECT_SAMPLER3D,
  1091. //AR_OBJECT_SAMPLERCUBE,
  1092. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1093. 1, // AR_OBJECT_POINTSTREAM
  1094. 1, // AR_OBJECT_LINESTREAM
  1095. 1, // AR_OBJECT_TRIANGLESTREAM
  1096. 2, // AR_OBJECT_INPUTPATCH
  1097. 2, // AR_OBJECT_OUTPUTPATCH
  1098. 1, // AR_OBJECT_RWTEXTURE1D
  1099. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1100. 1, // AR_OBJECT_RWTEXTURE2D
  1101. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1102. 1, // AR_OBJECT_RWTEXTURE3D
  1103. 1, // AR_OBJECT_RWBUFFER
  1104. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1105. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1106. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1107. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1108. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1109. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1110. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1111. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1112. 1, // AR_OBJECT_ROVBUFFER
  1113. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1114. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1115. 1, // AR_OBJECT_ROVTEXTURE1D
  1116. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1117. 1, // AR_OBJECT_ROVTEXTURE2D
  1118. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1119. 1, // AR_OBJECT_ROVTEXTURE3D
  1120. // SPIRV change starts
  1121. #ifdef ENABLE_SPIRV_CODEGEN
  1122. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1123. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1124. #endif // ENABLE_SPIRV_CODEGEN
  1125. // SPIRV change ends
  1126. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1127. 0, // AR_OBJECT_WAVE
  1128. 0, // AR_OBJECT_RAY_DESC
  1129. 0, // AR_OBJECT_ACCELARATION_STRUCT
  1130. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1131. };
  1132. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1133. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1134. struct SubscriptOperatorRecord
  1135. {
  1136. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1137. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1138. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1139. };
  1140. // Subscript operators for objects that are represented as HLSL structures or templates.
  1141. static
  1142. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1143. {
  1144. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1145. // AR_OBJECT_TEXTURE,
  1146. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1147. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1148. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1149. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1150. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1151. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1152. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1153. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1154. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1155. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1156. //AR_OBJECT_SAMPLER1D,
  1157. //AR_OBJECT_SAMPLER2D,
  1158. //AR_OBJECT_SAMPLER3D,
  1159. //AR_OBJECT_SAMPLERCUBE,
  1160. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1161. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1162. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1163. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1164. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1165. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1166. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1167. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1168. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1169. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1170. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1171. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1172. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1173. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1174. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1175. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1176. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1177. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1178. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1179. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1180. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1181. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1182. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1183. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1184. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1185. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1186. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1187. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1188. // SPIRV change starts
  1189. #ifdef ENABLE_SPIRV_CODEGEN
  1190. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1191. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1192. #endif // ENABLE_SPIRV_CODEGEN
  1193. // SPIRV change ends
  1194. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1195. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_WAVE
  1196. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_DESC
  1197. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ACCELARATION_STRUCT
  1198. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1199. };
  1200. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1201. // Type names for ArBasicKind values.
  1202. static
  1203. const char* g_ArBasicTypeNames[] =
  1204. {
  1205. "bool", "float", "half", "half", "float", "double",
  1206. "int", "sbyte", "byte", "short", "ushort",
  1207. "int", "uint", "long", "ulong",
  1208. "min10float", "min16float",
  1209. "min12int", "min16int", "min16uint",
  1210. "enum",
  1211. "<count>",
  1212. "<none>",
  1213. "<unknown>",
  1214. "<nocast>",
  1215. "<pointer>",
  1216. "enum class",
  1217. "null",
  1218. "string",
  1219. // "texture",
  1220. "Texture1D",
  1221. "Texture1DArray",
  1222. "Texture2D",
  1223. "Texture2DArray",
  1224. "Texture3D",
  1225. "TextureCube",
  1226. "TextureCubeArray",
  1227. "Texture2DMS",
  1228. "Texture2DMSArray",
  1229. "SamplerState",
  1230. "sampler1D",
  1231. "sampler2D",
  1232. "sampler3D",
  1233. "samplerCUBE",
  1234. "SamplerComparisonState",
  1235. "Buffer",
  1236. "RenderTargetView",
  1237. "DepthStencilView",
  1238. "ComputeShader",
  1239. "DomainShader",
  1240. "GeometryShader",
  1241. "HullShader",
  1242. "PixelShader",
  1243. "VertexShader",
  1244. "pixelfragment",
  1245. "vertexfragment",
  1246. "StateBlock",
  1247. "Rasterizer",
  1248. "DepthStencil",
  1249. "Blend",
  1250. "PointStream",
  1251. "LineStream",
  1252. "TriangleStream",
  1253. "InputPatch",
  1254. "OutputPatch",
  1255. "RWTexture1D",
  1256. "RWTexture1DArray",
  1257. "RWTexture2D",
  1258. "RWTexture2DArray",
  1259. "RWTexture3D",
  1260. "RWBuffer",
  1261. "ByteAddressBuffer",
  1262. "RWByteAddressBuffer",
  1263. "StructuredBuffer",
  1264. "RWStructuredBuffer",
  1265. "RWStructuredBuffer(Incrementable)",
  1266. "RWStructuredBuffer(Decrementable)",
  1267. "AppendStructuredBuffer",
  1268. "ConsumeStructuredBuffer",
  1269. "ConstantBuffer",
  1270. "TextureBuffer",
  1271. "RasterizerOrderedBuffer",
  1272. "RasterizerOrderedByteAddressBuffer",
  1273. "RasterizerOrderedStructuredBuffer",
  1274. "RasterizerOrderedTexture1D",
  1275. "RasterizerOrderedTexture1DArray",
  1276. "RasterizerOrderedTexture2D",
  1277. "RasterizerOrderedTexture2DArray",
  1278. "RasterizerOrderedTexture3D",
  1279. // SPIRV change starts
  1280. #ifdef ENABLE_SPIRV_CODEGEN
  1281. "SubpassInput",
  1282. "SubpassInputMS",
  1283. #endif // ENABLE_SPIRV_CODEGEN
  1284. // SPIRV change ends
  1285. "<internal inner type object>",
  1286. "deprecated effect object",
  1287. "wave_t",
  1288. "RayDesc",
  1289. "RaytracingAccelerationStructure",
  1290. "user defined type",
  1291. "BuiltInTriangleIntersectionAttributes"
  1292. };
  1293. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1294. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1295. #define DXASSERT_VALIDBASICKIND(kind) \
  1296. DXASSERT(\
  1297. kind != AR_BASIC_COUNT && \
  1298. kind != AR_BASIC_NONE && \
  1299. kind != AR_BASIC_UNKNOWN && \
  1300. kind != AR_BASIC_NOCAST && \
  1301. kind != AR_BASIC_POINTER && \
  1302. kind != AR_OBJECT_RENDERTARGETVIEW && \
  1303. kind != AR_OBJECT_DEPTHSTENCILVIEW && \
  1304. kind != AR_OBJECT_COMPUTESHADER && \
  1305. kind != AR_OBJECT_DOMAINSHADER && \
  1306. kind != AR_OBJECT_GEOMETRYSHADER && \
  1307. kind != AR_OBJECT_HULLSHADER && \
  1308. kind != AR_OBJECT_PIXELSHADER && \
  1309. kind != AR_OBJECT_VERTEXSHADER && \
  1310. kind != AR_OBJECT_PIXELFRAGMENT && \
  1311. kind != AR_OBJECT_VERTEXFRAGMENT, "otherwise caller is using a special flag or an unsupported kind value");
  1312. static
  1313. const char* g_DeprecatedEffectObjectNames[] =
  1314. {
  1315. // These are case insensitive in fxc, but we'll just create two case aliases
  1316. // to capture the majority of cases
  1317. "texture", "Texture",
  1318. "pixelshader", "PixelShader",
  1319. "vertexshader", "VertexShader",
  1320. // These are case sensitive in fxc
  1321. "pixelfragment", // 13
  1322. "vertexfragment", // 14
  1323. "ComputeShader", // 13
  1324. "DomainShader", // 12
  1325. "GeometryShader", // 14
  1326. "HullShader", // 10
  1327. "BlendState", // 10
  1328. "DepthStencilState",// 17
  1329. "DepthStencilView", // 16
  1330. "RasterizerState", // 15
  1331. "RenderTargetView", // 16
  1332. };
  1333. // The CompareStringsWithLen function lexicographically compares LHS and RHS and
  1334. // returns a value indicating the relationship between the strings - < 0 if LHS is
  1335. // less than RHS, 0 if they are equal, > 0 if LHS is greater than RHS.
  1336. static
  1337. int CompareStringsWithLen(
  1338. _In_count_(LHSlen) const char* LHS, size_t LHSlen,
  1339. _In_count_(RHSlen) const char* RHS, size_t RHSlen
  1340. )
  1341. {
  1342. // Check whether the name is greater or smaller (without walking past end).
  1343. size_t maxNameComparable = std::min(LHSlen, RHSlen);
  1344. int comparison = strncmp(LHS, RHS, maxNameComparable);
  1345. if (comparison != 0) return comparison;
  1346. // Check whether the name is greater or smaller based on extra characters.
  1347. return LHSlen - RHSlen;
  1348. }
  1349. static hlsl::ParameterModifier
  1350. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1351. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1352. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1353. }
  1354. if (pArg->qwUsage == AR_QUAL_OUT) {
  1355. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1356. }
  1357. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1358. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1359. }
  1360. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1361. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1362. // The first argument is the return value, which isn't included.
  1363. for (UINT i = 1; i < pIntrinsic->uNumArgs; ++i) {
  1364. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1365. }
  1366. }
  1367. static bool IsAtomicOperation(IntrinsicOp op) {
  1368. switch (op) {
  1369. case IntrinsicOp::IOP_InterlockedAdd:
  1370. case IntrinsicOp::IOP_InterlockedAnd:
  1371. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1372. case IntrinsicOp::IOP_InterlockedCompareStore:
  1373. case IntrinsicOp::IOP_InterlockedExchange:
  1374. case IntrinsicOp::IOP_InterlockedMax:
  1375. case IntrinsicOp::IOP_InterlockedMin:
  1376. case IntrinsicOp::IOP_InterlockedOr:
  1377. case IntrinsicOp::IOP_InterlockedXor:
  1378. case IntrinsicOp::MOP_InterlockedAdd:
  1379. case IntrinsicOp::MOP_InterlockedAnd:
  1380. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1381. case IntrinsicOp::MOP_InterlockedCompareStore:
  1382. case IntrinsicOp::MOP_InterlockedExchange:
  1383. case IntrinsicOp::MOP_InterlockedMax:
  1384. case IntrinsicOp::MOP_InterlockedMin:
  1385. case IntrinsicOp::MOP_InterlockedOr:
  1386. case IntrinsicOp::MOP_InterlockedXor:
  1387. return true;
  1388. default:
  1389. return false;
  1390. }
  1391. }
  1392. static bool IsBuiltinTable(LPCSTR tableName) {
  1393. return tableName == kBuiltinIntrinsicTableName;
  1394. }
  1395. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1396. LPCSTR tableName, LPCSTR lowering,
  1397. const HLSL_INTRINSIC *pIntrinsic) {
  1398. unsigned opcode = (unsigned)pIntrinsic->Op;
  1399. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1400. QualType Ty = FD->getReturnType();
  1401. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(pIntrinsic->Op);
  1402. if (pIntrinsic->iOverloadParamIndex != -1) {
  1403. const FunctionProtoType *FT =
  1404. FD->getFunctionType()->getAs<FunctionProtoType>();
  1405. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1406. }
  1407. // TODO: refine the code for getting element type
  1408. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1409. Ty = VecTy->getElementType();
  1410. }
  1411. if (Ty->isUnsignedIntegerType()) {
  1412. opcode = hlsl::GetUnsignedOpcode(opcode);
  1413. }
  1414. }
  1415. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1416. if (pIntrinsic->bReadNone)
  1417. FD->addAttr(ConstAttr::CreateImplicit(context));
  1418. if (pIntrinsic->bReadOnly)
  1419. FD->addAttr(PureAttr::CreateImplicit(context));
  1420. }
  1421. static
  1422. FunctionDecl *AddHLSLIntrinsicFunction(
  1423. ASTContext &context, _In_ NamespaceDecl *NS,
  1424. LPCSTR tableName, LPCSTR lowering,
  1425. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1426. _In_count_(functionArgTypeCount) QualType *functionArgQualTypes,
  1427. _In_range_(0, g_MaxIntrinsicParamCount - 1) size_t functionArgTypeCount) {
  1428. DXASSERT(functionArgTypeCount - 1 <= g_MaxIntrinsicParamCount,
  1429. "otherwise g_MaxIntrinsicParamCount should be larger");
  1430. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1431. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1432. InitParamMods(pIntrinsic, paramMods);
  1433. // Change dest address into reference type for atomic.
  1434. if (IsBuiltinTable(tableName)) {
  1435. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1436. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1437. "else operation was misrecognized");
  1438. functionArgQualTypes[kAtomicDstOperandIdx] =
  1439. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1440. }
  1441. }
  1442. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1443. // Change out/inout param to reference type.
  1444. if (paramMods[i-1].isAnyOut()) {
  1445. QualType Ty = functionArgQualTypes[i];
  1446. // Aggregate type will be indirect param convert to pointer type.
  1447. // Don't need add reference for it.
  1448. if ((!Ty->isArrayType() && !Ty->isRecordType()) ||
  1449. hlsl::IsHLSLVecMatType(Ty)) {
  1450. functionArgQualTypes[i] = context.getLValueReferenceType(Ty);
  1451. }
  1452. }
  1453. }
  1454. IdentifierInfo &functionId = context.Idents.get(
  1455. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1456. DeclarationName functionName(&functionId);
  1457. QualType returnQualType = functionArgQualTypes[0];
  1458. QualType functionType = context.getFunctionType(
  1459. functionArgQualTypes[0],
  1460. ArrayRef<QualType>(functionArgQualTypes + 1,
  1461. functionArgQualTypes + functionArgTypeCount),
  1462. clang::FunctionProtoType::ExtProtoInfo(), paramMods);
  1463. FunctionDecl *functionDecl = FunctionDecl::Create(
  1464. context, currentDeclContext, NoLoc,
  1465. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1466. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1467. currentDeclContext->addDecl(functionDecl);
  1468. functionDecl->setLexicalDeclContext(currentDeclContext);
  1469. // put under hlsl namespace
  1470. functionDecl->setDeclContext(NS);
  1471. // Add intrinsic attribute
  1472. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1473. ParmVarDecl *paramDecls[g_MaxIntrinsicParamCount];
  1474. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1475. IdentifierInfo &parameterId = context.Idents.get(
  1476. StringRef(pIntrinsic->pArgs[i].pName), tok::TokenKind::identifier);
  1477. ParmVarDecl *paramDecl =
  1478. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1479. functionArgQualTypes[i], nullptr,
  1480. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1481. functionDecl->addDecl(paramDecl);
  1482. paramDecls[i - 1] = paramDecl;
  1483. }
  1484. functionDecl->setParams(
  1485. ArrayRef<ParmVarDecl *>(paramDecls, functionArgTypeCount - 1));
  1486. functionDecl->setImplicit(true);
  1487. return functionDecl;
  1488. }
  1489. /// <summary>
  1490. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1491. /// </summary>
  1492. static
  1493. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1494. {
  1495. DXASSERT_NOMSG(expr != nullptr);
  1496. expr = expr->IgnoreParens();
  1497. return
  1498. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1499. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1500. }
  1501. /// <summary>
  1502. /// Silences diagnostics for the initialization sequence, typically because they have already
  1503. /// been emitted.
  1504. /// </summary>
  1505. static
  1506. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1507. {
  1508. DXASSERT_NOMSG(initSequence != nullptr);
  1509. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1510. }
  1511. class UsedIntrinsic
  1512. {
  1513. public:
  1514. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1515. {
  1516. // The canonical representations are unique'd in an ASTContext, and so these
  1517. // should be stable.
  1518. return RHS.getTypePtr() - LHS.getTypePtr();
  1519. }
  1520. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1521. {
  1522. // The intrinsics are defined in a single static table, and so should be stable.
  1523. return RHS - LHS;
  1524. }
  1525. int compare(const UsedIntrinsic& other) const
  1526. {
  1527. // Check whether it's the same instance.
  1528. if (this == &other) return 0;
  1529. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1530. if (result != 0) return result;
  1531. // At this point, it's the exact same intrinsic name.
  1532. // Compare the arguments for ordering then.
  1533. DXASSERT(m_argLength == other.m_argLength, "intrinsics aren't overloaded on argument count, so we should never create a key with different #s");
  1534. for (size_t i = 0; i < m_argLength; i++) {
  1535. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1536. if (argComparison != 0) return argComparison;
  1537. }
  1538. // Exactly the same.
  1539. return 0;
  1540. }
  1541. public:
  1542. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, _In_count_(argCount) QualType* args, size_t argCount)
  1543. : m_argLength(argCount), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1544. {
  1545. std::copy(args, args + argCount, m_args);
  1546. }
  1547. void setFunctionDecl(FunctionDecl* value) const
  1548. {
  1549. DXASSERT(value != nullptr, "no reason to clear this out");
  1550. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1551. m_functionDecl = value;
  1552. }
  1553. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1554. bool operator==(const UsedIntrinsic& other) const
  1555. {
  1556. return compare(other) == 0;
  1557. }
  1558. bool operator<(const UsedIntrinsic& other) const
  1559. {
  1560. return compare(other) < 0;
  1561. }
  1562. private:
  1563. QualType m_args[g_MaxIntrinsicParamCount+1];
  1564. size_t m_argLength;
  1565. const HLSL_INTRINSIC* m_intrinsicSource;
  1566. mutable FunctionDecl* m_functionDecl;
  1567. };
  1568. template <typename T>
  1569. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1570. {
  1571. if (ptr != nullptr)
  1572. {
  1573. *ptr = value;
  1574. }
  1575. }
  1576. static bool CombineBasicTypes(
  1577. ArBasicKind LeftKind,
  1578. ArBasicKind RightKind,
  1579. _Out_ ArBasicKind* pOutKind,
  1580. _Out_opt_ CastKind* leftCastKind = nullptr,
  1581. _Out_opt_ CastKind* rightCastKind = nullptr)
  1582. {
  1583. AssignOpt(CastKind::CK_NoOp, leftCastKind);
  1584. AssignOpt(CastKind::CK_NoOp, rightCastKind);
  1585. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1586. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1587. return false;
  1588. }
  1589. if (LeftKind == RightKind) {
  1590. *pOutKind = LeftKind;
  1591. return true;
  1592. }
  1593. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1594. UINT uRightProps = GetBasicKindProps(RightKind);
  1595. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1596. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1597. UINT uBothFlags = uLeftProps & uRightProps;
  1598. UINT uEitherFlags = uLeftProps | uRightProps;
  1599. if ((BPROP_BOOLEAN & uBothFlags) != 0)
  1600. {
  1601. *pOutKind = AR_BASIC_BOOL;
  1602. return true;
  1603. }
  1604. if ((BPROP_LITERAL & uBothFlags) != 0)
  1605. {
  1606. if ((BPROP_INTEGER & uBothFlags) != 0)
  1607. {
  1608. *pOutKind = AR_BASIC_LITERAL_INT;
  1609. }
  1610. else
  1611. {
  1612. *pOutKind = AR_BASIC_LITERAL_FLOAT;
  1613. }
  1614. return true;
  1615. }
  1616. if ((BPROP_UNSIGNED & uBothFlags) != 0)
  1617. {
  1618. switch (uBits)
  1619. {
  1620. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1621. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1622. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1623. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1624. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1625. default: DXASSERT_NOMSG(false); break;
  1626. }
  1627. AssignOpt(CK_IntegralCast, leftCastKind);
  1628. AssignOpt(CK_IntegralCast, rightCastKind);
  1629. return true;
  1630. }
  1631. if ((BPROP_INTEGER & uBothFlags) != 0)
  1632. {
  1633. if ((BPROP_UNSIGNED & uEitherFlags) != 0)
  1634. {
  1635. switch (uBits)
  1636. {
  1637. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1638. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1639. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1640. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1641. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1642. default: DXASSERT_NOMSG(false); break;
  1643. }
  1644. }
  1645. else
  1646. {
  1647. switch (uBits)
  1648. {
  1649. case BPROP_BITS0: *pOutKind = AR_BASIC_LITERAL_INT; break;
  1650. case BPROP_BITS8: *pOutKind = AR_BASIC_INT8; break;
  1651. case BPROP_BITS12: *pOutKind = AR_BASIC_MIN12INT; break;
  1652. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1653. *pOutKind = AR_BASIC_MIN16INT : *pOutKind = AR_BASIC_INT16; break;
  1654. case BPROP_BITS32: *pOutKind = AR_BASIC_INT32; break;
  1655. case BPROP_BITS64: *pOutKind = AR_BASIC_INT64; break;
  1656. default: DXASSERT_NOMSG(false); break;
  1657. }
  1658. }
  1659. AssignOpt(CK_IntegralCast, leftCastKind);
  1660. AssignOpt(CK_IntegralCast, rightCastKind);
  1661. return true;
  1662. }
  1663. // At least one side is floating-point. Assume both are and fix later
  1664. // in this function.
  1665. DXASSERT_NOMSG((BPROP_FLOATING & uEitherFlags) != 0);
  1666. AssignOpt(CK_FloatingCast, leftCastKind);
  1667. AssignOpt(CK_FloatingCast, rightCastKind);
  1668. if ((BPROP_FLOATING & uBothFlags) == 0)
  1669. {
  1670. // One side is floating-point and one isn't,
  1671. // convert to the floating-point type.
  1672. if ((BPROP_FLOATING & uLeftProps) != 0)
  1673. {
  1674. uBits = GET_BPROP_BITS(uLeftProps);
  1675. AssignOpt(CK_IntegralToFloating, rightCastKind);
  1676. }
  1677. else
  1678. {
  1679. DXASSERT_NOMSG((BPROP_FLOATING & uRightProps) != 0);
  1680. uBits = GET_BPROP_BITS(uRightProps);
  1681. AssignOpt(CK_IntegralToFloating, leftCastKind);
  1682. }
  1683. if (uBits == 0)
  1684. {
  1685. // We have a literal plus a non-literal so drop
  1686. // any literalness.
  1687. uBits = BPROP_BITS32;
  1688. }
  1689. }
  1690. switch (uBits)
  1691. {
  1692. case BPROP_BITS10:
  1693. *pOutKind = AR_BASIC_MIN10FLOAT;
  1694. break;
  1695. case BPROP_BITS16:
  1696. if ((uEitherFlags & BPROP_MIN_PRECISION) != 0)
  1697. {
  1698. *pOutKind = AR_BASIC_MIN16FLOAT;
  1699. }
  1700. else
  1701. {
  1702. *pOutKind = AR_BASIC_FLOAT16;
  1703. }
  1704. break;
  1705. case BPROP_BITS32:
  1706. if ((uEitherFlags & BPROP_LITERAL) != 0 &&
  1707. (uEitherFlags & BPROP_PARTIAL_PRECISION) != 0)
  1708. {
  1709. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1710. }
  1711. else if ((uBothFlags & BPROP_PARTIAL_PRECISION) != 0)
  1712. {
  1713. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1714. }
  1715. else
  1716. {
  1717. *pOutKind = AR_BASIC_FLOAT32;
  1718. }
  1719. break;
  1720. case BPROP_BITS64:
  1721. *pOutKind = AR_BASIC_FLOAT64;
  1722. break;
  1723. default:
  1724. DXASSERT(false, "unexpected bit count");
  1725. *pOutKind = AR_BASIC_FLOAT32;
  1726. break;
  1727. }
  1728. return true;
  1729. }
  1730. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1731. {
  1732. };
  1733. static
  1734. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1735. {
  1736. DXASSERT_NOMSG(intrinsics != nullptr);
  1737. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1738. switch (kind)
  1739. {
  1740. case AR_OBJECT_TRIANGLESTREAM:
  1741. case AR_OBJECT_POINTSTREAM:
  1742. case AR_OBJECT_LINESTREAM:
  1743. *intrinsics = g_StreamMethods;
  1744. *intrinsicCount = _countof(g_StreamMethods);
  1745. break;
  1746. case AR_OBJECT_TEXTURE1D:
  1747. *intrinsics = g_Texture1DMethods;
  1748. *intrinsicCount = _countof(g_Texture1DMethods);
  1749. break;
  1750. case AR_OBJECT_TEXTURE1D_ARRAY:
  1751. *intrinsics = g_Texture1DArrayMethods;
  1752. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1753. break;
  1754. case AR_OBJECT_TEXTURE2D:
  1755. *intrinsics = g_Texture2DMethods;
  1756. *intrinsicCount = _countof(g_Texture2DMethods);
  1757. break;
  1758. case AR_OBJECT_TEXTURE2DMS:
  1759. *intrinsics = g_Texture2DMSMethods;
  1760. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1761. break;
  1762. case AR_OBJECT_TEXTURE2D_ARRAY:
  1763. *intrinsics = g_Texture2DArrayMethods;
  1764. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1765. break;
  1766. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1767. *intrinsics = g_Texture2DArrayMSMethods;
  1768. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1769. break;
  1770. case AR_OBJECT_TEXTURE3D:
  1771. *intrinsics = g_Texture3DMethods;
  1772. *intrinsicCount = _countof(g_Texture3DMethods);
  1773. break;
  1774. case AR_OBJECT_TEXTURECUBE:
  1775. *intrinsics = g_TextureCUBEMethods;
  1776. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1777. break;
  1778. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1779. *intrinsics = g_TextureCUBEArrayMethods;
  1780. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1781. break;
  1782. case AR_OBJECT_BUFFER:
  1783. *intrinsics = g_BufferMethods;
  1784. *intrinsicCount = _countof(g_BufferMethods);
  1785. break;
  1786. case AR_OBJECT_RWTEXTURE1D:
  1787. case AR_OBJECT_ROVTEXTURE1D:
  1788. *intrinsics = g_RWTexture1DMethods;
  1789. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1790. break;
  1791. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1792. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1793. *intrinsics = g_RWTexture1DArrayMethods;
  1794. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1795. break;
  1796. case AR_OBJECT_RWTEXTURE2D:
  1797. case AR_OBJECT_ROVTEXTURE2D:
  1798. *intrinsics = g_RWTexture2DMethods;
  1799. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1800. break;
  1801. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1802. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1803. *intrinsics = g_RWTexture2DArrayMethods;
  1804. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1805. break;
  1806. case AR_OBJECT_RWTEXTURE3D:
  1807. case AR_OBJECT_ROVTEXTURE3D:
  1808. *intrinsics = g_RWTexture3DMethods;
  1809. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1810. break;
  1811. case AR_OBJECT_RWBUFFER:
  1812. case AR_OBJECT_ROVBUFFER:
  1813. *intrinsics = g_RWBufferMethods;
  1814. *intrinsicCount = _countof(g_RWBufferMethods);
  1815. break;
  1816. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1817. *intrinsics = g_ByteAddressBufferMethods;
  1818. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1819. break;
  1820. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1821. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1822. *intrinsics = g_RWByteAddressBufferMethods;
  1823. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1824. break;
  1825. case AR_OBJECT_STRUCTURED_BUFFER:
  1826. *intrinsics = g_StructuredBufferMethods;
  1827. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1828. break;
  1829. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1830. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1831. *intrinsics = g_RWStructuredBufferMethods;
  1832. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1833. break;
  1834. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1835. *intrinsics = g_AppendStructuredBufferMethods;
  1836. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1837. break;
  1838. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1839. *intrinsics = g_ConsumeStructuredBufferMethods;
  1840. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1841. break;
  1842. // SPIRV change starts
  1843. #ifdef ENABLE_SPIRV_CODEGEN
  1844. case AR_OBJECT_VK_SUBPASS_INPUT:
  1845. *intrinsics = g_VkSubpassInputMethods;
  1846. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  1847. break;
  1848. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1849. *intrinsics = g_VkSubpassInputMSMethods;
  1850. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  1851. break;
  1852. #endif // ENABLE_SPIRV_CODEGEN
  1853. // SPIRV change ends
  1854. default:
  1855. *intrinsics = nullptr;
  1856. *intrinsicCount = 0;
  1857. break;
  1858. }
  1859. }
  1860. static
  1861. bool IsRowOrColumnVariable(size_t value)
  1862. {
  1863. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1864. }
  1865. static
  1866. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1867. {
  1868. return
  1869. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1870. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1871. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1872. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1873. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1874. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1875. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1876. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1877. value == LICOMPTYPE_ANY; // any time
  1878. }
  1879. static
  1880. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1881. {
  1882. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1883. }
  1884. static
  1885. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  1886. {
  1887. // Note that LITEMPLATE_OBJECT can accept different types, but it
  1888. // specifies a single 'layout'. In practice, this information is used
  1889. // together with a component type that specifies a single object.
  1890. return value == LITEMPLATE_ANY; // Any layout
  1891. }
  1892. static
  1893. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  1894. {
  1895. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  1896. }
  1897. static
  1898. bool DoesIntrinsicRequireTemplate(const HLSL_INTRINSIC* intrinsic)
  1899. {
  1900. const HLSL_INTRINSIC_ARGUMENT* argument = intrinsic->pArgs;
  1901. for (size_t i = 0; i < intrinsic->uNumArgs; i++)
  1902. {
  1903. // The intrinsic will require a template for any of these reasons:
  1904. // - A type template (layout) or component needs to match something else.
  1905. // - A parameter can take multiple types.
  1906. // - Row or columns numbers may vary.
  1907. if (
  1908. argument->uTemplateId != i ||
  1909. DoesLegalTemplateAcceptMultipleTypes(argument->uLegalTemplates) ||
  1910. DoesComponentTypeAcceptMultipleTypes(argument->uLegalComponentTypes) ||
  1911. IsRowOrColumnVariable(argument->uCols) ||
  1912. IsRowOrColumnVariable(argument->uRows))
  1913. {
  1914. return true;
  1915. }
  1916. argument++;
  1917. }
  1918. return false;
  1919. }
  1920. static
  1921. bool TemplateHasDefaultType(ArBasicKind kind)
  1922. {
  1923. switch (kind) {
  1924. case AR_OBJECT_BUFFER:
  1925. case AR_OBJECT_TEXTURE1D:
  1926. case AR_OBJECT_TEXTURE2D:
  1927. case AR_OBJECT_TEXTURE3D:
  1928. case AR_OBJECT_TEXTURE1D_ARRAY:
  1929. case AR_OBJECT_TEXTURE2D_ARRAY:
  1930. case AR_OBJECT_TEXTURECUBE:
  1931. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1932. // SPIRV change starts
  1933. #ifdef ENABLE_SPIRV_CODEGEN
  1934. case AR_OBJECT_VK_SUBPASS_INPUT:
  1935. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1936. #endif // ENABLE_SPIRV_CODEGEN
  1937. // SPIRV change ends
  1938. return true;
  1939. }
  1940. return false;
  1941. }
  1942. /// <summary>
  1943. /// Use this class to iterate over intrinsic definitions that come from an external source.
  1944. /// </summary>
  1945. class IntrinsicTableDefIter
  1946. {
  1947. private:
  1948. StringRef _typeName;
  1949. StringRef _functionName;
  1950. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  1951. const HLSL_INTRINSIC* _tableIntrinsic;
  1952. UINT64 _tableLookupCookie;
  1953. unsigned _tableIndex;
  1954. unsigned _argCount;
  1955. bool _firstChecked;
  1956. IntrinsicTableDefIter(
  1957. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1958. StringRef typeName,
  1959. StringRef functionName,
  1960. unsigned argCount) :
  1961. _typeName(typeName), _functionName(functionName), _tables(tables),
  1962. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  1963. _argCount(argCount), _firstChecked(false)
  1964. {
  1965. }
  1966. void CheckForIntrinsic() {
  1967. if (_tableIndex >= _tables.size()) {
  1968. return;
  1969. }
  1970. _firstChecked = true;
  1971. // TODO: review this - this will allocate at least once per string
  1972. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  1973. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  1974. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  1975. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  1976. _tableLookupCookie = 0;
  1977. _tableIntrinsic = nullptr;
  1978. }
  1979. }
  1980. void MoveToNext() {
  1981. for (;;) {
  1982. // If we don't have an intrinsic, try the following table.
  1983. if (_firstChecked && _tableIntrinsic == nullptr) {
  1984. _tableIndex++;
  1985. }
  1986. CheckForIntrinsic();
  1987. if (_tableIndex == _tables.size() ||
  1988. (_tableIntrinsic != nullptr &&
  1989. _tableIntrinsic->uNumArgs ==
  1990. (_argCount + 1))) // uNumArgs includes return
  1991. break;
  1992. }
  1993. }
  1994. public:
  1995. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1996. StringRef typeName,
  1997. StringRef functionName,
  1998. unsigned argCount)
  1999. {
  2000. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  2001. return result;
  2002. }
  2003. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  2004. {
  2005. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  2006. result._tableIndex = tables.size();
  2007. return result;
  2008. }
  2009. bool operator!=(const IntrinsicTableDefIter& other)
  2010. {
  2011. if (!_firstChecked) {
  2012. MoveToNext();
  2013. }
  2014. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  2015. }
  2016. const HLSL_INTRINSIC* operator*()
  2017. {
  2018. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  2019. return _tableIntrinsic;
  2020. }
  2021. LPCSTR GetTableName()
  2022. {
  2023. LPCSTR tableName = nullptr;
  2024. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  2025. return nullptr;
  2026. }
  2027. return tableName;
  2028. }
  2029. LPCSTR GetLoweringStrategy()
  2030. {
  2031. LPCSTR lowering = nullptr;
  2032. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  2033. return nullptr;
  2034. }
  2035. return lowering;
  2036. }
  2037. IntrinsicTableDefIter& operator++()
  2038. {
  2039. MoveToNext();
  2040. return *this;
  2041. }
  2042. };
  2043. /// <summary>
  2044. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2045. /// </summary>
  2046. class IntrinsicDefIter
  2047. {
  2048. const HLSL_INTRINSIC* _current;
  2049. const HLSL_INTRINSIC* _end;
  2050. IntrinsicTableDefIter _tableIter;
  2051. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2052. _current(value), _end(end), _tableIter(tableIter)
  2053. { }
  2054. public:
  2055. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2056. {
  2057. return IntrinsicDefIter(start, table + count, tableIter);
  2058. }
  2059. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2060. {
  2061. return IntrinsicDefIter(table + count, table + count, tableIter);
  2062. }
  2063. bool operator!=(const IntrinsicDefIter& other)
  2064. {
  2065. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2066. }
  2067. const HLSL_INTRINSIC* operator*()
  2068. {
  2069. return (_current != _end) ? _current : *_tableIter;
  2070. }
  2071. LPCSTR GetTableName()
  2072. {
  2073. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2074. }
  2075. LPCSTR GetLoweringStrategy()
  2076. {
  2077. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2078. }
  2079. IntrinsicDefIter& operator++()
  2080. {
  2081. if (_current != _end) {
  2082. const HLSL_INTRINSIC* next = _current + 1;
  2083. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2084. _current = next;
  2085. }
  2086. else {
  2087. _current = _end;
  2088. }
  2089. } else {
  2090. ++_tableIter;
  2091. }
  2092. return *this;
  2093. }
  2094. };
  2095. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2096. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2097. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2098. }
  2099. static void CreateSimpleField(clang::ASTContext &context,
  2100. CXXRecordDecl *recordDecl, StringRef Name,
  2101. QualType Ty) {
  2102. IdentifierInfo &fieldId =
  2103. context.Idents.get(Name, tok::TokenKind::identifier);
  2104. TypeSourceInfo *filedTypeSource = context.getTrivialTypeSourceInfo(Ty, NoLoc);
  2105. const bool MutableFalse = false;
  2106. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  2107. FieldDecl *fieldDecl =
  2108. FieldDecl::Create(context, recordDecl, NoLoc, NoLoc, &fieldId, Ty,
  2109. filedTypeSource, nullptr, MutableFalse, initStyle);
  2110. fieldDecl->setAccess(AccessSpecifier::AS_public);
  2111. fieldDecl->setImplicit(true);
  2112. recordDecl->addDecl(fieldDecl);
  2113. }
  2114. // struct RayDesc
  2115. //{
  2116. // float3 Origin;
  2117. // float TMin;
  2118. // float3 Direction;
  2119. // float TMax;
  2120. //};
  2121. static CXXRecordDecl *CreateRayDescStruct(clang::ASTContext &context,
  2122. QualType float3Ty) {
  2123. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  2124. IdentifierInfo &rayDesc =
  2125. context.Idents.get(StringRef("RayDesc"), tok::TokenKind::identifier);
  2126. CXXRecordDecl *rayDescDecl = CXXRecordDecl::Create(
  2127. context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc,
  2128. &rayDesc, nullptr, DelayTypeCreationTrue);
  2129. rayDescDecl->startDefinition();
  2130. QualType floatTy = context.FloatTy;
  2131. // float3 Origin;
  2132. CreateSimpleField(context, rayDescDecl, "Origin", float3Ty);
  2133. // float TMin;
  2134. CreateSimpleField(context, rayDescDecl, "TMin", floatTy);
  2135. // float3 Direction;
  2136. CreateSimpleField(context, rayDescDecl, "Direction", float3Ty);
  2137. // float TMax;
  2138. CreateSimpleField(context, rayDescDecl, "TMax", floatTy);
  2139. rayDescDecl->completeDefinition();
  2140. // Both declarations need to be present for correct handling.
  2141. currentDeclContext->addDecl(rayDescDecl);
  2142. rayDescDecl->setImplicit(true);
  2143. return rayDescDecl;
  2144. }
  2145. // struct BuiltInTriangleIntersectionAttributes
  2146. // {
  2147. // float2 barycentrics;
  2148. // };
  2149. static CXXRecordDecl *AddBuiltInTriangleIntersectionAttributes(ASTContext& context, QualType baryType) {
  2150. DeclContext *curDC = context.getTranslationUnitDecl();
  2151. IdentifierInfo &attributesId =
  2152. context.Idents.get(StringRef("BuiltInTriangleIntersectionAttributes"),
  2153. tok::TokenKind::identifier);
  2154. CXXRecordDecl *attributesDecl = CXXRecordDecl::Create(
  2155. context, TagTypeKind::TTK_Struct, curDC, NoLoc, NoLoc,
  2156. &attributesId, nullptr, DelayTypeCreationTrue);
  2157. attributesDecl->startDefinition();
  2158. // float2 barycentrics;
  2159. CreateSimpleField(context, attributesDecl, "barycentrics", baryType);
  2160. attributesDecl->completeDefinition();
  2161. attributesDecl->setImplicit(true);
  2162. curDC->addDecl(attributesDecl);
  2163. return attributesDecl;
  2164. }
  2165. //
  2166. // This is similar to clang/Analysis/CallGraph, but the following differences
  2167. // motivate this:
  2168. //
  2169. // - track traversed vs. observed nodes explicitly
  2170. // - fully visit all reachable functions
  2171. // - merge graph visiting with checking for recursion
  2172. // - track global variables and types used (NYI)
  2173. //
  2174. namespace hlsl {
  2175. struct CallNode {
  2176. FunctionDecl *CallerFn;
  2177. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2178. };
  2179. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2180. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2181. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2182. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2183. // Returns the definition of a function.
  2184. // This serves two purposes - ignore built-in functions, and pick
  2185. // a single Decl * to be used in maps and sets.
  2186. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2187. if (!F) return nullptr;
  2188. if (F->doesThisDeclarationHaveABody()) return F;
  2189. F = F->getFirstDecl();
  2190. for (auto &&Candidate : F->redecls()) {
  2191. if (Candidate->doesThisDeclarationHaveABody()) {
  2192. return Candidate;
  2193. }
  2194. }
  2195. return nullptr;
  2196. }
  2197. // AST visitor that maintains visited and pending collections, as well
  2198. // as recording nodes of caller/callees.
  2199. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2200. private:
  2201. CallNodes &m_callNodes;
  2202. FunctionSet &m_visitedFunctions;
  2203. PendingFunctions &m_pendingFunctions;
  2204. FunctionDecl *m_source;
  2205. CallNodes::iterator m_sourceIt;
  2206. public:
  2207. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2208. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2209. : m_callNodes(callNodes),
  2210. m_visitedFunctions(visitedFunctions),
  2211. m_pendingFunctions(pendingFunctions) {}
  2212. void setSourceFn(FunctionDecl *F) {
  2213. F = getFunctionWithBody(F);
  2214. m_source = F;
  2215. m_sourceIt = m_callNodes.find(F);
  2216. }
  2217. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2218. ValueDecl *valueDecl = ref->getDecl();
  2219. FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(valueDecl);
  2220. fnDecl = getFunctionWithBody(fnDecl);
  2221. if (fnDecl) {
  2222. if (m_sourceIt == m_callNodes.end()) {
  2223. auto result = m_callNodes.insert(
  2224. std::pair<FunctionDecl *, CallNode>(m_source, CallNode{ m_source }));
  2225. DXASSERT(result.second == true,
  2226. "else setSourceFn didn't assign m_sourceIt");
  2227. m_sourceIt = result.first;
  2228. }
  2229. m_sourceIt->second.CalleeFns.insert(fnDecl);
  2230. if (!m_visitedFunctions.count(fnDecl)) {
  2231. m_pendingFunctions.push_back(fnDecl);
  2232. }
  2233. }
  2234. return true;
  2235. }
  2236. };
  2237. // A call graph that can check for reachability and recursion efficiently.
  2238. class CallGraphWithRecurseGuard {
  2239. private:
  2240. CallNodes m_callNodes;
  2241. FunctionSet m_visitedFunctions;
  2242. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2243. FunctionDecl *D) const {
  2244. if (CallStack.insert(D).second == false)
  2245. return D;
  2246. auto node = m_callNodes.find(D);
  2247. if (node != m_callNodes.end()) {
  2248. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2249. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2250. if (pResult)
  2251. return pResult;
  2252. }
  2253. }
  2254. CallStack.erase(D);
  2255. return nullptr;
  2256. }
  2257. public:
  2258. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2259. DXASSERT_NOMSG(EntryFnDecl);
  2260. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2261. PendingFunctions pendingFunctions;
  2262. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2263. pendingFunctions.push_back(EntryFnDecl);
  2264. while (!pendingFunctions.empty()) {
  2265. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2266. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2267. visitor.setSourceFn(pendingDecl);
  2268. visitor.TraverseDecl(pendingDecl);
  2269. }
  2270. }
  2271. }
  2272. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2273. FnCallStack CallStack;
  2274. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2275. return CheckRecursion(CallStack, EntryFnDecl);
  2276. }
  2277. void dump() const {
  2278. OutputDebugStringW(L"Call Nodes:\r\n");
  2279. for (auto &node : m_callNodes) {
  2280. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), node.first);
  2281. for (auto callee : node.second.CalleeFns) {
  2282. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), callee);
  2283. }
  2284. }
  2285. }
  2286. };
  2287. }
  2288. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2289. static
  2290. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2291. {
  2292. DXASSERT_NOMSG(context != nullptr);
  2293. DXASSERT_NOMSG(ident != nullptr);
  2294. DXASSERT_NOMSG(!baseType.isNull());
  2295. DeclContext* declContext = context->getTranslationUnitDecl();
  2296. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2297. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2298. declContext->addDecl(decl);
  2299. decl->setImplicit(true);
  2300. return decl;
  2301. }
  2302. class HLSLExternalSource : public ExternalSemaSource {
  2303. private:
  2304. // Inner types.
  2305. struct FindStructBasicTypeResult {
  2306. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2307. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2308. FindStructBasicTypeResult(ArBasicKind kind,
  2309. unsigned int basicKindAsTypeIndex)
  2310. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2311. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2312. };
  2313. // Declaration for matrix and vector templates.
  2314. ClassTemplateDecl* m_matrixTemplateDecl;
  2315. ClassTemplateDecl* m_vectorTemplateDecl;
  2316. // Namespace decl for hlsl intrin functions
  2317. NamespaceDecl* m_hlslNSDecl;
  2318. // Context being processed.
  2319. _Notnull_ ASTContext* m_context;
  2320. // Semantic analyzer being processed.
  2321. Sema* m_sema;
  2322. // Intrinsic tables available externally.
  2323. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2324. // Scalar types indexed by HLSLScalarType.
  2325. QualType m_scalarTypes[HLSLScalarTypeCount];
  2326. // Scalar types already built.
  2327. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2328. // 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.
  2329. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2330. // Matrix types already built, in shorthand form.
  2331. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2332. // Vector types already built.
  2333. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2334. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2335. // BuiltinType for each scalar type.
  2336. QualType m_baseTypes[HLSLScalarTypeCount];
  2337. // Built-in object types declarations, indexed by basic kind constant.
  2338. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2339. // Map from object decl to the object index.
  2340. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2341. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2342. // Mask for object which not has methods created.
  2343. uint64_t m_objectTypeLazyInitMask;
  2344. UsedIntrinsicStore m_usedIntrinsics;
  2345. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2346. void AddBaseTypes();
  2347. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2348. void AddHLSLScalarTypes();
  2349. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2350. {
  2351. DXASSERT_NOMSG(recordDecl != nullptr);
  2352. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2353. NamedDecl* parameterDecl = parameterList->getParam(0);
  2354. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2355. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2356. return QualType(parmDecl->getTypeForDecl(), 0);
  2357. }
  2358. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2359. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2360. {
  2361. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2362. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2363. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2364. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2365. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2366. if (
  2367. templateRef >= 0 &&
  2368. templateArg->uTemplateId == templateRef &&
  2369. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2370. componentRef >= 0 &&
  2371. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2372. componentArg->uComponentTypeId == 0 &&
  2373. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2374. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2375. !IsRowOrColumnVariable(matrixArg->uRows))
  2376. {
  2377. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2378. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2379. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2380. }
  2381. return QualType();
  2382. }
  2383. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2384. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2385. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2386. _Inout_ size_t* templateParamNamedDeclsCount)
  2387. {
  2388. DXASSERT_NOMSG(name != nullptr);
  2389. DXASSERT_NOMSG(recordDecl != nullptr);
  2390. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2391. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2392. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2393. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2394. // Create the declaration for the template parameter.
  2395. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2396. TemplateTypeParmDecl* templateTypeParmDecl =
  2397. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2398. id, TypenameTrue, ParameterPackFalse);
  2399. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2400. // Create the type that the parameter represents.
  2401. QualType result = m_context->getTemplateTypeParmType(
  2402. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2403. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2404. // it need not concern itself with maintaining this value.
  2405. (*templateParamNamedDeclsCount)++;
  2406. return result;
  2407. }
  2408. // Adds a function specified by the given intrinsic to a record declaration.
  2409. // The template depth will be zero for records that don't have a "template<>" line
  2410. // even if conceptual; or one if it does have one.
  2411. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2412. {
  2413. DXASSERT_NOMSG(recordDecl != nullptr);
  2414. DXASSERT_NOMSG(intrinsic != nullptr);
  2415. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2416. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2417. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2418. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2419. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2420. //
  2421. // Build template parameters, parameter types, and the return type.
  2422. // Parameter declarations are built after the function is created, to use it as their scope.
  2423. //
  2424. unsigned int numParams = intrinsic->uNumArgs - 1;
  2425. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2426. size_t templateParamNamedDeclsCount = 0;
  2427. QualType argsQTs[g_MaxIntrinsicParamCount];
  2428. StringRef argNames[g_MaxIntrinsicParamCount];
  2429. QualType functionResultQT;
  2430. DXASSERT(
  2431. _countof(templateParamNamedDecls) >= numParams + 1,
  2432. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2433. // Handle the return type.
  2434. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2435. // if (functionResultQT.isNull()) {
  2436. // Workaround for template parameter argument count mismatch.
  2437. // Create template parameter for return type always
  2438. // TODO: reenable the check and skip template argument.
  2439. functionResultQT = AddTemplateParamToArray(
  2440. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2441. &templateParamNamedDeclsCount);
  2442. // }
  2443. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2444. InitParamMods(intrinsic, paramMods);
  2445. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2446. // Handle parameters.
  2447. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2448. {
  2449. //
  2450. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2451. //
  2452. // However this may produce template instantiations with equivalent template arguments
  2453. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2454. // but the current intrinsic table has rules that are hard to process in their current form
  2455. // to find all cases.
  2456. //
  2457. char name[g_MaxIntrinsicParamName + 2];
  2458. name[0] = 'T';
  2459. name[1] = '\0';
  2460. strcat_s(name, intrinsic->pArgs[i].pName);
  2461. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2462. // Change out/inout param to reference type.
  2463. if (paramMods[i-1].isAnyOut())
  2464. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2465. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2466. }
  2467. // Create the declaration.
  2468. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2469. DeclarationName declarationName = DeclarationName(ii);
  2470. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2471. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2472. declarationName, true);
  2473. functionDecl->setImplicit(true);
  2474. // If the function is a template function, create the declaration and cross-reference.
  2475. if (templateParamNamedDeclsCount > 0)
  2476. {
  2477. hlsl::CreateFunctionTemplateDecl(
  2478. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2479. }
  2480. }
  2481. // Checks whether the two specified intrinsics generate equivalent templates.
  2482. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2483. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2484. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2485. {
  2486. if (left == right)
  2487. {
  2488. return true;
  2489. }
  2490. if (left == nullptr || right == nullptr)
  2491. {
  2492. return false;
  2493. }
  2494. return (left->uNumArgs == right->uNumArgs &&
  2495. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2496. }
  2497. // Adds all the intrinsic methods that correspond to the specified type.
  2498. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2499. {
  2500. DXASSERT_NOMSG(recordDecl != nullptr);
  2501. DXASSERT_NOMSG(templateDepth >= 0);
  2502. const HLSL_INTRINSIC* intrinsics;
  2503. const HLSL_INTRINSIC* prior = nullptr;
  2504. size_t intrinsicCount;
  2505. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2506. DXASSERT(
  2507. (intrinsics == nullptr) == (intrinsicCount == 0),
  2508. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2509. while (intrinsicCount--)
  2510. {
  2511. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2512. {
  2513. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2514. prior = intrinsics;
  2515. }
  2516. intrinsics++;
  2517. }
  2518. }
  2519. void AddDoubleSubscriptSupport(
  2520. _In_ ClassTemplateDecl* typeDecl,
  2521. _In_ CXXRecordDecl* recordDecl,
  2522. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2523. _In_z_ const char* type0Name,
  2524. _In_z_ const char* type1Name,
  2525. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2526. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2527. {
  2528. DXASSERT_NOMSG(typeDecl != nullptr);
  2529. DXASSERT_NOMSG(recordDecl != nullptr);
  2530. DXASSERT_NOMSG(memberName != nullptr);
  2531. DXASSERT_NOMSG(!elementType.isNull());
  2532. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2533. DXASSERT_NOMSG(type0Name != nullptr);
  2534. DXASSERT_NOMSG(type1Name != nullptr);
  2535. DXASSERT_NOMSG(indexer0Name != nullptr);
  2536. DXASSERT_NOMSG(!indexer0Type.isNull());
  2537. DXASSERT_NOMSG(indexer1Name != nullptr);
  2538. DXASSERT_NOMSG(!indexer1Type.isNull());
  2539. //
  2540. // Add inner types to the templates to represent the following C++ code inside the class.
  2541. // public:
  2542. // class sample_slice_type
  2543. // {
  2544. // public: TElement operator[](uint3 index);
  2545. // };
  2546. // class sample_type
  2547. // {
  2548. // public: sample_slice_type operator[](uint slice);
  2549. // };
  2550. // sample_type sample;
  2551. //
  2552. // Variable names reflect this structure, but this code will also produce the types
  2553. // for .mips access.
  2554. //
  2555. const bool MutableTrue = true;
  2556. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2557. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2558. &m_context->Idents.get(StringRef(type1Name)));
  2559. sampleSliceTypeDecl->setAccess(AS_public);
  2560. sampleSliceTypeDecl->setImplicit();
  2561. recordDecl->addDecl(sampleSliceTypeDecl);
  2562. sampleSliceTypeDecl->startDefinition();
  2563. const bool MutableFalse = false;
  2564. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2565. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2566. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2567. sliceHandleDecl->setAccess(AS_private);
  2568. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2569. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2570. sampleSliceTypeDecl, elementType,
  2571. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2572. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2573. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2574. sampleSliceTypeDecl->completeDefinition();
  2575. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2576. &m_context->Idents.get(StringRef(type0Name)));
  2577. sampleTypeDecl->setAccess(AS_public);
  2578. recordDecl->addDecl(sampleTypeDecl);
  2579. sampleTypeDecl->startDefinition();
  2580. sampleTypeDecl->setImplicit();
  2581. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2582. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2583. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2584. sampleHandleDecl->setAccess(AS_private);
  2585. sampleTypeDecl->addDecl(sampleHandleDecl);
  2586. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2587. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2588. sampleTypeDecl, m_context->getRValueReferenceType(sampleSliceType), // TODO: choose LValueRef if writable.
  2589. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2590. sampleTypeDecl->completeDefinition();
  2591. // Add subscript attribute
  2592. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2593. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2594. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2595. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2596. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2597. sampleFieldDecl->setAccess(AS_public);
  2598. recordDecl->addDecl(sampleFieldDecl);
  2599. }
  2600. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2601. _In_ CXXRecordDecl *recordDecl,
  2602. SubscriptOperatorRecord op) {
  2603. DXASSERT_NOMSG(typeDecl != nullptr);
  2604. DXASSERT_NOMSG(recordDecl != nullptr);
  2605. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2606. op.SubscriptCardinality <= 3);
  2607. DXASSERT(op.SubscriptCardinality > 0 ||
  2608. (op.HasMips == false && op.HasSample == false),
  2609. "objects that have .mips or .sample member also have a plain "
  2610. "subscript defined (otherwise static table is "
  2611. "likely incorrect, and this function won't know the cardinality "
  2612. "of the position parameter");
  2613. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2614. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2615. "read/write objects don't have .mips or .sample members");
  2616. // Return early if there is no work to be done.
  2617. if (op.SubscriptCardinality == 0) {
  2618. return;
  2619. }
  2620. const unsigned int templateDepth = 1;
  2621. // Add an operator[].
  2622. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2623. typeDecl->getTemplateParameters()->getParam(0));
  2624. QualType resultType = m_context->getTemplateTypeParmType(
  2625. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2626. if (isReadWrite)
  2627. resultType = m_context->getLValueReferenceType(resultType, false);
  2628. else
  2629. resultType = m_context->getRValueReferenceType(resultType);
  2630. QualType indexType =
  2631. op.SubscriptCardinality == 1
  2632. ? m_context->UnsignedIntTy
  2633. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2634. op.SubscriptCardinality);
  2635. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2636. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2637. ArrayRef<StringRef>(StringRef("index")),
  2638. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2639. hlsl::CreateFunctionTemplateDecl(
  2640. *m_context, recordDecl, functionDecl,
  2641. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2642. // Add a .mips member if necessary.
  2643. QualType uintType = m_context->UnsignedIntTy;
  2644. if (op.HasMips) {
  2645. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2646. templateTypeParmDecl, "mips_type",
  2647. "mips_slice_type", "mipSlice", uintType, "pos",
  2648. indexType);
  2649. }
  2650. // Add a .sample member if necessary.
  2651. if (op.HasSample) {
  2652. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2653. templateTypeParmDecl, "sample_type",
  2654. "sample_slice_type", "sampleSlice", uintType,
  2655. "pos", indexType);
  2656. // TODO: support operator[][](indexType, uint).
  2657. }
  2658. }
  2659. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2660. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2661. return a.first < b.first;
  2662. };
  2663. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2664. auto begin = m_objectTypeDeclsMap.begin();
  2665. auto end = m_objectTypeDeclsMap.end();
  2666. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2667. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2668. if (low == end)
  2669. return -1;
  2670. if (recordDecl == low->first)
  2671. return low->second;
  2672. else
  2673. return -1;
  2674. }
  2675. // Adds all built-in HLSL object types.
  2676. void AddObjectTypes()
  2677. {
  2678. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2679. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2680. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2681. m_objectTypeLazyInitMask = 0;
  2682. unsigned effectKindIndex = 0;
  2683. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2684. {
  2685. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2686. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2687. continue;
  2688. }
  2689. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2690. effectKindIndex = i;
  2691. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2692. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2693. const char* typeName = g_ArBasicTypeNames[kind];
  2694. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2695. CXXRecordDecl* recordDecl = nullptr;
  2696. if (kind == AR_OBJECT_RAY_DESC) {
  2697. QualType float3Ty = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 3);
  2698. recordDecl = CreateRayDescStruct(*m_context, float3Ty);
  2699. } else if (kind == AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES) {
  2700. QualType float2Type = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 2);
  2701. recordDecl = AddBuiltInTriangleIntersectionAttributes(*m_context, float2Type);
  2702. } else
  2703. if (templateArgCount == 0)
  2704. {
  2705. AddRecordTypeWithHandle(*m_context, &recordDecl, typeName);
  2706. DXASSERT(recordDecl != nullptr, "AddRecordTypeWithHandle failed to return the object declaration");
  2707. recordDecl->setImplicit(true);
  2708. }
  2709. else
  2710. {
  2711. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2712. ClassTemplateDecl* typeDecl = nullptr;
  2713. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2714. AddTemplateTypeWithHandle(*m_context, &typeDecl, &recordDecl, typeName, templateArgCount, typeDefault);
  2715. DXASSERT(typeDecl != nullptr, "AddTemplateTypeWithHandle failed to return the object declaration");
  2716. typeDecl->setImplicit(true);
  2717. recordDecl->setImplicit(true);
  2718. }
  2719. m_objectTypeDecls[i] = recordDecl;
  2720. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2721. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2722. }
  2723. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2724. {
  2725. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2726. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2727. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2728. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2729. currentDeclContext->addDecl(samplerDecl);
  2730. samplerDecl->setImplicit(true);
  2731. // Create decls for each deprecated effect object type:
  2732. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2733. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2734. for (int i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2735. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2736. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2737. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2738. currentDeclContext->addDecl(effectObjDecl);
  2739. effectObjDecl->setImplicit(true);
  2740. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2741. }
  2742. }
  2743. // Make sure it's in order.
  2744. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2745. }
  2746. FunctionDecl* AddSubscriptSpecialization(
  2747. _In_ FunctionTemplateDecl* functionTemplate,
  2748. QualType objectElement,
  2749. const FindStructBasicTypeResult& findResult);
  2750. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  2751. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2752. }
  2753. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  2754. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2755. }
  2756. HRESULT CombineDimensions(QualType leftType, QualType rightType, ArTypeObjectKind leftKind, ArTypeObjectKind rightKind, QualType *resultType);
  2757. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  2758. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2759. rowCount >= 0 && rowCount <= 4 && colCount >= 0 &&
  2760. colCount <= 4);
  2761. TypedefDecl *qts =
  2762. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  2763. if (qts == nullptr) {
  2764. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  2765. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  2766. rowCount, colCount);
  2767. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  2768. }
  2769. return qts;
  2770. }
  2771. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  2772. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2773. colCount >= 0 && colCount <= 4);
  2774. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  2775. if (qts == nullptr) {
  2776. QualType type = LookupVectorType(scalarType, colCount);
  2777. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  2778. colCount);
  2779. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  2780. }
  2781. return qts;
  2782. }
  2783. public:
  2784. HLSLExternalSource() :
  2785. m_matrixTemplateDecl(nullptr),
  2786. m_vectorTemplateDecl(nullptr),
  2787. m_context(nullptr),
  2788. m_sema(nullptr)
  2789. {
  2790. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  2791. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  2792. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  2793. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  2794. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  2795. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  2796. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  2797. }
  2798. ~HLSLExternalSource() { }
  2799. static HLSLExternalSource* FromSema(_In_ Sema* self)
  2800. {
  2801. DXASSERT_NOMSG(self != nullptr);
  2802. ExternalSemaSource* externalSource = self->getExternalSource();
  2803. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  2804. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  2805. return hlsl;
  2806. }
  2807. void InitializeSema(Sema& S) override
  2808. {
  2809. m_sema = &S;
  2810. S.addExternalSource(this);
  2811. AddObjectTypes();
  2812. AddStdIsEqualImplementation(S.getASTContext(), S);
  2813. for (auto && intrinsic : m_intrinsicTables) {
  2814. AddIntrinsicTableMethods(intrinsic);
  2815. }
  2816. }
  2817. void ForgetSema() override
  2818. {
  2819. m_sema = nullptr;
  2820. }
  2821. Sema* getSema() {
  2822. return m_sema;
  2823. }
  2824. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  2825. // We shouldn't create Typedef for built in scalar types.
  2826. // For built in scalar types, this funciton may be called for
  2827. // TypoCorrection. In that case, we return a nullptr.
  2828. if (m_scalarTypes[scalarType].isNull()) {
  2829. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  2830. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  2831. }
  2832. return m_scalarTypeDefs[scalarType];
  2833. }
  2834. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  2835. {
  2836. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  2837. if (qt.isNull()) {
  2838. // lazy initialization of scalar types
  2839. if (m_scalarTypes[scalarType].isNull()) {
  2840. LookupScalarTypeDef(scalarType);
  2841. }
  2842. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  2843. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  2844. }
  2845. return qt;
  2846. }
  2847. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  2848. {
  2849. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  2850. if (qt.isNull()) {
  2851. if (m_scalarTypes[scalarType].isNull()) {
  2852. LookupScalarTypeDef(scalarType);
  2853. }
  2854. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  2855. m_vectorTypes[scalarType][colCount - 1] = qt;
  2856. }
  2857. return qt;
  2858. }
  2859. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  2860. // TODO: enalbe this once we introduce precise master option
  2861. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  2862. if (type == HLSLScalarType_int_min12) {
  2863. const char *PromotedType =
  2864. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  2865. : HLSLScalarTypeNames[HLSLScalarType_int16];
  2866. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2867. << HLSLScalarTypeNames[type] << PromotedType;
  2868. } else if (type == HLSLScalarType_float_min10) {
  2869. const char *PromotedType =
  2870. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  2871. : HLSLScalarTypeNames[HLSLScalarType_float16];
  2872. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2873. << HLSLScalarTypeNames[type] << PromotedType;
  2874. }
  2875. if (!UseMinPrecision) {
  2876. if (type == HLSLScalarType_float_min16) {
  2877. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2878. << HLSLScalarTypeNames[type]
  2879. << HLSLScalarTypeNames[HLSLScalarType_float16];
  2880. } else if (type == HLSLScalarType_int_min16) {
  2881. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2882. << HLSLScalarTypeNames[type]
  2883. << HLSLScalarTypeNames[HLSLScalarType_int16];
  2884. } else if (type == HLSLScalarType_uint_min16) {
  2885. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2886. << HLSLScalarTypeNames[type]
  2887. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  2888. }
  2889. }
  2890. }
  2891. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  2892. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  2893. switch (type) {
  2894. case HLSLScalarType_float16:
  2895. case HLSLScalarType_float32:
  2896. case HLSLScalarType_float64:
  2897. case HLSLScalarType_int16:
  2898. case HLSLScalarType_int32:
  2899. case HLSLScalarType_uint16:
  2900. case HLSLScalarType_uint32:
  2901. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  2902. << HLSLScalarTypeNames[type] << "2018";
  2903. return false;
  2904. default:
  2905. break;
  2906. }
  2907. }
  2908. if (getSema()->getLangOpts().UseMinPrecision) {
  2909. switch (type) {
  2910. case HLSLScalarType_float16:
  2911. case HLSLScalarType_int16:
  2912. case HLSLScalarType_uint16:
  2913. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  2914. << HLSLScalarTypeNames[type];
  2915. return false;
  2916. default:
  2917. break;
  2918. }
  2919. }
  2920. return true;
  2921. }
  2922. bool LookupUnqualified(LookupResult &R, Scope *S) override
  2923. {
  2924. const DeclarationNameInfo declName = R.getLookupNameInfo();
  2925. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  2926. if (idInfo == nullptr) {
  2927. return false;
  2928. }
  2929. // Currently template instantiation is blocked when a fatal error is
  2930. // detected. So no faulting-in types at this point, instead we simply
  2931. // back out.
  2932. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  2933. return false;
  2934. }
  2935. StringRef nameIdentifier = idInfo->getName();
  2936. HLSLScalarType parsedType;
  2937. int rowCount;
  2938. int colCount;
  2939. // Try parsing hlsl scalar types that is not initialized at AST time.
  2940. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  2941. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  2942. if (rowCount == 0 && colCount == 0) { // scalar
  2943. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  2944. if (!typeDecl) return false;
  2945. R.addDecl(typeDecl);
  2946. }
  2947. else if (rowCount == 0) { // vector
  2948. QualType qt = LookupVectorType(parsedType, colCount);
  2949. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  2950. R.addDecl(qts);
  2951. }
  2952. else { // matrix
  2953. QualType qt = LookupMatrixType(parsedType, rowCount, colCount);
  2954. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  2955. R.addDecl(qts);
  2956. }
  2957. return true;
  2958. }
  2959. return false;
  2960. }
  2961. /// <summary>
  2962. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  2963. /// </sumary>
  2964. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  2965. {
  2966. DXASSERT_NOMSG(type != nullptr);
  2967. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2968. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2969. if (templateSpecializationDecl) {
  2970. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  2971. if (decl == m_matrixTemplateDecl)
  2972. return AR_TOBJ_MATRIX;
  2973. else if (decl == m_vectorTemplateDecl)
  2974. return AR_TOBJ_VECTOR;
  2975. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  2976. return AR_TOBJ_OBJECT;
  2977. }
  2978. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2979. if (typeRecordDecl->getDeclContext()->isFileContext()) {
  2980. int index = FindObjectBasicKindIndex(typeRecordDecl);
  2981. if (index != -1) {
  2982. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  2983. if ( AR_OBJECT_RAY_DESC == kind || AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES == kind)
  2984. return AR_TOBJ_COMPOUND;
  2985. }
  2986. return AR_TOBJ_OBJECT;
  2987. }
  2988. else
  2989. return AR_TOBJ_INNER_OBJ;
  2990. }
  2991. return AR_TOBJ_COMPOUND;
  2992. }
  2993. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  2994. bool IsBuiltInObjectType(QualType type)
  2995. {
  2996. type = GetStructuralForm(type);
  2997. if (!type.isNull() && type->isStructureOrClassType()) {
  2998. const RecordType* recordType = type->getAs<RecordType>();
  2999. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  3000. }
  3001. return false;
  3002. }
  3003. /// <summary>
  3004. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  3005. /// possibly refering to original template record if it's a specialization; this makes the result
  3006. /// suitable for looking up in initialization tables.
  3007. /// </summary>
  3008. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  3009. {
  3010. const CXXRecordDecl* recordDecl;
  3011. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  3012. {
  3013. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  3014. }
  3015. else
  3016. {
  3017. recordDecl = dyn_cast<CXXRecordDecl>(context);
  3018. }
  3019. return recordDecl;
  3020. }
  3021. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  3022. ArTypeObjectKind GetTypeObjectKind(QualType type)
  3023. {
  3024. DXASSERT_NOMSG(!type.isNull());
  3025. type = GetStructuralForm(type);
  3026. if (type->isVoidType()) return AR_TOBJ_VOID;
  3027. if (type->isArrayType()) return AR_TOBJ_ARRAY;
  3028. if (type->isPointerType()) {
  3029. return AR_TOBJ_POINTER;
  3030. }
  3031. if (type->isStructureOrClassType()) {
  3032. const RecordType* recordType = type->getAs<RecordType>();
  3033. return ClassifyRecordType(recordType);
  3034. } else if (const InjectedClassNameType *ClassNameTy =
  3035. type->getAs<InjectedClassNameType>()) {
  3036. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  3037. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  3038. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3039. if (templateSpecializationDecl) {
  3040. ClassTemplateDecl *decl =
  3041. templateSpecializationDecl->getSpecializedTemplate();
  3042. if (decl == m_matrixTemplateDecl)
  3043. return AR_TOBJ_MATRIX;
  3044. else if (decl == m_vectorTemplateDecl)
  3045. return AR_TOBJ_VECTOR;
  3046. DXASSERT(decl->isImplicit(),
  3047. "otherwise object template decl is not set to implicit");
  3048. return AR_TOBJ_OBJECT;
  3049. }
  3050. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3051. if (typeRecordDecl->getDeclContext()->isFileContext())
  3052. return AR_TOBJ_OBJECT;
  3053. else
  3054. return AR_TOBJ_INNER_OBJ;
  3055. }
  3056. return AR_TOBJ_COMPOUND;
  3057. }
  3058. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  3059. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  3060. return AR_TOBJ_INVALID;
  3061. }
  3062. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  3063. QualType GetMatrixOrVectorElementType(QualType type)
  3064. {
  3065. type = GetStructuralForm(type);
  3066. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3067. DXASSERT_NOMSG(typeRecordDecl);
  3068. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3069. DXASSERT_NOMSG(templateSpecializationDecl);
  3070. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  3071. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  3072. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  3073. }
  3074. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  3075. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  3076. QualType GetStructuralForm(QualType type)
  3077. {
  3078. if (type.isNull()) {
  3079. return type;
  3080. }
  3081. const ReferenceType *RefType = nullptr;
  3082. const AttributedType *AttrType = nullptr;
  3083. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  3084. (AttrType = dyn_cast<AttributedType>(type)))
  3085. {
  3086. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  3087. }
  3088. return type->getCanonicalTypeUnqualified();
  3089. }
  3090. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  3091. ArBasicKind GetTypeElementKind(QualType type)
  3092. {
  3093. type = GetStructuralForm(type);
  3094. ArTypeObjectKind kind = GetTypeObjectKind(type);
  3095. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  3096. QualType elementType = GetMatrixOrVectorElementType(type);
  3097. return GetTypeElementKind(elementType);
  3098. }
  3099. if (type->isArrayType()) {
  3100. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  3101. return GetTypeElementKind(arrayType->getElementType());
  3102. }
  3103. if (kind == AR_TOBJ_INNER_OBJ) {
  3104. return AR_OBJECT_INNER;
  3105. } else if (kind == AR_TOBJ_OBJECT) {
  3106. // Classify the object as the element type.
  3107. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  3108. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3109. // NOTE: this will likely need to be updated for specialized records
  3110. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  3111. return g_ArBasicKindsAsTypes[index];
  3112. }
  3113. CanQualType canType = type->getCanonicalTypeUnqualified();
  3114. return BasicTypeForScalarType(canType);
  3115. }
  3116. ArBasicKind BasicTypeForScalarType(CanQualType type)
  3117. {
  3118. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3119. {
  3120. switch (BT->getKind())
  3121. {
  3122. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3123. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3124. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3125. case BuiltinType::Half: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  3126. case BuiltinType::Int: return AR_BASIC_INT32;
  3127. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3128. case BuiltinType::Short: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  3129. case BuiltinType::UShort: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  3130. case BuiltinType::Long: return AR_BASIC_INT32;
  3131. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3132. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3133. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3134. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3135. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3136. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3137. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3138. }
  3139. }
  3140. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3141. if (ET->getDecl()->isScopedUsingClassTag())
  3142. return AR_BASIC_ENUM_CLASS;
  3143. return AR_BASIC_ENUM;
  3144. }
  3145. return AR_BASIC_UNKNOWN;
  3146. }
  3147. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3148. DXASSERT_NOMSG(table != nullptr);
  3149. // Function intrinsics are added on-demand, objects get template methods.
  3150. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3151. // Grab information already processed by AddObjectTypes.
  3152. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3153. const char *typeName = g_ArBasicTypeNames[kind];
  3154. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3155. DXASSERT(0 <= templateArgCount && templateArgCount <= 2,
  3156. "otherwise a new case has been added");
  3157. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3158. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3159. if (recordDecl == nullptr) {
  3160. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3161. continue;
  3162. }
  3163. // This is a variation of AddObjectMethods using the new table.
  3164. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3165. const HLSL_INTRINSIC *pPrior = nullptr;
  3166. UINT64 lookupCookie = 0;
  3167. CA2W wideTypeName(typeName);
  3168. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3169. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3170. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3171. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3172. // NOTE: this only works with the current implementation because
  3173. // intrinsics are alive as long as the table is alive.
  3174. pPrior = pIntrinsic;
  3175. }
  3176. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3177. }
  3178. }
  3179. }
  3180. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3181. DXASSERT_NOMSG(table != nullptr);
  3182. m_intrinsicTables.push_back(table);
  3183. // If already initialized, add methods immediately.
  3184. if (m_sema != nullptr) {
  3185. AddIntrinsicTableMethods(table);
  3186. }
  3187. }
  3188. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3189. {
  3190. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3191. switch (kind) {
  3192. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3193. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3194. case AR_BASIC_FLOAT16: return HLSLScalarType_float_min16;
  3195. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3196. return HLSLScalarType_float;
  3197. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3198. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3199. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3200. case AR_BASIC_INT8: return HLSLScalarType_int;
  3201. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3202. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3203. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3204. case AR_BASIC_INT32: return HLSLScalarType_int;
  3205. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3206. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3207. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3208. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3209. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3210. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3211. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3212. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3213. default:
  3214. return HLSLScalarType_unknown;
  3215. }
  3216. }
  3217. QualType GetBasicKindType(ArBasicKind kind)
  3218. {
  3219. DXASSERT_VALIDBASICKIND(kind);
  3220. switch (kind) {
  3221. case AR_OBJECT_NULL: return m_context->VoidTy;
  3222. case AR_BASIC_BOOL: return m_context->BoolTy;
  3223. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3224. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3225. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->FloatTy;
  3226. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3227. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3228. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3229. case AR_BASIC_INT8: return m_context->IntTy;
  3230. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3231. case AR_BASIC_INT16: return m_context->ShortTy;
  3232. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3233. case AR_BASIC_INT32: return m_context->IntTy;
  3234. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3235. case AR_BASIC_INT64: return m_context->LongLongTy;
  3236. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3237. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3238. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3239. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3240. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3241. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3242. case AR_OBJECT_STRING: return QualType();
  3243. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3244. case AR_OBJECT_TEXTURE1D:
  3245. case AR_OBJECT_TEXTURE1D_ARRAY:
  3246. case AR_OBJECT_TEXTURE2D:
  3247. case AR_OBJECT_TEXTURE2D_ARRAY:
  3248. case AR_OBJECT_TEXTURE3D:
  3249. case AR_OBJECT_TEXTURECUBE:
  3250. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3251. case AR_OBJECT_TEXTURE2DMS:
  3252. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3253. case AR_OBJECT_SAMPLER:
  3254. case AR_OBJECT_SAMPLERCOMPARISON:
  3255. case AR_OBJECT_BUFFER:
  3256. case AR_OBJECT_POINTSTREAM:
  3257. case AR_OBJECT_LINESTREAM:
  3258. case AR_OBJECT_TRIANGLESTREAM:
  3259. case AR_OBJECT_INPUTPATCH:
  3260. case AR_OBJECT_OUTPUTPATCH:
  3261. case AR_OBJECT_RWTEXTURE1D:
  3262. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3263. case AR_OBJECT_RWTEXTURE2D:
  3264. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3265. case AR_OBJECT_RWTEXTURE3D:
  3266. case AR_OBJECT_RWBUFFER:
  3267. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3268. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3269. case AR_OBJECT_STRUCTURED_BUFFER:
  3270. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3271. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3272. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3273. case AR_OBJECT_WAVE:
  3274. case AR_OBJECT_ACCELARATION_STRUCT:
  3275. case AR_OBJECT_RAY_DESC:
  3276. case AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES:
  3277. {
  3278. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3279. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3280. size_t index = match - g_ArBasicKindsAsTypes;
  3281. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3282. }
  3283. case AR_OBJECT_SAMPLER1D:
  3284. case AR_OBJECT_SAMPLER2D:
  3285. case AR_OBJECT_SAMPLER3D:
  3286. case AR_OBJECT_SAMPLERCUBE:
  3287. // Turn dimension-typed samplers into sampler states.
  3288. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3289. case AR_OBJECT_STATEBLOCK:
  3290. case AR_OBJECT_RASTERIZER:
  3291. case AR_OBJECT_DEPTHSTENCIL:
  3292. case AR_OBJECT_BLEND:
  3293. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3294. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3295. default:
  3296. return QualType();
  3297. }
  3298. }
  3299. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3300. /// <param name="E">Expression to typecast.</param>
  3301. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3302. ExprResult PromoteToIntIfBool(ExprResult& E);
  3303. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3304. {
  3305. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3306. (qwUsages);
  3307. return type;
  3308. }
  3309. QualType NewSimpleAggregateType(
  3310. _In_ ArTypeObjectKind ExplicitKind,
  3311. _In_ ArBasicKind componentType,
  3312. _In_ UINT64 qwQual,
  3313. _In_ UINT uRows,
  3314. _In_ UINT uCols)
  3315. {
  3316. DXASSERT_VALIDBASICKIND(componentType);
  3317. QualType pType; // The type to return.
  3318. QualType pEltType = GetBasicKindType(componentType);
  3319. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3320. // TODO: handle adding qualifications like const
  3321. pType = NewQualifiedType(
  3322. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3323. pEltType);
  3324. if (uRows > 1 ||
  3325. uCols > 1 ||
  3326. ExplicitKind == AR_TOBJ_VECTOR ||
  3327. ExplicitKind == AR_TOBJ_MATRIX)
  3328. {
  3329. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3330. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3331. if ((uRows == 1 &&
  3332. ExplicitKind != AR_TOBJ_MATRIX) ||
  3333. ExplicitKind == AR_TOBJ_VECTOR)
  3334. {
  3335. pType = LookupVectorType(scalarType, uCols);
  3336. }
  3337. else
  3338. {
  3339. pType = LookupMatrixType(scalarType, uRows, uCols);
  3340. }
  3341. // TODO: handle colmajor/rowmajor
  3342. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3343. //{
  3344. // VN(pType = NewQualifiedType(pSrcLoc,
  3345. // qwQual & (AR_QUAL_COLMAJOR |
  3346. // AR_QUAL_ROWMAJOR),
  3347. // pMatrix));
  3348. //}
  3349. //else
  3350. //{
  3351. // pType = pMatrix;
  3352. //}
  3353. }
  3354. return pType;
  3355. }
  3356. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3357. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3358. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3359. /// <param name="Args">Invocation arguments to match.</param>
  3360. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3361. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  3362. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3363. bool MatchArguments(
  3364. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3365. _In_ QualType objectElement,
  3366. _In_ ArrayRef<Expr *> Args,
  3367. _Out_writes_(g_MaxIntrinsicParamCount + 1) QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  3368. _Out_range_(0, g_MaxIntrinsicParamCount + 1) size_t* argCount);
  3369. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3370. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3371. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3372. bool IsValidateObjectElement(
  3373. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3374. _In_ QualType objectElement);
  3375. // Returns the iterator with the first entry that matches the requirement
  3376. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3377. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3378. size_t tableSize,
  3379. StringRef typeName,
  3380. StringRef nameIdentifier,
  3381. size_t argumentCount)
  3382. {
  3383. // This is implemented by a linear scan for now.
  3384. // We tested binary search on tables, and there was no performance gain on
  3385. // samples probably for the following reasons.
  3386. // 1. The tables are not big enough to make noticable difference
  3387. // 2. The user of this function assumes that it returns the first entry in
  3388. // the table that matches name and argument count. So even in the binary
  3389. // search, we have to scan backwards until the entry does not match the name
  3390. // or arg count. For linear search this is not a problem
  3391. for (unsigned int i = 0; i < tableSize; i++) {
  3392. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3393. // Do some quick checks to verify size and name.
  3394. if (pIntrinsic->uNumArgs != 1 + argumentCount) {
  3395. continue;
  3396. }
  3397. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3398. continue;
  3399. }
  3400. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3401. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3402. }
  3403. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3404. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3405. }
  3406. bool AddOverloadedCallCandidates(
  3407. UnresolvedLookupExpr *ULE,
  3408. ArrayRef<Expr *> Args,
  3409. OverloadCandidateSet &CandidateSet,
  3410. bool PartialOverloading) override
  3411. {
  3412. DXASSERT_NOMSG(ULE != nullptr);
  3413. const DeclarationNameInfo declName = ULE->getNameInfo();
  3414. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3415. if (idInfo == nullptr)
  3416. {
  3417. return false;
  3418. }
  3419. StringRef nameIdentifier = idInfo->getName();
  3420. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3421. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  3422. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3423. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3424. while (cursor != end)
  3425. {
  3426. // If this is the intrinsic we're interested in, build up a representation
  3427. // of the types we need.
  3428. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3429. LPCSTR tableName = cursor.GetTableName();
  3430. LPCSTR lowering = cursor.GetLoweringStrategy();
  3431. DXASSERT(
  3432. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3433. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3434. QualType functionArgTypes[g_MaxIntrinsicParamCount + 1];
  3435. size_t functionArgTypeCount = 0;
  3436. if (!MatchArguments(pIntrinsic, QualType(), Args, functionArgTypes, &functionArgTypeCount))
  3437. {
  3438. ++cursor;
  3439. continue;
  3440. }
  3441. // Get or create the overload we're interested in.
  3442. FunctionDecl* intrinsicFuncDecl = nullptr;
  3443. std::pair<UsedIntrinsicStore::iterator, bool> insertResult = m_usedIntrinsics.insert(UsedIntrinsic(
  3444. pIntrinsic, functionArgTypes, functionArgTypeCount));
  3445. bool insertedNewValue = insertResult.second;
  3446. if (insertedNewValue)
  3447. {
  3448. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3449. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, functionArgTypes, functionArgTypeCount);
  3450. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3451. }
  3452. else
  3453. {
  3454. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3455. }
  3456. OverloadCandidate& candidate = CandidateSet.addCandidate();
  3457. candidate.Function = intrinsicFuncDecl;
  3458. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3459. candidate.Viable = true;
  3460. return true;
  3461. }
  3462. return false;
  3463. }
  3464. bool Initialize(ASTContext& context)
  3465. {
  3466. m_context = &context;
  3467. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3468. /*Inline*/ false, SourceLocation(),
  3469. SourceLocation(), &context.Idents.get("hlsl"),
  3470. /*PrevDecl*/ nullptr);
  3471. m_hlslNSDecl->setImplicit();
  3472. AddBaseTypes();
  3473. AddHLSLScalarTypes();
  3474. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3475. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  3476. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  3477. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  3478. // Initializing built in integers for ray tracing
  3479. AddRayFlags(*m_context);
  3480. AddHitKinds(*m_context);
  3481. return true;
  3482. }
  3483. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  3484. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  3485. /// <summary>Checks whether the specified type is a scalar type.</summary>
  3486. bool IsScalarType(const QualType& type) {
  3487. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  3488. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3489. }
  3490. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3491. bool IsValidVectorSize(size_t length) {
  3492. return 1 <= length && length <= 4;
  3493. }
  3494. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3495. bool IsValidMatrixColOrRowSize(size_t length) {
  3496. return 1 <= length && length <= 4;
  3497. }
  3498. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3499. if (type.isNull()) {
  3500. return false;
  3501. }
  3502. if (type.hasQualifiers()) {
  3503. return false;
  3504. }
  3505. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3506. if (type->getTypeClass() == Type::TemplateTypeParm)
  3507. return true;
  3508. QualType qt = GetStructuralForm(type);
  3509. if (requireScalar) {
  3510. if (!IsScalarType(qt)) {
  3511. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3512. return false;
  3513. }
  3514. return true;
  3515. }
  3516. else {
  3517. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3518. if (qt->isArrayType()) {
  3519. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3520. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3521. }
  3522. else if (objectKind == AR_TOBJ_VECTOR) {
  3523. bool valid = true;
  3524. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3525. valid = false;
  3526. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3527. }
  3528. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3529. valid = false;
  3530. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3531. }
  3532. return valid;
  3533. }
  3534. else if (objectKind == AR_TOBJ_MATRIX) {
  3535. bool valid = true;
  3536. UINT rowCount, colCount;
  3537. GetRowsAndCols(type, rowCount, colCount);
  3538. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3539. valid = false;
  3540. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3541. }
  3542. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3543. valid = false;
  3544. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3545. }
  3546. return valid;
  3547. }
  3548. else if (qt->isStructureType()) {
  3549. const RecordType* recordType = qt->getAsStructureType();
  3550. objectKind = ClassifyRecordType(recordType);
  3551. switch (objectKind)
  3552. {
  3553. case AR_TOBJ_OBJECT:
  3554. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3555. return false;
  3556. case AR_TOBJ_COMPOUND:
  3557. {
  3558. const RecordDecl* recordDecl = recordType->getDecl();
  3559. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3560. RecordDecl::field_iterator end = recordDecl->field_end();
  3561. bool result = true;
  3562. while (begin != end) {
  3563. const FieldDecl* fieldDecl = *begin;
  3564. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3565. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3566. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3567. result = false;
  3568. }
  3569. begin++;
  3570. }
  3571. return result;
  3572. }
  3573. default:
  3574. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3575. return false;
  3576. }
  3577. }
  3578. else if(IsScalarType(qt)) {
  3579. return true;
  3580. }
  3581. else {
  3582. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3583. return false;
  3584. }
  3585. }
  3586. }
  3587. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3588. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3589. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3590. _Inout_opt_ StandardConversionSequence* sequence);
  3591. /// <summary>Produces an expression that turns the given expression into the specified numeric type.</summary>
  3592. Expr* CastExprToTypeNumeric(Expr* expr, QualType targetType);
  3593. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3594. void GetConversionForm(
  3595. QualType type,
  3596. bool explicitConversion,
  3597. ArTypeInfo* pTypeInfo);
  3598. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3599. bool suppressWarnings, bool suppressErrors,
  3600. _Inout_opt_ StandardConversionSequence* sequence);
  3601. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3602. bool ValidateTypeRequirements(
  3603. SourceLocation loc,
  3604. ArBasicKind elementKind,
  3605. ArTypeObjectKind objectKind,
  3606. bool requiresIntegrals,
  3607. bool requiresNumerics);
  3608. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3609. /// <param name="OpLoc">Source location for operator.</param>
  3610. /// <param name="Opc">Kind of binary operator.</param>
  3611. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3612. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3613. /// <param name="ResultTy">Result type for operator expression.</param>
  3614. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3615. /// <param name="CompResultTy">Type of computation result.</param>
  3616. void CheckBinOpForHLSL(
  3617. SourceLocation OpLoc,
  3618. BinaryOperatorKind Opc,
  3619. ExprResult& LHS,
  3620. ExprResult& RHS,
  3621. QualType& ResultTy,
  3622. QualType& CompLHSTy,
  3623. QualType& CompResultTy);
  3624. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3625. /// <param name="OpLoc">Source location for operator.</param>
  3626. /// <param name="Opc">Kind of operator.</param>
  3627. /// <param name="InputExpr">Input expression to the operator.</param>
  3628. /// <param name="VK">Value kind for resulting expression.</param>
  3629. /// <param name="OK">Object kind for resulting expression.</param>
  3630. /// <returns>The result type for the expression.</returns>
  3631. QualType CheckUnaryOpForHLSL(
  3632. SourceLocation OpLoc,
  3633. UnaryOperatorKind Opc,
  3634. ExprResult& InputExpr,
  3635. ExprValueKind& VK,
  3636. ExprObjectKind& OK);
  3637. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3638. /// <param name="Cond">Vector condition expression.</param>
  3639. /// <param name="LHS">Left hand side.</param>
  3640. /// <param name="RHS">Right hand side.</param>
  3641. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3642. /// <returns>Result type of vector conditional expression.</returns>
  3643. clang::QualType HLSLExternalSource::CheckVectorConditional(
  3644. _In_ ExprResult &Cond,
  3645. _In_ ExprResult &LHS,
  3646. _In_ ExprResult &RHS,
  3647. _In_ SourceLocation QuestionLoc);
  3648. clang::QualType ApplyTypeSpecSignToParsedType(
  3649. _In_ clang::QualType &type,
  3650. _In_ TypeSpecifierSign TSS,
  3651. _In_ SourceLocation Loc
  3652. );
  3653. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3654. {
  3655. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3656. {
  3657. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3658. return true;
  3659. }
  3660. return false;
  3661. }
  3662. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3663. bool
  3664. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3665. SourceLocation /* TemplateLoc */,
  3666. TemplateArgumentListInfo &TemplateArgList) {
  3667. DXASSERT_NOMSG(Template != nullptr);
  3668. // Determine which object type the template refers to.
  3669. StringRef templateName = Template->getName();
  3670. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3671. if (templateName.equals(StringRef("is_same"))) {
  3672. return false;
  3673. }
  3674. bool isMatrix = Template->getCanonicalDecl() ==
  3675. m_matrixTemplateDecl->getCanonicalDecl();
  3676. bool isVector = Template->getCanonicalDecl() ==
  3677. m_vectorTemplateDecl->getCanonicalDecl();
  3678. bool requireScalar = isMatrix || isVector;
  3679. // Check constraints on the type. Right now we only check that template
  3680. // types are primitive types.
  3681. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3682. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3683. SourceLocation argSrcLoc = argLoc.getLocation();
  3684. const TemplateArgument &arg = argLoc.getArgument();
  3685. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3686. QualType argType = arg.getAsType();
  3687. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3688. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3689. return true;
  3690. }
  3691. }
  3692. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  3693. if (isMatrix || isVector) {
  3694. Expr *expr = arg.getAsExpr();
  3695. llvm::APSInt constantResult;
  3696. if (expr != nullptr &&
  3697. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  3698. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  3699. return true;
  3700. }
  3701. }
  3702. }
  3703. }
  3704. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  3705. if (isMatrix || isVector) {
  3706. llvm::APSInt Val = arg.getAsIntegral();
  3707. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  3708. return true;
  3709. }
  3710. }
  3711. }
  3712. }
  3713. return false;
  3714. }
  3715. /// <summary>Diagnoses an assignment operation.</summary>
  3716. /// <param name="ConvTy">Type of conversion assignment.</param>
  3717. /// <param name="Loc">Location for operation.</param>
  3718. /// <param name="DstType">Destination type.</param>
  3719. /// <param name="SrcType">Source type.</param>
  3720. /// <param name="SrcExpr">Source expression.</param>
  3721. /// <param name="Action">Action that triggers the assignment (assignment, passing, return, etc).</param>
  3722. /// <param name="Complained">Whether a diagnostic was emitted.</param>
  3723. void DiagnoseAssignmentResultForHLSL(
  3724. Sema::AssignConvertType ConvTy,
  3725. SourceLocation Loc,
  3726. QualType DstType, QualType SrcType,
  3727. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  3728. _Out_opt_ bool *Complained);
  3729. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  3730. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  3731. /// <param name="functionDeclContext">Declaration context of function.</param>
  3732. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  3733. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  3734. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  3735. void FindIntrinsicTable(
  3736. _In_ DeclContext* functionDeclContext,
  3737. _Outptr_result_z_ const char** name,
  3738. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  3739. _Out_ size_t* intrinsicCount);
  3740. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  3741. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  3742. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  3743. /// <param name="Args">Array of expressions being used as arguments.</param>
  3744. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  3745. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  3746. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  3747. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  3748. FunctionTemplateDecl *FunctionTemplate,
  3749. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3750. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  3751. clang::OverloadingResult GetBestViableFunction(
  3752. clang::SourceLocation Loc,
  3753. clang::OverloadCandidateSet& set,
  3754. clang::OverloadCandidateSet::iterator& Best);
  3755. /// <summary>
  3756. /// Initializes the specified <paramref name="initSequence" /> describing how
  3757. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  3758. /// </summary>
  3759. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  3760. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  3761. /// <param name="Args">Arguments to the initialization.</param>
  3762. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  3763. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  3764. void InitializeInitSequenceForHLSL(
  3765. const InitializedEntity& Entity,
  3766. const InitializationKind& Kind,
  3767. MultiExprArg Args,
  3768. bool TopLevelOfInitList,
  3769. _Inout_ InitializationSequence* initSequence);
  3770. /// <summary>
  3771. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3772. /// </summary>
  3773. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3774. bool IsConversionToLessOrEqualElements(
  3775. const ExprResult& sourceExpr,
  3776. const QualType& targetType,
  3777. bool explicitConversion);
  3778. /// <summary>
  3779. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3780. /// </summary>
  3781. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3782. bool IsConversionToLessOrEqualElements(
  3783. const QualType& sourceType,
  3784. const QualType& targetType,
  3785. bool explicitConversion);
  3786. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  3787. /// <param name="BaseExpr">Base expression for member access.</param>
  3788. /// <param name="MemberName">Name of member to look up.</param>
  3789. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3790. /// <param name="OpLoc">Location of access operand.</param>
  3791. /// <param name="MemberLoc">Location of member.</param>
  3792. /// <param name="result">Result of lookup operation.</param>
  3793. /// <returns>true if the base type is a matrix and the lookup has been handled.</returns>
  3794. bool LookupMatrixMemberExprForHLSL(
  3795. Expr& BaseExpr,
  3796. DeclarationName MemberName,
  3797. bool IsArrow,
  3798. SourceLocation OpLoc,
  3799. SourceLocation MemberLoc,
  3800. ExprResult* result);
  3801. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  3802. /// <param name="BaseExpr">Base expression for member access.</param>
  3803. /// <param name="MemberName">Name of member to look up.</param>
  3804. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3805. /// <param name="OpLoc">Location of access operand.</param>
  3806. /// <param name="MemberLoc">Location of member.</param>
  3807. /// <param name="result">Result of lookup operation.</param>
  3808. /// <returns>true if the base type is a vector and the lookup has been handled.</returns>
  3809. bool LookupVectorMemberExprForHLSL(
  3810. Expr& BaseExpr,
  3811. DeclarationName MemberName,
  3812. bool IsArrow,
  3813. SourceLocation OpLoc,
  3814. SourceLocation MemberLoc,
  3815. ExprResult* result);
  3816. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  3817. /// <param name="E">Expression to convert.</param>
  3818. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  3819. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  3820. clang::Expr *HLSLImpCastToScalar(
  3821. _In_ clang::Sema* self,
  3822. _In_ clang::Expr* From,
  3823. ArTypeObjectKind FromShape,
  3824. ArBasicKind EltKind);
  3825. clang::ExprResult PerformHLSLConversion(
  3826. _In_ clang::Expr* From,
  3827. _In_ clang::QualType targetType,
  3828. _In_ const clang::StandardConversionSequence &SCS,
  3829. _In_ clang::Sema::CheckedConversionKind CCK);
  3830. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  3831. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  3832. /// <summary>
  3833. /// Checks if a static cast can be performed, and performs it if possible.
  3834. /// </summary>
  3835. /// <param name="SrcExpr">Expression to cast.</param>
  3836. /// <param name="DestType">Type to cast SrcExpr to.</param>
  3837. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  3838. /// <param name="OpRange">Source range for the cast operation.</param>
  3839. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  3840. /// <param name="Kind">The kind of operation required for a conversion.</param>
  3841. /// <param name="BasePath">A simple array of base specifiers.</param>
  3842. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  3843. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  3844. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  3845. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  3846. QualType DestType,
  3847. Sema::CheckedConversionKind CCK,
  3848. const SourceRange &OpRange, unsigned &msg,
  3849. CastKind &Kind, CXXCastPath &BasePath,
  3850. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  3851. _Inout_opt_ StandardConversionSequence* standard);
  3852. /// <summary>
  3853. /// Checks if a subscript index argument can be initialized from the given expression.
  3854. /// </summary>
  3855. /// <param name="SrcExpr">Source expression used as argument.</param>
  3856. /// <param name="DestType">Parameter type to initialize.</param>
  3857. /// <remarks>
  3858. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  3859. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  3860. /// </remarks>
  3861. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  3862. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  3863. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  3864. // Everything is ready.
  3865. if (m_objectTypeLazyInitMask == 0)
  3866. return;
  3867. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  3868. int idx = FindObjectBasicKindIndex(recordDecl);
  3869. // Not object type.
  3870. if (idx == -1)
  3871. return;
  3872. uint64_t bit = ((uint64_t)1)<<idx;
  3873. // Already created.
  3874. if ((m_objectTypeLazyInitMask & bit) == 0)
  3875. return;
  3876. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  3877. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  3878. int startDepth = 0;
  3879. if (templateArgCount > 0) {
  3880. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  3881. "otherwise a new case has been added");
  3882. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  3883. AddObjectSubscripts(kind, typeDecl, recordDecl,
  3884. g_ArBasicKindsSubscripts[idx]);
  3885. startDepth = 1;
  3886. }
  3887. AddObjectMethods(kind, recordDecl, startDepth);
  3888. // Clear the object.
  3889. m_objectTypeLazyInitMask &= ~bit;
  3890. }
  3891. FunctionDecl* AddHLSLIntrinsicMethod(
  3892. LPCSTR tableName,
  3893. LPCSTR lowering,
  3894. _In_ const HLSL_INTRINSIC* intrinsic,
  3895. _In_ FunctionTemplateDecl *FunctionTemplate,
  3896. ArrayRef<Expr *> Args,
  3897. _In_count_(parameterTypeCount) QualType* parameterTypes,
  3898. size_t parameterTypeCount)
  3899. {
  3900. DXASSERT_NOMSG(intrinsic != nullptr);
  3901. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  3902. DXASSERT_NOMSG(parameterTypes != nullptr);
  3903. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  3904. // Create the template arguments.
  3905. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  3906. for (size_t i = 0; i < parameterTypeCount; i++) {
  3907. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  3908. }
  3909. // Look for an existing specialization.
  3910. void *InsertPos = nullptr;
  3911. FunctionDecl *SpecFunc =
  3912. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  3913. if (SpecFunc != nullptr) {
  3914. return SpecFunc;
  3915. }
  3916. // Change return type to rvalue reference type for aggregate types
  3917. QualType retTy = parameterTypes[0];
  3918. if (retTy->isAggregateType() && !IsHLSLVecMatType(retTy))
  3919. parameterTypes[0] = m_context->getRValueReferenceType(retTy);
  3920. // Create a new specialization.
  3921. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  3922. InitParamMods(intrinsic, paramMods);
  3923. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3924. // Change out/inout parameter type to rvalue reference type.
  3925. if (paramMods[i - 1].isAnyOut()) {
  3926. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  3927. }
  3928. }
  3929. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  3930. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  3931. // Remove this when update intrinsic table not affect other things.
  3932. // Change vector<float,1> into float for bias.
  3933. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  3934. DXASSERT(parameterTypeCount > biasOperandID,
  3935. "else operation was misrecognized");
  3936. if (const ExtVectorType *VecTy =
  3937. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  3938. *m_context, parameterTypes[biasOperandID])) {
  3939. if (VecTy->getNumElements() == 1)
  3940. parameterTypes[biasOperandID] = VecTy->getElementType();
  3941. }
  3942. }
  3943. DeclContext *owner = FunctionTemplate->getDeclContext();
  3944. TemplateArgumentList templateArgumentList(
  3945. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  3946. templateArgs.size());
  3947. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  3948. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  3949. mlTemplateArgumentList);
  3950. FunctionProtoType::ExtProtoInfo EmptyEPI;
  3951. QualType functionType = m_context->getFunctionType(
  3952. parameterTypes[0],
  3953. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  3954. EmptyEPI, paramMods);
  3955. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  3956. FunctionProtoTypeLoc Proto =
  3957. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  3958. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  3959. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3960. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  3961. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  3962. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  3963. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  3964. Params.push_back(paramDecl);
  3965. }
  3966. QualType T = TInfo->getType();
  3967. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  3968. CXXMethodDecl* method = CXXMethodDecl::Create(
  3969. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  3970. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  3971. // Add intrinsic attr
  3972. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  3973. // Record this function template specialization.
  3974. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  3975. *m_context, templateArgs.data(), templateArgs.size());
  3976. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  3977. // Attach the parameters
  3978. for (unsigned P = 0; P < Params.size(); ++P) {
  3979. Params[P]->setOwningFunction(method);
  3980. Proto.setParam(P, Params[P]);
  3981. }
  3982. method->setParams(Params);
  3983. // Adjust access.
  3984. method->setAccess(AccessSpecifier::AS_public);
  3985. FunctionTemplate->setAccess(method->getAccess());
  3986. return method;
  3987. }
  3988. // Overload support.
  3989. UINT64 ScoreCast(QualType leftType, QualType rightType);
  3990. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  3991. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  3992. unsigned GetNumElements(QualType anyType);
  3993. unsigned GetNumBasicElements(QualType anyType);
  3994. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  3995. QualType GetNthElementType(QualType type, unsigned index);
  3996. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  3997. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3998. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3999. };
  4000. // Use this class to flatten a type into HLSL primitives and iterate through them.
  4001. class FlattenedTypeIterator
  4002. {
  4003. private:
  4004. enum FlattenedIterKind {
  4005. FK_Simple,
  4006. FK_Fields,
  4007. FK_Expressions,
  4008. FK_IncompleteArray,
  4009. FK_Bases,
  4010. };
  4011. // Use this struct to represent a specific point in the tracked tree.
  4012. struct FlattenedTypeTracker {
  4013. QualType Type; // Type at this position in the tree.
  4014. unsigned int Count; // Count of consecutive types
  4015. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  4016. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  4017. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  4018. RecordDecl::field_iterator EndField; // STL-style end of fields.
  4019. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  4020. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  4021. FlattenedIterKind IterKind; // Kind of tracker.
  4022. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  4023. FlattenedTypeTracker(QualType type)
  4024. : Type(type), Count(0), CurrentExpr(nullptr),
  4025. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  4026. FlattenedTypeTracker(QualType type, unsigned int count,
  4027. MultiExprArg::iterator expression)
  4028. : Type(type), Count(count), CurrentExpr(expression),
  4029. IterKind(FK_Simple), IsConsidered(false) {}
  4030. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  4031. RecordDecl::field_iterator end)
  4032. : Type(type), Count(0), CurrentField(current), EndField(end),
  4033. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  4034. FlattenedTypeTracker(MultiExprArg::iterator current,
  4035. MultiExprArg::iterator end)
  4036. : Count(0), CurrentExpr(current), EndExpr(end),
  4037. IterKind(FK_Expressions), IsConsidered(false) {}
  4038. FlattenedTypeTracker(QualType type,
  4039. CXXRecordDecl::base_class_iterator current,
  4040. CXXRecordDecl::base_class_iterator end)
  4041. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  4042. IterKind(FK_Bases), IsConsidered(false) {}
  4043. /// <summary>Gets the current expression if one is available.</summary>
  4044. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  4045. /// <summary>Replaces the current expression.</summary>
  4046. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  4047. };
  4048. HLSLExternalSource& m_source; // Source driving the iteration.
  4049. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  4050. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  4051. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  4052. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  4053. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  4054. QualType m_firstType; // Name of first type found, used for diagnostics.
  4055. SourceLocation m_loc; // Location used for diagnostics.
  4056. static const size_t MaxTypeDepth = 100;
  4057. void advanceLeafTracker();
  4058. /// <summary>Consumes leaves.</summary>
  4059. void consumeLeaf();
  4060. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  4061. bool considerLeaf();
  4062. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  4063. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  4064. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  4065. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  4066. public:
  4067. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  4068. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  4069. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  4070. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  4071. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  4072. QualType getCurrentElement() const;
  4073. /// <summary>Get the number of repeated current elements.</summary>
  4074. unsigned int getCurrentElementSize() const;
  4075. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  4076. bool hasCurrentElement() const;
  4077. /// <summary>Consumes count elements on this iterator.</summary>
  4078. void advanceCurrentElement(unsigned int count);
  4079. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  4080. unsigned int countRemaining();
  4081. /// <summary>Gets the current expression if one is available.</summary>
  4082. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  4083. /// <summary>Replaces the current expression.</summary>
  4084. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  4085. struct ComparisonResult
  4086. {
  4087. unsigned int LeftCount;
  4088. unsigned int RightCount;
  4089. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  4090. bool AreElementsEqual;
  4091. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  4092. bool CanConvertElements;
  4093. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  4094. bool IsConvertibleAndEqualLength() const {
  4095. return LeftCount == RightCount;
  4096. }
  4097. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  4098. bool IsConvertibleAndLeftLonger() const {
  4099. return CanConvertElements && LeftCount > RightCount;
  4100. }
  4101. bool IsRightLonger() const {
  4102. return RightCount > LeftCount;
  4103. }
  4104. };
  4105. static ComparisonResult CompareIterators(
  4106. HLSLExternalSource& source, SourceLocation loc,
  4107. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  4108. static ComparisonResult CompareTypes(
  4109. HLSLExternalSource& source,
  4110. SourceLocation leftLoc, SourceLocation rightLoc,
  4111. QualType left, QualType right);
  4112. // Compares the arguments to initialize the left type, modifying them if necessary.
  4113. static ComparisonResult CompareTypesForInit(
  4114. HLSLExternalSource& source, QualType left, MultiExprArg args,
  4115. SourceLocation leftLoc, SourceLocation rightLoc);
  4116. };
  4117. static
  4118. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  4119. {
  4120. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  4121. if (specialization) {
  4122. const TemplateArgumentList& list = specialization->getTemplateArgs();
  4123. if (list.size()) {
  4124. return list[0].getAsType();
  4125. }
  4126. }
  4127. return QualType();
  4128. }
  4129. static
  4130. QualType GetFirstElementType(QualType type)
  4131. {
  4132. if (!type.isNull()) {
  4133. const RecordType* record = type->getAs<RecordType>();
  4134. if (record) {
  4135. return GetFirstElementTypeFromDecl(record->getDecl());
  4136. }
  4137. }
  4138. return QualType();
  4139. }
  4140. void HLSLExternalSource::AddBaseTypes()
  4141. {
  4142. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4143. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4144. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4145. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4146. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4147. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->FloatTy : m_context->HalfTy;
  4148. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4149. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4150. m_baseTypes[HLSLScalarType_float_min10] = m_context->HalfTy;
  4151. m_baseTypes[HLSLScalarType_float_min16] = m_context->HalfTy;
  4152. m_baseTypes[HLSLScalarType_int_min12] = m_context->ShortTy;
  4153. m_baseTypes[HLSLScalarType_int_min16] = m_context->ShortTy;
  4154. m_baseTypes[HLSLScalarType_uint_min16] = m_context->UnsignedShortTy;
  4155. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4156. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4157. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4158. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4159. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4160. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4161. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4162. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4163. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4164. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4165. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4166. }
  4167. void HLSLExternalSource::AddHLSLScalarTypes()
  4168. {
  4169. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4170. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4171. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4172. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4173. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4174. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4175. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4176. }
  4177. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4178. _In_ FunctionTemplateDecl* functionTemplate,
  4179. QualType objectElement,
  4180. const FindStructBasicTypeResult& findResult)
  4181. {
  4182. DXASSERT_NOMSG(functionTemplate != nullptr);
  4183. DXASSERT_NOMSG(!objectElement.isNull());
  4184. DXASSERT_NOMSG(findResult.Found());
  4185. DXASSERT(
  4186. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4187. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4188. // Subscript is templated only on its return type.
  4189. // Create the template argument.
  4190. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4191. QualType resultType = objectElement;
  4192. if (isReadWrite)
  4193. resultType = m_context->getLValueReferenceType(resultType, false);
  4194. else {
  4195. // Add const to avoid write.
  4196. resultType = m_context->getConstType(resultType);
  4197. resultType = m_context->getLValueReferenceType(resultType);
  4198. }
  4199. TemplateArgument templateArgument(resultType);
  4200. unsigned subscriptCardinality =
  4201. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4202. QualType subscriptIndexType =
  4203. subscriptCardinality == 1
  4204. ? m_context->UnsignedIntTy
  4205. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4206. subscriptCardinality);
  4207. // Look for an existing specialization.
  4208. void* InsertPos = nullptr;
  4209. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4210. if (SpecFunc != nullptr) {
  4211. return SpecFunc;
  4212. }
  4213. // Create a new specialization.
  4214. DeclContext* owner = functionTemplate->getDeclContext();
  4215. TemplateArgumentList templateArgumentList(
  4216. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4217. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4218. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4219. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4220. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4221. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4222. QualType functionType = m_context->getFunctionType(
  4223. resultType, subscriptIndexType, templateEPI, None);
  4224. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4225. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4226. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4227. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4228. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4229. QualType T = TInfo->getType();
  4230. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4231. CXXMethodDecl* method = CXXMethodDecl::Create(
  4232. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4233. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4234. // Add subscript attribute
  4235. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4236. // Record this function template specialization.
  4237. method->setFunctionTemplateSpecialization(functionTemplate,
  4238. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4239. // Attach the parameters
  4240. indexerParam->setOwningFunction(method);
  4241. Proto.setParam(0, indexerParam);
  4242. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4243. // Adjust access.
  4244. method->setAccess(AccessSpecifier::AS_public);
  4245. functionTemplate->setAccess(method->getAccess());
  4246. return method;
  4247. }
  4248. /// <summary>
  4249. /// This routine combines Source into Target. If you have a symmetric operation
  4250. /// and want to treat either side equally you should call it twice, swapping the
  4251. /// parameter order.
  4252. /// </summary>
  4253. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4254. _Out_opt_ ArBasicKind *pCombined) {
  4255. if (Target == Source) {
  4256. AssignOpt(Target, pCombined);
  4257. return true;
  4258. }
  4259. if (Source == AR_OBJECT_NULL) {
  4260. // NULL is valid for any object type.
  4261. AssignOpt(Target, pCombined);
  4262. return true;
  4263. }
  4264. switch (Target) {
  4265. AR_BASIC_ROBJECT_CASES:
  4266. if (Source == AR_OBJECT_STATEBLOCK) {
  4267. AssignOpt(Target, pCombined);
  4268. return true;
  4269. }
  4270. break;
  4271. AR_BASIC_TEXTURE_CASES:
  4272. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4273. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4274. AssignOpt(Target, pCombined);
  4275. return true;
  4276. }
  4277. break;
  4278. case AR_OBJECT_SAMPLERCOMPARISON:
  4279. if (Source == AR_OBJECT_STATEBLOCK) {
  4280. AssignOpt(Target, pCombined);
  4281. return true;
  4282. }
  4283. break;
  4284. }
  4285. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4286. return false;
  4287. }
  4288. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4289. HLSLExternalSource *pHLSLExternalSource) {
  4290. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4291. llvm::APInt val = intLit->getValue();
  4292. unsigned width = val.getActiveBits();
  4293. bool isNeg = val.isNegative();
  4294. if (isNeg) {
  4295. // Signed.
  4296. if (width <= 32)
  4297. return ArBasicKind::AR_BASIC_INT32;
  4298. else
  4299. return ArBasicKind::AR_BASIC_INT64;
  4300. } else {
  4301. // Unsigned.
  4302. if (width <= 32)
  4303. return ArBasicKind::AR_BASIC_UINT32;
  4304. else
  4305. return ArBasicKind::AR_BASIC_UINT64;
  4306. }
  4307. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4308. llvm::APFloat val = floatLit->getValue();
  4309. unsigned width = val.getSizeInBits(val.getSemantics());
  4310. if (width <= 16)
  4311. return ArBasicKind::AR_BASIC_FLOAT16;
  4312. else if (width <= 32)
  4313. return ArBasicKind::AR_BASIC_FLOAT32;
  4314. else
  4315. return AR_BASIC_FLOAT64;
  4316. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4317. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4318. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4319. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4320. kind = ArBasicKind::AR_BASIC_INT32;
  4321. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4322. kind = ArBasicKind::AR_BASIC_INT64;
  4323. }
  4324. return kind;
  4325. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4326. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4327. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4328. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4329. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4330. CombineBasicTypes(kind, kind1, &kind);
  4331. return kind;
  4332. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4333. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4334. return kind;
  4335. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4336. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4337. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4338. CombineBasicTypes(kind, kind1, &kind);
  4339. return kind;
  4340. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4341. // Use target Type for cast.
  4342. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4343. return kind;
  4344. } else {
  4345. // Could only be function call.
  4346. CallExpr *CE = cast<CallExpr>(litExpr);
  4347. // TODO: calculate the function call result.
  4348. if (CE->getNumArgs() == 1)
  4349. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4350. else {
  4351. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4352. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4353. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4354. CombineBasicTypes(kind, kindI, &kind);
  4355. }
  4356. return kind;
  4357. }
  4358. }
  4359. }
  4360. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4361. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4362. if (kind == *pCT)
  4363. return true;
  4364. pCT++;
  4365. }
  4366. return false;
  4367. }
  4368. static ArBasicKind
  4369. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4370. unsigned uLegalComponentTypes,
  4371. HLSLExternalSource *pHLSLExternalSource) {
  4372. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4373. ArBasicKind defaultKind = *pCT;
  4374. // Use first none literal kind as defaultKind.
  4375. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4376. ArBasicKind kind = *pCT;
  4377. pCT++;
  4378. // Skip literal type.
  4379. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4380. continue;
  4381. defaultKind = kind;
  4382. break;
  4383. }
  4384. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4385. if (kind == AR_BASIC_LITERAL_INT) {
  4386. // Search for match first.
  4387. // For literal arg which don't affect return type, the search should always success.
  4388. // Unless use literal int on a float parameter.
  4389. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4390. return litKind;
  4391. // Return the default.
  4392. return defaultKind;
  4393. }
  4394. else {
  4395. // Search for float32 first.
  4396. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4397. return AR_BASIC_FLOAT32;
  4398. // Search for float64.
  4399. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4400. return AR_BASIC_FLOAT64;
  4401. // return default.
  4402. return defaultKind;
  4403. }
  4404. }
  4405. _Use_decl_annotations_ bool
  4406. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4407. QualType objectElement) {
  4408. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4409. switch (op) {
  4410. case IntrinsicOp::MOP_Sample:
  4411. case IntrinsicOp::MOP_SampleBias:
  4412. case IntrinsicOp::MOP_SampleCmp:
  4413. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4414. case IntrinsicOp::MOP_SampleGrad:
  4415. case IntrinsicOp::MOP_SampleLevel: {
  4416. ArBasicKind kind = GetTypeElementKind(objectElement);
  4417. UINT uBits = GET_BPROP_BITS(kind);
  4418. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4419. } break;
  4420. default:
  4421. return true;
  4422. }
  4423. }
  4424. _Use_decl_annotations_
  4425. bool HLSLExternalSource::MatchArguments(
  4426. const HLSL_INTRINSIC* pIntrinsic,
  4427. QualType objectElement,
  4428. ArrayRef<Expr *> Args,
  4429. QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  4430. size_t* argCount)
  4431. {
  4432. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4433. DXASSERT_NOMSG(argCount != nullptr);
  4434. static const UINT UnusedSize = 0xFF;
  4435. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4436. #define CAB(_) { if (!(_)) return false; }
  4437. *argCount = 0;
  4438. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4439. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4440. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4441. // Reset infos
  4442. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4443. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4444. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4445. const unsigned retArgIdx = 0;
  4446. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4447. // Populate the template for each argument.
  4448. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4449. ArrayRef<Expr*>::iterator end = Args.end();
  4450. unsigned int iArg = 1;
  4451. for (; iterArg != end; ++iterArg) {
  4452. Expr* pCallArg = *iterArg;
  4453. // No vararg support.
  4454. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  4455. return false;
  4456. }
  4457. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  4458. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  4459. DXASSERT(pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS, "no vararg support");
  4460. QualType pType = pCallArg->getType();
  4461. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  4462. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  4463. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_RAYDESC) {
  4464. if (TypeInfoShapeKind == AR_TOBJ_COMPOUND) {
  4465. if (CXXRecordDecl *pDecl = pType->getAsCXXRecordDecl()) {
  4466. int index = FindObjectBasicKindIndex(pDecl);
  4467. if (index != -1 && AR_OBJECT_RAY_DESC == g_ArBasicKindsAsTypes[index]) {
  4468. ++iArg;
  4469. continue;
  4470. }
  4471. }
  4472. }
  4473. m_sema->Diag(pCallArg->getExprLoc(),
  4474. diag::err_hlsl_ray_desc_required);
  4475. return false;
  4476. }
  4477. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4478. DXASSERT(objectElement.isNull(), "");
  4479. QualType Ty = pCallArg->getType();
  4480. // Must be user define type for LICOMPTYPE_USER_DEFINED_TYPE arg.
  4481. if (TypeInfoShapeKind != AR_TOBJ_COMPOUND) {
  4482. m_sema->Diag(pCallArg->getExprLoc(),
  4483. diag::err_hlsl_no_struct_user_defined_type);
  4484. return false;
  4485. }
  4486. objectElement = Ty;
  4487. ++iArg;
  4488. continue;
  4489. }
  4490. // If we are a type and templateID requires one, this isn't a match.
  4491. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4492. ++iArg;
  4493. continue;
  4494. }
  4495. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  4496. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  4497. bool affectRetType =
  4498. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  4499. // For literal arg which don't affect return type, find concrete type.
  4500. // For literal arg affect return type,
  4501. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  4502. // where all argumentss are literal.
  4503. // CombineBasicTypes will cover the rest cases.
  4504. if (!affectRetType) {
  4505. TypeInfoEltKind = ConcreteLiteralType(
  4506. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  4507. }
  4508. }
  4509. UINT TypeInfoCols = 1;
  4510. UINT TypeInfoRows = 1;
  4511. switch (TypeInfoShapeKind) {
  4512. case AR_TOBJ_MATRIX:
  4513. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  4514. break;
  4515. case AR_TOBJ_VECTOR:
  4516. TypeInfoCols = GetHLSLVecSize(pType);
  4517. break;
  4518. case AR_TOBJ_BASIC:
  4519. case AR_TOBJ_OBJECT:
  4520. break;
  4521. default:
  4522. return false; // no struct, arrays or void
  4523. }
  4524. DXASSERT(
  4525. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  4526. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  4527. // Compare template
  4528. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  4529. (AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  4530. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind)) {
  4531. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  4532. }
  4533. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  4534. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  4535. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  4536. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  4537. return false;
  4538. }
  4539. }
  4540. else {
  4541. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  4542. return false;
  4543. }
  4544. }
  4545. DXASSERT(
  4546. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4547. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4548. // Merge ComponentTypes
  4549. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4550. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4551. }
  4552. else {
  4553. if (!CombineBasicTypes(
  4554. ComponentType[pIntrinsicArg->uComponentTypeId],
  4555. TypeInfoEltKind,
  4556. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4557. return false;
  4558. }
  4559. }
  4560. // Rows
  4561. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4562. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4563. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4564. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4565. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4566. uSpecialSize[uSpecialId] = TypeInfoRows;
  4567. }
  4568. }
  4569. else {
  4570. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4571. return false;
  4572. }
  4573. }
  4574. }
  4575. // Columns
  4576. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4577. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4578. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4579. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4580. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4581. uSpecialSize[uSpecialId] = TypeInfoCols;
  4582. }
  4583. }
  4584. else {
  4585. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4586. return false;
  4587. }
  4588. }
  4589. }
  4590. // Usage
  4591. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4592. if (pCallArg->getType().isConstQualified()) {
  4593. // Can't use a const type in an out or inout parameter.
  4594. return false;
  4595. }
  4596. }
  4597. iArg++;
  4598. }
  4599. DXASSERT(iterArg == end, "otherwise the argument list wasn't fully processed");
  4600. // Default template and component type for return value
  4601. if (pIntrinsic->pArgs[0].qwUsage && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE) {
  4602. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4603. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4604. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4605. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4606. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4607. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4608. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4609. // half return type should map to float for min precision
  4610. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  4611. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  4612. getSema()->getLangOpts().UseMinPrecision) {
  4613. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4614. ArBasicKind::AR_BASIC_FLOAT32;
  4615. }
  4616. else {
  4617. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4618. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4619. }
  4620. }
  4621. }
  4622. }
  4623. }
  4624. // Make sure all template, component type, and texture type selections are valid.
  4625. for (size_t i = 0; i < Args.size() + 1; i++) {
  4626. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4627. // Check template.
  4628. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4629. continue; // Already verified that this is available.
  4630. }
  4631. if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4632. continue;
  4633. }
  4634. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4635. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4636. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4637. Template[i] = *pTT;
  4638. }
  4639. else {
  4640. while (AR_TOBJ_UNKNOWN != *pTT) {
  4641. if (Template[i] == *pTT)
  4642. break;
  4643. pTT++;
  4644. }
  4645. }
  4646. if (AR_TOBJ_UNKNOWN == *pTT)
  4647. return false;
  4648. }
  4649. else if (pTT) {
  4650. Template[i] = *pTT;
  4651. }
  4652. // Check component type.
  4653. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4654. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4655. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4656. if (ComponentType[i] == *pCT)
  4657. break;
  4658. pCT++;
  4659. }
  4660. // has to be a strict match
  4661. if (*pCT == AR_BASIC_NOCAST)
  4662. return false;
  4663. // If it is an object, see if it can be cast to the first thing in the
  4664. // list, otherwise move on to next intrinsic.
  4665. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4666. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4667. return false;
  4668. }
  4669. }
  4670. if (AR_BASIC_UNKNOWN == *pCT) {
  4671. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4672. }
  4673. }
  4674. else if (pCT) {
  4675. ComponentType[i] = *pCT;
  4676. }
  4677. }
  4678. // Default to a void return type.
  4679. argTypes[0] = m_context->VoidTy;
  4680. // Default specials sizes.
  4681. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  4682. if (UnusedSize == uSpecialSize[i]) {
  4683. uSpecialSize[i] = 1;
  4684. }
  4685. }
  4686. // Populate argTypes.
  4687. for (size_t i = 0; i <= Args.size(); i++) {
  4688. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4689. if (!pArgument->qwUsage)
  4690. continue;
  4691. QualType pNewType;
  4692. unsigned int quals = 0; // qualifications for this argument
  4693. // If we have no type, set it to our input type (templatized)
  4694. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4695. // Use the templated input type, but resize it if the
  4696. // intrinsic's rows/cols isn't 0
  4697. if (pArgument->uRows && pArgument->uCols) {
  4698. UINT uRows, uCols;
  4699. // if type is overriden, use new type size, for
  4700. // now it only supports scalars
  4701. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4702. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4703. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4704. uRows = uSpecialSize[uSpecialId];
  4705. }
  4706. else if (pArgument->uRows > 0) {
  4707. uRows = pArgument->uRows;
  4708. }
  4709. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4710. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4711. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4712. uCols = uSpecialSize[uSpecialId];
  4713. }
  4714. else if (pArgument->uCols > 0) {
  4715. uCols = pArgument->uCols;
  4716. }
  4717. // 1x1 numeric outputs are always scalar.. since these
  4718. // are most flexible
  4719. if ((1 == uCols) && (1 == uRows)) {
  4720. pNewType = objectElement;
  4721. if (pNewType.isNull()) {
  4722. return false;
  4723. }
  4724. }
  4725. else {
  4726. // non-scalars unsupported right now since nothing
  4727. // uses it, would have to create either a type
  4728. // list for sub-structures or just resize the
  4729. // given type
  4730. // VH(E_NOTIMPL);
  4731. return false;
  4732. }
  4733. }
  4734. else {
  4735. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  4736. if (objectElement.isNull()) {
  4737. return false;
  4738. }
  4739. pNewType = objectElement;
  4740. }
  4741. } else if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4742. if (objectElement.isNull()) {
  4743. return false;
  4744. }
  4745. pNewType = objectElement;
  4746. } else {
  4747. ArBasicKind pEltType;
  4748. // ComponentType, if the Id is special then it gets the
  4749. // component type from the first component of the type, if
  4750. // we need more (for the second component, e.g.), then we
  4751. // can use more specials, etc.
  4752. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4753. if (objectElement.isNull()) {
  4754. return false;
  4755. }
  4756. pEltType = GetTypeElementKind(objectElement);
  4757. DXASSERT_VALIDBASICKIND(pEltType);
  4758. }
  4759. else {
  4760. pEltType = ComponentType[pArgument->uComponentTypeId];
  4761. DXASSERT_VALIDBASICKIND(pEltType);
  4762. }
  4763. UINT uRows, uCols;
  4764. // Rows
  4765. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4766. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4767. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4768. uRows = uSpecialSize[uSpecialId];
  4769. }
  4770. else {
  4771. uRows = pArgument->uRows;
  4772. }
  4773. // Cols
  4774. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4775. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4776. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4777. uCols = uSpecialSize[uSpecialId];
  4778. }
  4779. else {
  4780. uCols = pArgument->uCols;
  4781. }
  4782. // Verify that the final results are in bounds.
  4783. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  4784. // Const
  4785. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  4786. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  4787. qwQual |= AR_QUAL_CONST;
  4788. DXASSERT_VALIDBASICKIND(pEltType);
  4789. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  4790. }
  4791. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  4792. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  4793. // TODO: support out modifier
  4794. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  4795. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  4796. //}
  4797. }
  4798. *argCount = iArg;
  4799. DXASSERT(
  4800. *argCount == pIntrinsic->uNumArgs,
  4801. "In the absence of varargs, a successful match would indicate we have as many arguments and types as the intrinsic template");
  4802. return true;
  4803. #undef CAB
  4804. }
  4805. _Use_decl_annotations_
  4806. HLSLExternalSource::FindStructBasicTypeResult
  4807. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  4808. {
  4809. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4810. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  4811. // may be a simple class, such as RWByteAddressBuffer.
  4812. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  4813. // We save the caller from filtering out other types of context (like the translation unit itself).
  4814. if (recordDecl != nullptr)
  4815. {
  4816. int index = FindObjectBasicKindIndex(recordDecl);
  4817. if (index != -1) {
  4818. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  4819. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  4820. }
  4821. }
  4822. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  4823. }
  4824. _Use_decl_annotations_
  4825. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  4826. {
  4827. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4828. DXASSERT_NOMSG(name != nullptr);
  4829. DXASSERT_NOMSG(intrinsics != nullptr);
  4830. DXASSERT_NOMSG(intrinsicCount != nullptr);
  4831. *intrinsics = nullptr;
  4832. *intrinsicCount = 0;
  4833. *name = nullptr;
  4834. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  4835. if (lookup.Found()) {
  4836. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  4837. *name = g_ArBasicTypeNames[lookup.Kind];
  4838. }
  4839. }
  4840. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  4841. {
  4842. return
  4843. // Arithmetic operators.
  4844. Opc == BinaryOperatorKind::BO_Add ||
  4845. Opc == BinaryOperatorKind::BO_AddAssign ||
  4846. Opc == BinaryOperatorKind::BO_Sub ||
  4847. Opc == BinaryOperatorKind::BO_SubAssign ||
  4848. Opc == BinaryOperatorKind::BO_Rem ||
  4849. Opc == BinaryOperatorKind::BO_RemAssign ||
  4850. Opc == BinaryOperatorKind::BO_Div ||
  4851. Opc == BinaryOperatorKind::BO_DivAssign ||
  4852. Opc == BinaryOperatorKind::BO_Mul ||
  4853. Opc == BinaryOperatorKind::BO_MulAssign;
  4854. }
  4855. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  4856. {
  4857. return
  4858. // Arithmetic-and-assignment operators.
  4859. Opc == BinaryOperatorKind::BO_AddAssign ||
  4860. Opc == BinaryOperatorKind::BO_SubAssign ||
  4861. Opc == BinaryOperatorKind::BO_RemAssign ||
  4862. Opc == BinaryOperatorKind::BO_DivAssign ||
  4863. Opc == BinaryOperatorKind::BO_MulAssign ||
  4864. // Bitwise-and-assignment operators.
  4865. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4866. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4867. Opc == BinaryOperatorKind::BO_AndAssign ||
  4868. Opc == BinaryOperatorKind::BO_OrAssign ||
  4869. Opc == BinaryOperatorKind::BO_XorAssign;
  4870. }
  4871. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  4872. {
  4873. return
  4874. Opc == BinaryOperatorKind::BO_AndAssign ||
  4875. Opc == BinaryOperatorKind::BO_OrAssign ||
  4876. Opc == BinaryOperatorKind::BO_XorAssign;
  4877. }
  4878. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  4879. {
  4880. return
  4881. Opc == BinaryOperatorKind::BO_Shl ||
  4882. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4883. Opc == BinaryOperatorKind::BO_Shr ||
  4884. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4885. Opc == BinaryOperatorKind::BO_And ||
  4886. Opc == BinaryOperatorKind::BO_AndAssign ||
  4887. Opc == BinaryOperatorKind::BO_Or ||
  4888. Opc == BinaryOperatorKind::BO_OrAssign ||
  4889. Opc == BinaryOperatorKind::BO_Xor ||
  4890. Opc == BinaryOperatorKind::BO_XorAssign;
  4891. }
  4892. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  4893. {
  4894. return
  4895. Opc == BinaryOperatorKind::BO_Shl ||
  4896. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4897. Opc == BinaryOperatorKind::BO_Shr ||
  4898. Opc == BinaryOperatorKind::BO_ShrAssign;
  4899. }
  4900. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  4901. {
  4902. return
  4903. Opc == BinaryOperatorKind::BO_EQ ||
  4904. Opc == BinaryOperatorKind::BO_NE;
  4905. }
  4906. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  4907. {
  4908. return
  4909. Opc == BinaryOperatorKind::BO_LT ||
  4910. Opc == BinaryOperatorKind::BO_GT ||
  4911. Opc == BinaryOperatorKind::BO_LE ||
  4912. Opc == BinaryOperatorKind::BO_GE;
  4913. }
  4914. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  4915. {
  4916. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  4917. }
  4918. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  4919. {
  4920. return
  4921. Opc == BinaryOperatorKind::BO_LAnd ||
  4922. Opc == BinaryOperatorKind::BO_LOr;
  4923. }
  4924. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  4925. {
  4926. return
  4927. BinaryOperatorKindIsArithmetic(Opc) ||
  4928. BinaryOperatorKindIsOrderComparison(Opc) ||
  4929. BinaryOperatorKindIsLogical(Opc);
  4930. }
  4931. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  4932. {
  4933. return BinaryOperatorKindIsBitwise(Opc);
  4934. }
  4935. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  4936. {
  4937. return
  4938. BinaryOperatorKindIsBitwise(Opc) ||
  4939. BinaryOperatorKindIsArithmetic(Opc);
  4940. }
  4941. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  4942. {
  4943. return Opc == UnaryOperatorKind::UO_Not;
  4944. }
  4945. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  4946. {
  4947. return
  4948. Opc == UnaryOperatorKind::UO_LNot ||
  4949. Opc == UnaryOperatorKind::UO_Plus ||
  4950. Opc == UnaryOperatorKind::UO_Minus ||
  4951. // The omission in fxc caused objects and structs to accept this.
  4952. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4953. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4954. }
  4955. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  4956. {
  4957. return
  4958. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4959. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4960. }
  4961. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  4962. {
  4963. return
  4964. Opc == UnaryOperatorKind::UO_Not ||
  4965. Opc == UnaryOperatorKind::UO_Plus ||
  4966. Opc == UnaryOperatorKind::UO_Minus;
  4967. }
  4968. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  4969. {
  4970. return
  4971. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4972. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4973. }
  4974. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  4975. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  4976. }
  4977. /// <summary>
  4978. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  4979. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  4980. /// </summary>
  4981. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  4982. {
  4983. return
  4984. value == AR_TOBJ_BASIC ||
  4985. value == AR_TOBJ_MATRIX ||
  4986. value == AR_TOBJ_VECTOR;
  4987. }
  4988. static bool IsBasicKindIntegral(ArBasicKind value)
  4989. {
  4990. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  4991. }
  4992. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  4993. {
  4994. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  4995. }
  4996. static bool IsBasicKindNumeric(ArBasicKind value)
  4997. {
  4998. return GetBasicKindProps(value) & BPROP_NUMERIC;
  4999. }
  5000. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  5001. {
  5002. // An invalid expression is pass-through at this point.
  5003. if (E.isInvalid())
  5004. {
  5005. return E;
  5006. }
  5007. QualType qt = E.get()->getType();
  5008. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  5009. if (elementKind != AR_BASIC_BOOL)
  5010. {
  5011. return E;
  5012. }
  5013. // Construct a scalar/vector/matrix type with the same shape as E.
  5014. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  5015. QualType targetType;
  5016. UINT colCount, rowCount;
  5017. GetRowsAndColsForAny(qt, rowCount, colCount);
  5018. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  5019. if (E.get()->isLValue()) {
  5020. E = m_sema->DefaultLvalueConversion(E.get()).get();
  5021. }
  5022. switch (objectKind)
  5023. {
  5024. case AR_TOBJ_SCALAR:
  5025. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5026. case AR_TOBJ_ARRAY:
  5027. case AR_TOBJ_VECTOR:
  5028. case AR_TOBJ_MATRIX:
  5029. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5030. default:
  5031. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  5032. }
  5033. return E;
  5034. }
  5035. _Use_decl_annotations_
  5036. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  5037. {
  5038. DXASSERT_NOMSG(pTypeInfo != nullptr);
  5039. DXASSERT_NOMSG(!type.isNull());
  5040. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  5041. pTypeInfo->ObjKind = GetTypeElementKind(type);
  5042. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  5043. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  5044. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  5045. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  5046. }
  5047. // Highest possible score (i.e., worst possible score).
  5048. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  5049. // Leave the first two score bits to handle higher-level
  5050. // variations like target type.
  5051. #define SCORE_MIN_SHIFT 2
  5052. // Space out scores to allow up to 128 parameters to
  5053. // vary between score sets spill into each other.
  5054. #define SCORE_PARAM_SHIFT 7
  5055. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  5056. if (anyType.isNull()) {
  5057. return 0;
  5058. }
  5059. anyType = GetStructuralForm(anyType);
  5060. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5061. switch (kind) {
  5062. case AR_TOBJ_BASIC:
  5063. case AR_TOBJ_OBJECT:
  5064. return 1;
  5065. case AR_TOBJ_COMPOUND: {
  5066. // TODO: consider caching this value for perf
  5067. unsigned total = 0;
  5068. const RecordType *recordType = anyType->getAs<RecordType>();
  5069. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5070. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5071. while (fi != fend) {
  5072. total += GetNumElements(fi->getType());
  5073. ++fi;
  5074. }
  5075. return total;
  5076. }
  5077. case AR_TOBJ_ARRAY:
  5078. case AR_TOBJ_MATRIX:
  5079. case AR_TOBJ_VECTOR:
  5080. return GetElementCount(anyType);
  5081. default:
  5082. DXASSERT(kind == AR_TOBJ_VOID,
  5083. "otherwise the type cannot be classified or is not supported");
  5084. return 0;
  5085. }
  5086. }
  5087. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  5088. if (anyType.isNull()) {
  5089. return 0;
  5090. }
  5091. anyType = GetStructuralForm(anyType);
  5092. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5093. switch (kind) {
  5094. case AR_TOBJ_BASIC:
  5095. case AR_TOBJ_OBJECT:
  5096. return 1;
  5097. case AR_TOBJ_COMPOUND: {
  5098. // TODO: consider caching this value for perf
  5099. unsigned total = 0;
  5100. const RecordType *recordType = anyType->getAs<RecordType>();
  5101. RecordDecl * RD = recordType->getDecl();
  5102. // Take care base.
  5103. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5104. if (CXXRD->getNumBases()) {
  5105. for (const auto &I : CXXRD->bases()) {
  5106. const CXXRecordDecl *BaseDecl =
  5107. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5108. if (BaseDecl->field_empty())
  5109. continue;
  5110. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5111. total += GetNumBasicElements(parentTy);
  5112. }
  5113. }
  5114. }
  5115. RecordDecl::field_iterator fi = RD->field_begin();
  5116. RecordDecl::field_iterator fend = RD->field_end();
  5117. while (fi != fend) {
  5118. total += GetNumBasicElements(fi->getType());
  5119. ++fi;
  5120. }
  5121. return total;
  5122. }
  5123. case AR_TOBJ_ARRAY: {
  5124. unsigned arraySize = GetElementCount(anyType);
  5125. unsigned eltSize = GetNumBasicElements(
  5126. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  5127. return arraySize * eltSize;
  5128. }
  5129. case AR_TOBJ_MATRIX:
  5130. case AR_TOBJ_VECTOR:
  5131. return GetElementCount(anyType);
  5132. default:
  5133. DXASSERT(kind == AR_TOBJ_VOID,
  5134. "otherwise the type cannot be classified or is not supported");
  5135. return 0;
  5136. }
  5137. }
  5138. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  5139. unsigned leftSize,
  5140. QualType rightType,
  5141. unsigned rightSize) {
  5142. // We can convert from a larger type to a smaller
  5143. // but not a smaller type to a larger so default
  5144. // to just comparing the destination size.
  5145. unsigned uElts = leftSize;
  5146. leftType = GetStructuralForm(leftType);
  5147. rightType = GetStructuralForm(rightType);
  5148. if (leftType->isArrayType() && rightType->isArrayType()) {
  5149. //
  5150. // If we're comparing arrays we don't
  5151. // need to compare every element of
  5152. // the arrays since all elements
  5153. // will have the same type.
  5154. // We only need to compare enough
  5155. // elements that we've tried every
  5156. // possible mix of dst and src elements.
  5157. //
  5158. // TODO: handle multidimensional arrays and arrays of arrays
  5159. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5160. unsigned uDstEltSize = GetNumElements(pDstElt);
  5161. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5162. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5163. if (uDstEltSize == uSrcEltSize) {
  5164. uElts = uDstEltSize;
  5165. } else if (uDstEltSize > uSrcEltSize) {
  5166. // If one size is not an even multiple of the other we need to let the
  5167. // full compare run in order to try all alignments.
  5168. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5169. uElts = uDstEltSize;
  5170. }
  5171. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5172. uElts = uSrcEltSize;
  5173. }
  5174. }
  5175. return uElts;
  5176. }
  5177. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5178. if (type.isNull()) {
  5179. return type;
  5180. }
  5181. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5182. switch (kind) {
  5183. case AR_TOBJ_BASIC:
  5184. case AR_TOBJ_OBJECT:
  5185. return (index == 0) ? type : QualType();
  5186. case AR_TOBJ_COMPOUND: {
  5187. // TODO: consider caching this value for perf
  5188. const RecordType *recordType = type->getAsStructureType();
  5189. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5190. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5191. while (fi != fend) {
  5192. if (!fi->getType().isNull()) {
  5193. unsigned subElements = GetNumElements(fi->getType());
  5194. if (index < subElements) {
  5195. return GetNthElementType(fi->getType(), index);
  5196. } else {
  5197. index -= subElements;
  5198. }
  5199. }
  5200. ++fi;
  5201. }
  5202. return QualType();
  5203. }
  5204. case AR_TOBJ_ARRAY: {
  5205. unsigned arraySize;
  5206. QualType elementType;
  5207. unsigned elementCount;
  5208. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5209. elementCount = GetElementCount(elementType);
  5210. if (index < elementCount) {
  5211. return GetNthElementType(elementType, index);
  5212. }
  5213. arraySize = GetArraySize(type);
  5214. if (index >= arraySize * elementCount) {
  5215. return QualType();
  5216. }
  5217. return GetNthElementType(elementType, index % elementCount);
  5218. }
  5219. case AR_TOBJ_MATRIX:
  5220. case AR_TOBJ_VECTOR:
  5221. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5222. : QualType();
  5223. default:
  5224. DXASSERT(kind == AR_TOBJ_VOID,
  5225. "otherwise the type cannot be classified or is not supported");
  5226. return QualType();
  5227. }
  5228. }
  5229. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5230. // Eliminate exact matches first, then check for promotions.
  5231. if (leftKind == rightKind) {
  5232. return false;
  5233. }
  5234. switch (rightKind) {
  5235. case AR_BASIC_FLOAT16:
  5236. switch (leftKind) {
  5237. case AR_BASIC_FLOAT32:
  5238. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5239. case AR_BASIC_FLOAT64:
  5240. return true;
  5241. }
  5242. break;
  5243. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5244. switch (leftKind) {
  5245. case AR_BASIC_FLOAT32:
  5246. case AR_BASIC_FLOAT64:
  5247. return true;
  5248. }
  5249. break;
  5250. case AR_BASIC_FLOAT32:
  5251. switch (leftKind) {
  5252. case AR_BASIC_FLOAT64:
  5253. return true;
  5254. }
  5255. break;
  5256. case AR_BASIC_MIN10FLOAT:
  5257. switch (leftKind) {
  5258. case AR_BASIC_MIN16FLOAT:
  5259. case AR_BASIC_FLOAT16:
  5260. case AR_BASIC_FLOAT32:
  5261. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5262. case AR_BASIC_FLOAT64:
  5263. return true;
  5264. }
  5265. break;
  5266. case AR_BASIC_MIN16FLOAT:
  5267. switch (leftKind) {
  5268. case AR_BASIC_FLOAT16:
  5269. case AR_BASIC_FLOAT32:
  5270. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5271. case AR_BASIC_FLOAT64:
  5272. return true;
  5273. }
  5274. break;
  5275. case AR_BASIC_INT8:
  5276. case AR_BASIC_UINT8:
  5277. // For backwards compat we consider signed/unsigned the same.
  5278. switch (leftKind) {
  5279. case AR_BASIC_INT16:
  5280. case AR_BASIC_INT32:
  5281. case AR_BASIC_INT64:
  5282. case AR_BASIC_UINT16:
  5283. case AR_BASIC_UINT32:
  5284. case AR_BASIC_UINT64:
  5285. return true;
  5286. }
  5287. break;
  5288. case AR_BASIC_INT16:
  5289. case AR_BASIC_UINT16:
  5290. // For backwards compat we consider signed/unsigned the same.
  5291. switch (leftKind) {
  5292. case AR_BASIC_INT32:
  5293. case AR_BASIC_INT64:
  5294. case AR_BASIC_UINT32:
  5295. case AR_BASIC_UINT64:
  5296. return true;
  5297. }
  5298. break;
  5299. case AR_BASIC_INT32:
  5300. case AR_BASIC_UINT32:
  5301. // For backwards compat we consider signed/unsigned the same.
  5302. switch (leftKind) {
  5303. case AR_BASIC_INT64:
  5304. case AR_BASIC_UINT64:
  5305. return true;
  5306. }
  5307. break;
  5308. case AR_BASIC_MIN12INT:
  5309. switch (leftKind) {
  5310. case AR_BASIC_MIN16INT:
  5311. case AR_BASIC_INT32:
  5312. case AR_BASIC_INT64:
  5313. return true;
  5314. }
  5315. break;
  5316. case AR_BASIC_MIN16INT:
  5317. switch (leftKind) {
  5318. case AR_BASIC_INT32:
  5319. case AR_BASIC_INT64:
  5320. return true;
  5321. }
  5322. break;
  5323. case AR_BASIC_MIN16UINT:
  5324. switch (leftKind) {
  5325. case AR_BASIC_UINT32:
  5326. case AR_BASIC_UINT64:
  5327. return true;
  5328. }
  5329. break;
  5330. }
  5331. return false;
  5332. }
  5333. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5334. // Eliminate exact matches first, then check for casts.
  5335. if (leftKind == rightKind) {
  5336. return false;
  5337. }
  5338. //
  5339. // All minimum-bits types are only considered matches of themselves
  5340. // and thus are not in this table.
  5341. //
  5342. switch (leftKind) {
  5343. case AR_BASIC_LITERAL_INT:
  5344. switch (rightKind) {
  5345. case AR_BASIC_INT8:
  5346. case AR_BASIC_INT16:
  5347. case AR_BASIC_INT32:
  5348. case AR_BASIC_INT64:
  5349. case AR_BASIC_UINT8:
  5350. case AR_BASIC_UINT16:
  5351. case AR_BASIC_UINT32:
  5352. case AR_BASIC_UINT64:
  5353. return false;
  5354. }
  5355. break;
  5356. case AR_BASIC_INT8:
  5357. switch (rightKind) {
  5358. // For backwards compat we consider signed/unsigned the same.
  5359. case AR_BASIC_LITERAL_INT:
  5360. case AR_BASIC_UINT8:
  5361. return false;
  5362. }
  5363. break;
  5364. case AR_BASIC_INT16:
  5365. switch (rightKind) {
  5366. // For backwards compat we consider signed/unsigned the same.
  5367. case AR_BASIC_LITERAL_INT:
  5368. case AR_BASIC_UINT16:
  5369. return false;
  5370. }
  5371. break;
  5372. case AR_BASIC_INT32:
  5373. switch (rightKind) {
  5374. // For backwards compat we consider signed/unsigned the same.
  5375. case AR_BASIC_LITERAL_INT:
  5376. case AR_BASIC_UINT32:
  5377. return false;
  5378. }
  5379. break;
  5380. case AR_BASIC_INT64:
  5381. switch (rightKind) {
  5382. // For backwards compat we consider signed/unsigned the same.
  5383. case AR_BASIC_LITERAL_INT:
  5384. case AR_BASIC_UINT64:
  5385. return false;
  5386. }
  5387. break;
  5388. case AR_BASIC_UINT8:
  5389. switch (rightKind) {
  5390. // For backwards compat we consider signed/unsigned the same.
  5391. case AR_BASIC_LITERAL_INT:
  5392. case AR_BASIC_INT8:
  5393. return false;
  5394. }
  5395. break;
  5396. case AR_BASIC_UINT16:
  5397. switch (rightKind) {
  5398. // For backwards compat we consider signed/unsigned the same.
  5399. case AR_BASIC_LITERAL_INT:
  5400. case AR_BASIC_INT16:
  5401. return false;
  5402. }
  5403. break;
  5404. case AR_BASIC_UINT32:
  5405. switch (rightKind) {
  5406. // For backwards compat we consider signed/unsigned the same.
  5407. case AR_BASIC_LITERAL_INT:
  5408. case AR_BASIC_INT32:
  5409. return false;
  5410. }
  5411. break;
  5412. case AR_BASIC_UINT64:
  5413. switch (rightKind) {
  5414. // For backwards compat we consider signed/unsigned the same.
  5415. case AR_BASIC_LITERAL_INT:
  5416. case AR_BASIC_INT64:
  5417. return false;
  5418. }
  5419. break;
  5420. case AR_BASIC_LITERAL_FLOAT:
  5421. switch (rightKind) {
  5422. case AR_BASIC_LITERAL_FLOAT:
  5423. case AR_BASIC_FLOAT16:
  5424. case AR_BASIC_FLOAT32:
  5425. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5426. case AR_BASIC_FLOAT64:
  5427. return false;
  5428. }
  5429. break;
  5430. case AR_BASIC_FLOAT16:
  5431. switch (rightKind) {
  5432. case AR_BASIC_LITERAL_FLOAT:
  5433. return false;
  5434. }
  5435. break;
  5436. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5437. switch (rightKind) {
  5438. case AR_BASIC_LITERAL_FLOAT:
  5439. return false;
  5440. }
  5441. break;
  5442. case AR_BASIC_FLOAT32:
  5443. switch (rightKind) {
  5444. case AR_BASIC_LITERAL_FLOAT:
  5445. return false;
  5446. }
  5447. break;
  5448. case AR_BASIC_FLOAT64:
  5449. switch (rightKind) {
  5450. case AR_BASIC_LITERAL_FLOAT:
  5451. return false;
  5452. }
  5453. break;
  5454. }
  5455. return true;
  5456. }
  5457. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5458. // Eliminate exact matches first, then check for casts.
  5459. if (leftKind == rightKind) {
  5460. return false;
  5461. }
  5462. //
  5463. // All minimum-bits types are only considered matches of themselves
  5464. // and thus are not in this table.
  5465. //
  5466. switch (leftKind) {
  5467. case AR_BASIC_LITERAL_INT:
  5468. switch (rightKind) {
  5469. case AR_BASIC_INT8:
  5470. case AR_BASIC_INT16:
  5471. case AR_BASIC_INT32:
  5472. case AR_BASIC_INT64:
  5473. case AR_BASIC_UINT8:
  5474. case AR_BASIC_UINT16:
  5475. case AR_BASIC_UINT32:
  5476. case AR_BASIC_UINT64:
  5477. return false;
  5478. }
  5479. break;
  5480. case AR_BASIC_INT8:
  5481. case AR_BASIC_INT16:
  5482. case AR_BASIC_INT32:
  5483. case AR_BASIC_INT64:
  5484. case AR_BASIC_UINT8:
  5485. case AR_BASIC_UINT16:
  5486. case AR_BASIC_UINT32:
  5487. case AR_BASIC_UINT64:
  5488. switch (rightKind) {
  5489. case AR_BASIC_LITERAL_INT:
  5490. return false;
  5491. }
  5492. break;
  5493. case AR_BASIC_LITERAL_FLOAT:
  5494. switch (rightKind) {
  5495. case AR_BASIC_LITERAL_FLOAT:
  5496. case AR_BASIC_FLOAT16:
  5497. case AR_BASIC_FLOAT32:
  5498. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5499. case AR_BASIC_FLOAT64:
  5500. return false;
  5501. }
  5502. break;
  5503. case AR_BASIC_FLOAT16:
  5504. case AR_BASIC_FLOAT32:
  5505. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5506. case AR_BASIC_FLOAT64:
  5507. switch (rightKind) {
  5508. case AR_BASIC_LITERAL_FLOAT:
  5509. return false;
  5510. }
  5511. break;
  5512. }
  5513. return true;
  5514. }
  5515. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  5516. {
  5517. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  5518. return 0;
  5519. }
  5520. UINT64 uScore = 0;
  5521. UINT uLSize = GetNumElements(pLType);
  5522. UINT uRSize = GetNumElements(pRType);
  5523. UINT uCompareSize;
  5524. bool bLCast = false;
  5525. bool bRCast = false;
  5526. bool bLIntCast = false;
  5527. bool bRIntCast = false;
  5528. bool bLPromo = false;
  5529. bool bRPromo = false;
  5530. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  5531. if (uCompareSize > uRSize) {
  5532. uCompareSize = uRSize;
  5533. }
  5534. for (UINT i = 0; i < uCompareSize; i++) {
  5535. ArBasicKind LeftElementKind, RightElementKind;
  5536. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  5537. QualType leftSub = GetNthElementType(pLType, i);
  5538. QualType rightSub = GetNthElementType(pRType, i);
  5539. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  5540. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  5541. LeftElementKind = GetTypeElementKind(leftSub);
  5542. RightElementKind = GetTypeElementKind(rightSub);
  5543. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  5544. // information needed is the ShapeKind, EltKind and ObjKind.
  5545. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  5546. bool bCombine;
  5547. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  5548. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  5549. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  5550. ArBasicKind RightObjKind = RightElementKind;
  5551. LeftElementKind = LeftObjKind;
  5552. RightElementKind = RightObjKind;
  5553. if (leftKind != rightKind) {
  5554. bCombine = false;
  5555. }
  5556. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  5557. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  5558. }
  5559. }
  5560. else {
  5561. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  5562. }
  5563. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  5564. bLPromo = true;
  5565. }
  5566. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  5567. bLCast = true;
  5568. }
  5569. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  5570. bLIntCast = true;
  5571. }
  5572. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  5573. bRPromo = true;
  5574. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  5575. bRCast = true;
  5576. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  5577. bRIntCast = true;
  5578. }
  5579. } else {
  5580. bLCast = true;
  5581. bRCast = true;
  5582. }
  5583. }
  5584. #define SCORE_COND(shift, cond) { \
  5585. if (cond) uScore += 1UI64 << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  5586. SCORE_COND(0, uRSize < uLSize);
  5587. SCORE_COND(1, bLPromo);
  5588. SCORE_COND(2, bRPromo);
  5589. SCORE_COND(3, bLIntCast);
  5590. SCORE_COND(4, bRIntCast);
  5591. SCORE_COND(5, bLCast);
  5592. SCORE_COND(6, bRCast);
  5593. SCORE_COND(7, uLSize < uRSize);
  5594. #undef SCORE_COND
  5595. // Make sure our scores fit in a UINT64.
  5596. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  5597. return uScore;
  5598. }
  5599. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  5600. DXASSERT(ics, "otherwise conversion has not been initialized");
  5601. if (!ics->isInitialized()) {
  5602. return 0;
  5603. }
  5604. if (!ics->isStandard()) {
  5605. return SCORE_MAX;
  5606. }
  5607. QualType fromType = ics->Standard.getFromType();
  5608. QualType toType = ics->Standard.getToType(2); // final type
  5609. return ScoreCast(toType, fromType);
  5610. }
  5611. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  5612. // Ignore target version mismatches.
  5613. // in/out considerations have been taken care of by viability.
  5614. // 'this' considerations don't matter without inheritance, other
  5615. // than lookup and viability.
  5616. UINT64 result = 0;
  5617. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  5618. UINT64 score;
  5619. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  5620. if (score == SCORE_MAX) {
  5621. return SCORE_MAX;
  5622. }
  5623. result += score;
  5624. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  5625. if (score == SCORE_MAX) {
  5626. return SCORE_MAX;
  5627. }
  5628. result += score;
  5629. }
  5630. return result;
  5631. }
  5632. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  5633. SourceLocation Loc,
  5634. OverloadCandidateSet& set,
  5635. OverloadCandidateSet::iterator& Best)
  5636. {
  5637. UINT64 bestScore = SCORE_MAX;
  5638. unsigned scoreMatch = 0;
  5639. Best = set.end();
  5640. if (set.size() == 1 && set.begin()->Viable) {
  5641. Best = set.begin();
  5642. return OR_Success;
  5643. }
  5644. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  5645. if (Cand->Viable) {
  5646. UINT64 score = ScoreFunction(Cand);
  5647. if (score != SCORE_MAX) {
  5648. if (score == bestScore) {
  5649. ++scoreMatch;
  5650. } else if (score < bestScore) {
  5651. Best = Cand;
  5652. scoreMatch = 1;
  5653. bestScore = score;
  5654. }
  5655. }
  5656. }
  5657. }
  5658. if (Best == set.end()) {
  5659. return OR_No_Viable_Function;
  5660. }
  5661. if (scoreMatch > 1) {
  5662. Best = set.end();
  5663. return OR_Ambiguous;
  5664. }
  5665. // No need to check for deleted functions to yield OR_Deleted.
  5666. return OR_Success;
  5667. }
  5668. /// <summary>
  5669. /// Initializes the specified <paramref name="initSequence" /> describing how
  5670. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  5671. /// </summary>
  5672. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  5673. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  5674. /// <param name="Args">Arguments to the initialization.</param>
  5675. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  5676. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  5677. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  5678. const InitializedEntity& Entity,
  5679. const InitializationKind& Kind,
  5680. MultiExprArg Args,
  5681. bool TopLevelOfInitList,
  5682. _Inout_ InitializationSequence* initSequence)
  5683. {
  5684. DXASSERT_NOMSG(initSequence != nullptr);
  5685. // In HLSL there are no default initializers, eg float4x4 m();
  5686. if (Kind.getKind() == InitializationKind::IK_Default) {
  5687. return;
  5688. }
  5689. // Value initializers occur for temporaries with empty parens or braces.
  5690. if (Kind.getKind() == InitializationKind::IK_Value) {
  5691. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  5692. SilenceSequenceDiagnostics(initSequence);
  5693. return;
  5694. }
  5695. // If we have a DirectList, we should have a single InitListExprClass argument.
  5696. DXASSERT(
  5697. Kind.getKind() != InitializationKind::IK_DirectList ||
  5698. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  5699. "otherwise caller is passing in incorrect initialization configuration");
  5700. bool isCast = Kind.isCStyleCast();
  5701. QualType destType = Entity.getType();
  5702. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  5703. // Direct initialization occurs for explicit constructor arguments.
  5704. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  5705. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  5706. !Kind.isCStyleOrFunctionalCast()) {
  5707. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  5708. SilenceSequenceDiagnostics(initSequence);
  5709. return;
  5710. }
  5711. bool flatten =
  5712. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  5713. Kind.getKind() == InitializationKind::IK_DirectList ||
  5714. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  5715. if (flatten) {
  5716. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  5717. // array types to adjust the value - we do calculate this as part of type analysis.
  5718. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  5719. FlattenedTypeIterator::ComparisonResult comparisonResult =
  5720. FlattenedTypeIterator::CompareTypesForInit(
  5721. *this, destType, Args,
  5722. Kind.getLocation(), Kind.getLocation());
  5723. if (comparisonResult.IsConvertibleAndEqualLength() ||
  5724. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  5725. {
  5726. initSequence->AddListInitializationStep(destType);
  5727. }
  5728. else
  5729. {
  5730. SourceLocation diagLocation;
  5731. if (Args.size() > 0)
  5732. {
  5733. diagLocation = Args.front()->getLocStart();
  5734. }
  5735. else
  5736. {
  5737. diagLocation = Entity.getDiagLoc();
  5738. }
  5739. m_sema->Diag(diagLocation,
  5740. diag::err_vector_incorrect_num_initializers)
  5741. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  5742. << comparisonResult.LeftCount << comparisonResult.RightCount;
  5743. SilenceSequenceDiagnostics(initSequence);
  5744. }
  5745. }
  5746. else {
  5747. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  5748. Expr* firstArg = Args.front();
  5749. if (IsExpressionBinaryComma(firstArg)) {
  5750. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  5751. }
  5752. ExprResult expr = ExprResult(firstArg);
  5753. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  5754. Sema::CheckedConversionKind::CCK_CStyleCast :
  5755. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  5756. unsigned int msg = 0;
  5757. CastKind castKind;
  5758. CXXCastPath basePath;
  5759. SourceRange range = Kind.getRange();
  5760. ImplicitConversionSequence ics;
  5761. ics.setStandard();
  5762. bool castWorked = TryStaticCastForHLSL(
  5763. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  5764. if (castWorked) {
  5765. if (destType.getCanonicalType() ==
  5766. firstArg->getType().getCanonicalType() &&
  5767. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  5768. initSequence->AddCAssignmentStep(destType);
  5769. } else {
  5770. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  5771. }
  5772. }
  5773. else {
  5774. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  5775. }
  5776. }
  5777. }
  5778. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5779. const QualType& sourceType,
  5780. const QualType& targetType,
  5781. bool explicitConversion)
  5782. {
  5783. DXASSERT_NOMSG(!sourceType.isNull());
  5784. DXASSERT_NOMSG(!targetType.isNull());
  5785. ArTypeInfo sourceTypeInfo;
  5786. ArTypeInfo targetTypeInfo;
  5787. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  5788. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  5789. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  5790. {
  5791. return false;
  5792. }
  5793. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  5794. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  5795. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  5796. !isVecMatTrunc)
  5797. {
  5798. return false;
  5799. }
  5800. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  5801. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  5802. return true;
  5803. }
  5804. // Same struct is eqaul.
  5805. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  5806. sourceType.getCanonicalType().getUnqualifiedType() ==
  5807. targetType.getCanonicalType().getUnqualifiedType()) {
  5808. return true;
  5809. }
  5810. // DerivedFrom is less.
  5811. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  5812. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  5813. const RecordType *targetRT = targetType->getAsStructureType();
  5814. if (!targetRT)
  5815. targetRT = dyn_cast<RecordType>(targetType);
  5816. const RecordType *sourceRT = sourceType->getAsStructureType();
  5817. if (!sourceRT)
  5818. sourceRT = dyn_cast<RecordType>(sourceType);
  5819. if (targetRT && sourceRT) {
  5820. RecordDecl *targetRD = targetRT->getDecl();
  5821. RecordDecl *sourceRD = sourceRT->getDecl();
  5822. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  5823. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  5824. if (targetCXXRD && sourceCXXRD) {
  5825. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  5826. return true;
  5827. }
  5828. }
  5829. }
  5830. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  5831. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  5832. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  5833. {
  5834. return false;
  5835. }
  5836. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  5837. }
  5838. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5839. const ExprResult& sourceExpr,
  5840. const QualType& targetType,
  5841. bool explicitConversion)
  5842. {
  5843. if (sourceExpr.isInvalid() || targetType.isNull())
  5844. {
  5845. return false;
  5846. }
  5847. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  5848. }
  5849. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  5850. {
  5851. DXASSERT_NOMSG(!type.isNull());
  5852. DXASSERT_NOMSG(count != nullptr);
  5853. *count = 0;
  5854. UINT subCount = 0;
  5855. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  5856. switch (shapeKind)
  5857. {
  5858. case AR_TOBJ_ARRAY:
  5859. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  5860. {
  5861. *count = subCount * GetArraySize(type);
  5862. return true;
  5863. }
  5864. return false;
  5865. case AR_TOBJ_COMPOUND:
  5866. {
  5867. UINT maxCount = 0;
  5868. { // Determine maximum count to prevent infinite loop on incomplete array
  5869. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  5870. maxCount = itCount.countRemaining();
  5871. if (!maxCount) {
  5872. return false; // empty struct.
  5873. }
  5874. }
  5875. FlattenedTypeIterator it(SourceLocation(), type, *this);
  5876. while (it.hasCurrentElement()) {
  5877. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  5878. if (!isFieldNumeric) {
  5879. return false;
  5880. }
  5881. if (*count >= maxCount) {
  5882. // this element is an incomplete array at the end; iterator will not advance past this element.
  5883. // don't add to *count either, so *count will represent minimum size of the structure.
  5884. break;
  5885. }
  5886. *count += (subCount * it.getCurrentElementSize());
  5887. it.advanceCurrentElement(it.getCurrentElementSize());
  5888. }
  5889. return true;
  5890. }
  5891. default:
  5892. DXASSERT(false, "unreachable");
  5893. case AR_TOBJ_BASIC:
  5894. case AR_TOBJ_MATRIX:
  5895. case AR_TOBJ_VECTOR:
  5896. *count = GetElementCount(type);
  5897. return IsBasicKindNumeric(GetTypeElementKind(type));
  5898. case AR_TOBJ_OBJECT:
  5899. return false;
  5900. }
  5901. }
  5902. enum MatrixMemberAccessError {
  5903. MatrixMemberAccessError_None, // No errors found.
  5904. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  5905. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  5906. MatrixMemberAccessError_Empty, // No members specified.
  5907. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  5908. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  5909. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5910. };
  5911. static
  5912. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  5913. {
  5914. DXASSERT_NOMSG(memberText != nullptr);
  5915. DXASSERT_NOMSG(value != nullptr);
  5916. if ('0' <= *memberText && *memberText <= '9')
  5917. {
  5918. *value = (*memberText) - '0';
  5919. }
  5920. else
  5921. {
  5922. return MatrixMemberAccessError_BadFormat;
  5923. }
  5924. memberText++;
  5925. return MatrixMemberAccessError_None;
  5926. }
  5927. static
  5928. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  5929. {
  5930. DXASSERT_NOMSG(memberText != nullptr);
  5931. DXASSERT_NOMSG(value != nullptr);
  5932. MatrixMemberAccessPositions result;
  5933. bool zeroBasedDecided = false;
  5934. bool zeroBased = false;
  5935. // Set the output value to invalid to allow early exits when errors are found.
  5936. value->IsValid = 0;
  5937. // Assume this is true until proven otherwise.
  5938. result.IsValid = 1;
  5939. result.Count = 0;
  5940. while (*memberText)
  5941. {
  5942. // Check for a leading underscore.
  5943. if (*memberText != '_')
  5944. {
  5945. return MatrixMemberAccessError_BadFormat;
  5946. }
  5947. ++memberText;
  5948. // Check whether we have an 'm' or a digit.
  5949. if (*memberText == 'm')
  5950. {
  5951. if (zeroBasedDecided && !zeroBased)
  5952. {
  5953. return MatrixMemberAccessError_MixingRefs;
  5954. }
  5955. zeroBased = true;
  5956. zeroBasedDecided = true;
  5957. ++memberText;
  5958. }
  5959. else if (!('0' <= *memberText && *memberText <= '9'))
  5960. {
  5961. return MatrixMemberAccessError_BadFormat;
  5962. }
  5963. else
  5964. {
  5965. if (zeroBasedDecided && zeroBased)
  5966. {
  5967. return MatrixMemberAccessError_MixingRefs;
  5968. }
  5969. zeroBased = false;
  5970. zeroBasedDecided = true;
  5971. }
  5972. // Consume two digits for the position.
  5973. uint32_t rowPosition;
  5974. uint32_t colPosition;
  5975. MatrixMemberAccessError digitError;
  5976. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  5977. {
  5978. return digitError;
  5979. }
  5980. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  5981. {
  5982. return digitError;
  5983. }
  5984. // Look for specific common errors (developer likely mixed up reference style).
  5985. if (zeroBased)
  5986. {
  5987. if (rowPosition == 4 || colPosition == 4)
  5988. {
  5989. return MatrixMemberAccessError_FourInZeroBased;
  5990. }
  5991. }
  5992. else
  5993. {
  5994. if (rowPosition == 0 || colPosition == 0)
  5995. {
  5996. return MatrixMemberAccessError_ZeroInOneBased;
  5997. }
  5998. // SetPosition will use zero-based indices.
  5999. --rowPosition;
  6000. --colPosition;
  6001. }
  6002. if (result.Count == 4)
  6003. {
  6004. return MatrixMemberAccessError_TooManyPositions;
  6005. }
  6006. result.SetPosition(result.Count, rowPosition, colPosition);
  6007. result.Count++;
  6008. }
  6009. if (result.Count == 0)
  6010. {
  6011. return MatrixMemberAccessError_Empty;
  6012. }
  6013. *value = result;
  6014. return MatrixMemberAccessError_None;
  6015. }
  6016. bool HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  6017. Expr& BaseExpr,
  6018. DeclarationName MemberName,
  6019. bool IsArrow,
  6020. SourceLocation OpLoc,
  6021. SourceLocation MemberLoc,
  6022. ExprResult* result)
  6023. {
  6024. DXASSERT_NOMSG(result != nullptr);
  6025. QualType BaseType = BaseExpr.getType();
  6026. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6027. // Assume failure.
  6028. *result = ExprError();
  6029. if (GetTypeObjectKind(BaseType) != AR_TOBJ_MATRIX)
  6030. {
  6031. return false;
  6032. }
  6033. QualType elementType;
  6034. UINT rowCount, colCount;
  6035. GetRowsAndCols(BaseType, rowCount, colCount);
  6036. elementType = GetMatrixOrVectorElementType(BaseType);
  6037. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6038. const char *memberText = member->getNameStart();
  6039. MatrixMemberAccessPositions positions;
  6040. MatrixMemberAccessError memberAccessError;
  6041. unsigned msg = 0;
  6042. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  6043. switch (memberAccessError)
  6044. {
  6045. case MatrixMemberAccessError_BadFormat:
  6046. msg = diag::err_hlsl_matrix_member_bad_format;
  6047. break;
  6048. case MatrixMemberAccessError_Empty:
  6049. msg = diag::err_hlsl_matrix_member_empty;
  6050. break;
  6051. case MatrixMemberAccessError_FourInZeroBased:
  6052. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  6053. break;
  6054. case MatrixMemberAccessError_MixingRefs:
  6055. msg = diag::err_hlsl_matrix_member_mixing_refs;
  6056. break;
  6057. case MatrixMemberAccessError_None:
  6058. msg = 0;
  6059. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6060. // Check the position with the type now.
  6061. for (unsigned int i = 0; i < positions.Count; i++)
  6062. {
  6063. uint32_t rowPos, colPos;
  6064. positions.GetPosition(i, &rowPos, &colPos);
  6065. if (rowPos >= rowCount || colPos >= colCount)
  6066. {
  6067. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  6068. break;
  6069. }
  6070. }
  6071. break;
  6072. case MatrixMemberAccessError_TooManyPositions:
  6073. msg = diag::err_hlsl_matrix_member_too_many_positions;
  6074. break;
  6075. case MatrixMemberAccessError_ZeroInOneBased:
  6076. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  6077. break;
  6078. default:
  6079. llvm_unreachable("Unknown MatrixMemberAccessError value");
  6080. }
  6081. if (msg != 0)
  6082. {
  6083. m_sema->Diag(MemberLoc, msg) << memberText;
  6084. // It's possible that it's a simple out-of-bounds condition. In this case,
  6085. // generate the member access expression with the correct arity and continue
  6086. // processing.
  6087. if (!positions.IsValid)
  6088. {
  6089. return true;
  6090. }
  6091. }
  6092. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6093. // Consume elements
  6094. QualType resultType;
  6095. if (positions.Count == 1)
  6096. resultType = elementType;
  6097. else
  6098. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6099. // Add qualifiers from BaseType.
  6100. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6101. ExprValueKind VK =
  6102. positions.ContainsDuplicateElements() ? VK_RValue :
  6103. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6104. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6105. *result = matrixExpr;
  6106. return true;
  6107. }
  6108. enum VectorMemberAccessError {
  6109. VectorMemberAccessError_None, // No errors found.
  6110. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  6111. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  6112. VectorMemberAccessError_Empty, // No members specified.
  6113. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6114. };
  6115. static
  6116. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  6117. DXASSERT_NOMSG(memberText != nullptr);
  6118. DXASSERT_NOMSG(value != nullptr);
  6119. rgbaStyle = false;
  6120. switch (*memberText) {
  6121. case 'r':
  6122. rgbaStyle = true;
  6123. case 'x':
  6124. *value = 0;
  6125. break;
  6126. case 'g':
  6127. rgbaStyle = true;
  6128. case 'y':
  6129. *value = 1;
  6130. break;
  6131. case 'b':
  6132. rgbaStyle = true;
  6133. case 'z':
  6134. *value = 2;
  6135. break;
  6136. case 'a':
  6137. rgbaStyle = true;
  6138. case 'w':
  6139. *value = 3;
  6140. break;
  6141. default:
  6142. return VectorMemberAccessError_BadFormat;
  6143. }
  6144. memberText++;
  6145. return VectorMemberAccessError_None;
  6146. }
  6147. static
  6148. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  6149. DXASSERT_NOMSG(memberText != nullptr);
  6150. DXASSERT_NOMSG(value != nullptr);
  6151. VectorMemberAccessPositions result;
  6152. bool rgbaStyleDecided = false;
  6153. bool rgbaStyle = false;
  6154. // Set the output value to invalid to allow early exits when errors are found.
  6155. value->IsValid = 0;
  6156. // Assume this is true until proven otherwise.
  6157. result.IsValid = 1;
  6158. result.Count = 0;
  6159. while (*memberText) {
  6160. // Consume one character for the swizzle.
  6161. uint32_t colPosition;
  6162. VectorMemberAccessError digitError;
  6163. bool rgbaStyleTmp = false;
  6164. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6165. return digitError;
  6166. }
  6167. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6168. return VectorMemberAccessError_MixingStyles;
  6169. }
  6170. else {
  6171. rgbaStyleDecided = true;
  6172. rgbaStyle = rgbaStyleTmp;
  6173. }
  6174. if (result.Count == 4) {
  6175. return VectorMemberAccessError_TooManyPositions;
  6176. }
  6177. result.SetPosition(result.Count, colPosition);
  6178. result.Count++;
  6179. }
  6180. if (result.Count == 0) {
  6181. return VectorMemberAccessError_Empty;
  6182. }
  6183. *value = result;
  6184. return VectorMemberAccessError_None;
  6185. }
  6186. bool HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6187. Expr& BaseExpr,
  6188. DeclarationName MemberName,
  6189. bool IsArrow,
  6190. SourceLocation OpLoc,
  6191. SourceLocation MemberLoc,
  6192. ExprResult* result) {
  6193. DXASSERT_NOMSG(result != nullptr);
  6194. QualType BaseType = BaseExpr.getType();
  6195. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6196. // Assume failure.
  6197. *result = ExprError();
  6198. if (GetTypeObjectKind(BaseType) != AR_TOBJ_VECTOR) {
  6199. return false;
  6200. }
  6201. QualType elementType;
  6202. UINT colCount = GetHLSLVecSize(BaseType);
  6203. elementType = GetMatrixOrVectorElementType(BaseType);
  6204. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6205. const char *memberText = member->getNameStart();
  6206. VectorMemberAccessPositions positions;
  6207. VectorMemberAccessError memberAccessError;
  6208. unsigned msg = 0;
  6209. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6210. switch (memberAccessError) {
  6211. case VectorMemberAccessError_BadFormat:
  6212. msg = diag::err_hlsl_vector_member_bad_format;
  6213. break;
  6214. case VectorMemberAccessError_Empty:
  6215. msg = diag::err_hlsl_vector_member_empty;
  6216. break;
  6217. case VectorMemberAccessError_MixingStyles:
  6218. msg = diag::err_ext_vector_component_name_mixedsets;
  6219. break;
  6220. case VectorMemberAccessError_None:
  6221. msg = 0;
  6222. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6223. // Check the position with the type now.
  6224. for (unsigned int i = 0; i < positions.Count; i++) {
  6225. uint32_t colPos;
  6226. positions.GetPosition(i, &colPos);
  6227. if (colPos >= colCount) {
  6228. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6229. break;
  6230. }
  6231. }
  6232. break;
  6233. case VectorMemberAccessError_TooManyPositions:
  6234. msg = diag::err_hlsl_vector_member_too_many_positions;
  6235. break;
  6236. default:
  6237. llvm_unreachable("Unknown VectorMemberAccessError value");
  6238. }
  6239. if (msg != 0) {
  6240. m_sema->Diag(MemberLoc, msg) << memberText;
  6241. // It's possible that it's a simple out-of-bounds condition. In this case,
  6242. // generate the member access expression with the correct arity and continue
  6243. // processing.
  6244. if (!positions.IsValid) {
  6245. return true;
  6246. }
  6247. }
  6248. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6249. // Consume elements
  6250. QualType resultType;
  6251. if (positions.Count == 1)
  6252. resultType = elementType;
  6253. else
  6254. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6255. // Add qualifiers from BaseType.
  6256. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6257. ExprValueKind VK =
  6258. positions.ContainsDuplicateElements() ? VK_RValue :
  6259. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6260. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6261. *result = vectorExpr;
  6262. return true;
  6263. }
  6264. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  6265. DXASSERT_NOMSG(E != nullptr);
  6266. ArBasicKind basic = GetTypeElementKind(E->getType());
  6267. if (!IS_BASIC_PRIMITIVE(basic)) {
  6268. return E;
  6269. }
  6270. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  6271. if (kind != AR_TOBJ_SCALAR) {
  6272. return E;
  6273. }
  6274. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  6275. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  6276. }
  6277. static clang::CastKind ImplicitConversionKindToCastKind(
  6278. clang::ImplicitConversionKind ICK,
  6279. ArBasicKind FromKind,
  6280. ArBasicKind ToKind) {
  6281. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  6282. // based on from/to kinds in order to determine CastKind?
  6283. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  6284. // problem.
  6285. switch (ICK) {
  6286. case ICK_Integral_Promotion:
  6287. case ICK_Integral_Conversion:
  6288. return CK_IntegralCast;
  6289. case ICK_Floating_Promotion:
  6290. case ICK_Floating_Conversion:
  6291. return CK_FloatingCast;
  6292. case ICK_Floating_Integral:
  6293. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  6294. return CK_FloatingToIntegral;
  6295. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  6296. return CK_IntegralToFloating;
  6297. break;
  6298. case ICK_Boolean_Conversion:
  6299. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  6300. return CK_FloatingToBoolean;
  6301. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  6302. return CK_IntegralToBoolean;
  6303. break;
  6304. }
  6305. return CK_Invalid;
  6306. }
  6307. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  6308. switch (CK) {
  6309. case CK_IntegralCast:
  6310. return CK_HLSLCC_IntegralCast;
  6311. case CK_FloatingCast:
  6312. return CK_HLSLCC_FloatingCast;
  6313. case CK_FloatingToIntegral:
  6314. return CK_HLSLCC_FloatingToIntegral;
  6315. case CK_IntegralToFloating:
  6316. return CK_HLSLCC_IntegralToFloating;
  6317. case CK_FloatingToBoolean:
  6318. return CK_HLSLCC_FloatingToBoolean;
  6319. case CK_IntegralToBoolean:
  6320. return CK_HLSLCC_IntegralToBoolean;
  6321. }
  6322. return CK_Invalid;
  6323. }
  6324. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  6325. _In_ clang::Sema* self,
  6326. _In_ clang::Expr* From,
  6327. ArTypeObjectKind FromShape,
  6328. ArBasicKind EltKind)
  6329. {
  6330. clang::CastKind CK = CK_Invalid;
  6331. if (AR_TOBJ_MATRIX == FromShape)
  6332. CK = CK_HLSLMatrixToScalarCast;
  6333. if (AR_TOBJ_VECTOR == FromShape)
  6334. CK = CK_HLSLVectorToScalarCast;
  6335. if (CK_Invalid != CK) {
  6336. return self->ImpCastExprToType(From,
  6337. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  6338. }
  6339. return From;
  6340. }
  6341. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  6342. _In_ clang::Expr* From,
  6343. _In_ clang::QualType targetType,
  6344. _In_ const clang::StandardConversionSequence &SCS,
  6345. _In_ clang::Sema::CheckedConversionKind CCK)
  6346. {
  6347. QualType sourceType = From->getType();
  6348. sourceType = GetStructuralForm(sourceType);
  6349. targetType = GetStructuralForm(targetType);
  6350. ArTypeInfo SourceInfo, TargetInfo;
  6351. CollectInfo(sourceType, &SourceInfo);
  6352. CollectInfo(targetType, &TargetInfo);
  6353. clang::CastKind CK = CK_Invalid;
  6354. QualType intermediateTarget;
  6355. // TODO: construct vector/matrix and component cast expressions
  6356. switch (SCS.Second) {
  6357. case ICK_Flat_Conversion: {
  6358. // TODO: determine how to handle individual component conversions:
  6359. // - have an array of conversions for ComponentConversion in SCS?
  6360. // convert that to an array of casts under a special kind of flat
  6361. // flat conversion node? What do component conversion casts cast
  6362. // from? We don't have a From expression for individiual components.
  6363. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6364. break;
  6365. }
  6366. case ICK_HLSL_Derived_To_Base: {
  6367. CXXCastPath BasePath;
  6368. if (m_sema->CheckDerivedToBaseConversion(
  6369. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  6370. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  6371. return ExprError();
  6372. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  6373. break;
  6374. }
  6375. case ICK_HLSLVector_Splat: {
  6376. // 1. optionally convert from vec1 or mat1x1 to scalar
  6377. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6378. // 2. optionally convert component type
  6379. if (ICK_Identity != SCS.ComponentConversion) {
  6380. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6381. if (CK_Invalid != CK) {
  6382. From = m_sema->ImpCastExprToType(From,
  6383. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6384. }
  6385. }
  6386. // 3. splat scalar to final vector or matrix
  6387. CK = CK_Invalid;
  6388. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  6389. CK = CK_HLSLVectorSplat;
  6390. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  6391. CK = CK_HLSLMatrixSplat;
  6392. if (CK_Invalid != CK) {
  6393. From = m_sema->ImpCastExprToType(From,
  6394. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6395. }
  6396. break;
  6397. }
  6398. case ICK_HLSLVector_Scalar: {
  6399. // 1. select vector or matrix component
  6400. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6401. // 2. optionally convert component type
  6402. if (ICK_Identity != SCS.ComponentConversion) {
  6403. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6404. if (CK_Invalid != CK) {
  6405. From = m_sema->ImpCastExprToType(From,
  6406. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6407. }
  6408. }
  6409. break;
  6410. }
  6411. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  6412. // can be done with case fall-through, since this is the order in which we want to
  6413. // do the conversion operations.
  6414. case ICK_HLSLVector_Truncation: {
  6415. // 1. dimension truncation
  6416. // vector truncation or matrix truncation?
  6417. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  6418. From = m_sema->ImpCastExprToType(From,
  6419. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  6420. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6421. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  6422. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  6423. // Handle the column to vector case
  6424. From = m_sema->ImpCastExprToType(From,
  6425. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  6426. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6427. } else {
  6428. From = m_sema->ImpCastExprToType(From,
  6429. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6430. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6431. }
  6432. } else {
  6433. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  6434. }
  6435. }
  6436. __fallthrough;
  6437. case ICK_HLSLVector_Conversion: {
  6438. // 2. Do ShapeKind conversion if necessary
  6439. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  6440. switch (TargetInfo.ShapeKind) {
  6441. case AR_TOBJ_VECTOR:
  6442. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6443. From = m_sema->ImpCastExprToType(From,
  6444. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6445. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6446. break;
  6447. case AR_TOBJ_MATRIX:
  6448. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6449. From = m_sema->ImpCastExprToType(From,
  6450. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6451. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6452. break;
  6453. case AR_TOBJ_BASIC:
  6454. // Truncation may be followed by cast to scalar
  6455. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6456. break;
  6457. default:
  6458. DXASSERT(false, "otherwise, invalid casting sequence");
  6459. break;
  6460. }
  6461. }
  6462. // 3. Do component type conversion
  6463. if (ICK_Identity != SCS.ComponentConversion) {
  6464. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6465. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  6466. CK = ConvertToComponentCastKind(CK);
  6467. if (CK_Invalid != CK) {
  6468. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6469. }
  6470. }
  6471. break;
  6472. }
  6473. case ICK_Identity:
  6474. // Nothing to do.
  6475. break;
  6476. default:
  6477. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  6478. }
  6479. return From;
  6480. }
  6481. void HLSLExternalSource::GetConversionForm(
  6482. QualType type,
  6483. bool explicitConversion,
  6484. ArTypeInfo* pTypeInfo)
  6485. {
  6486. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  6487. CollectInfo(type, pTypeInfo);
  6488. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  6489. // but that value is only used for pointer conversions.
  6490. // When explicitly converting types complex aggregates can be treated
  6491. // as vectors if they are entirely numeric.
  6492. switch (pTypeInfo->ShapeKind)
  6493. {
  6494. case AR_TOBJ_COMPOUND:
  6495. case AR_TOBJ_ARRAY:
  6496. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  6497. {
  6498. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  6499. }
  6500. else
  6501. {
  6502. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  6503. }
  6504. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  6505. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  6506. break;
  6507. case AR_TOBJ_VECTOR:
  6508. case AR_TOBJ_MATRIX:
  6509. // Convert 1x1 types to scalars.
  6510. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  6511. {
  6512. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  6513. }
  6514. break;
  6515. }
  6516. }
  6517. static
  6518. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  6519. {
  6520. DXASSERT_NOMSG(allowed != nullptr);
  6521. bool applicable = true;
  6522. *allowed = true;
  6523. if (explicitConversion) {
  6524. // (void) non-void
  6525. if (target->isVoidType()) {
  6526. DXASSERT_NOMSG(*allowed);
  6527. }
  6528. // (non-void) void
  6529. else if (source->isVoidType()) {
  6530. *allowed = false;
  6531. }
  6532. else {
  6533. applicable = false;
  6534. }
  6535. }
  6536. else {
  6537. // (void) void
  6538. if (source->isVoidType() && target->isVoidType()) {
  6539. DXASSERT_NOMSG(*allowed);
  6540. }
  6541. // (void) non-void, (non-void) void
  6542. else if (source->isVoidType() || target->isVoidType()) {
  6543. *allowed = false;
  6544. }
  6545. else {
  6546. applicable = false;
  6547. }
  6548. }
  6549. return applicable;
  6550. }
  6551. _Use_decl_annotations_
  6552. bool HLSLExternalSource::CanConvert(
  6553. SourceLocation loc,
  6554. Expr* sourceExpr,
  6555. QualType target,
  6556. bool explicitConversion,
  6557. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  6558. _Inout_opt_ StandardConversionSequence* standard)
  6559. {
  6560. DXASSERT_NOMSG(sourceExpr != nullptr);
  6561. DXASSERT_NOMSG(!target.isNull());
  6562. // Implements the semantics of ArType::CanConvertTo.
  6563. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  6564. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  6565. QualType source = sourceExpr->getType();
  6566. // Cannot cast function type.
  6567. if (source->isFunctionType())
  6568. return false;
  6569. // Convert to an r-value to begin with.
  6570. bool needsLValueToRValue = sourceExpr->isLValue() &&
  6571. !target->isLValueReferenceType() &&
  6572. IsConversionToLessOrEqualElements(source, target, explicitConversion);
  6573. bool targetRef = target->isReferenceType();
  6574. // Initialize the output standard sequence if available.
  6575. if (standard != nullptr) {
  6576. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  6577. standard->setAsIdentityConversion();
  6578. if (needsLValueToRValue) {
  6579. standard->First = ICK_Lvalue_To_Rvalue;
  6580. }
  6581. standard->setFromType(source);
  6582. standard->setAllToTypes(target);
  6583. }
  6584. source = GetStructuralForm(source);
  6585. target = GetStructuralForm(target);
  6586. // Temporary conversion kind tracking which will be used/fixed up at the end
  6587. ImplicitConversionKind Second = ICK_Identity;
  6588. ImplicitConversionKind ComponentConversion = ICK_Identity;
  6589. // Identical types require no conversion.
  6590. if (source == target) {
  6591. Remarks = TYPE_CONVERSION_IDENTICAL;
  6592. goto lSuccess;
  6593. }
  6594. // Trivial cases for void.
  6595. bool allowed;
  6596. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  6597. if (allowed) {
  6598. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  6599. goto lSuccess;
  6600. }
  6601. else {
  6602. return false;
  6603. }
  6604. }
  6605. ArTypeInfo TargetInfo, SourceInfo;
  6606. CollectInfo(target, &TargetInfo);
  6607. CollectInfo(source, &SourceInfo);
  6608. UINT uTSize = TargetInfo.uTotalElts;
  6609. UINT uSSize = SourceInfo.uTotalElts;
  6610. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  6611. // are we missing cases?
  6612. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  6613. return false;
  6614. }
  6615. // Structure cast.
  6616. if (TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY ||
  6617. SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY) {
  6618. if (!explicitConversion && TargetInfo.ShapeKind != SourceInfo.ShapeKind)
  6619. {
  6620. return false;
  6621. }
  6622. const RecordType *targetRT = target->getAsStructureType();
  6623. if (!targetRT)
  6624. targetRT = dyn_cast<RecordType>(target);
  6625. const RecordType *sourceRT = source->getAsStructureType();
  6626. if (!sourceRT)
  6627. sourceRT = dyn_cast<RecordType>(source);
  6628. if (targetRT && sourceRT) {
  6629. RecordDecl *targetRD = targetRT->getDecl();
  6630. RecordDecl *sourceRD = sourceRT->getDecl();
  6631. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6632. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6633. if (targetCXXRD && sourceCXXRD) {
  6634. if (targetRD == sourceRD) {
  6635. Second = ICK_Flat_Conversion;
  6636. goto lSuccess;
  6637. }
  6638. if (sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  6639. Second = ICK_HLSL_Derived_To_Base;
  6640. goto lSuccess;
  6641. }
  6642. } else {
  6643. if (targetRD == sourceRD) {
  6644. Second = ICK_Flat_Conversion;
  6645. goto lSuccess;
  6646. }
  6647. }
  6648. }
  6649. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6650. BuiltinType::Kind kind = BT->getKind();
  6651. switch (kind) {
  6652. case BuiltinType::Kind::UInt:
  6653. case BuiltinType::Kind::Int:
  6654. case BuiltinType::Kind::Float:
  6655. case BuiltinType::Kind::LitFloat:
  6656. case BuiltinType::Kind::LitInt:
  6657. if (explicitConversion) {
  6658. Second = ICK_Flat_Conversion;
  6659. goto lSuccess;
  6660. }
  6661. break;
  6662. }
  6663. }
  6664. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6665. BuiltinType::Kind kind = BT->getKind();
  6666. switch (kind) {
  6667. case BuiltinType::Kind::UInt:
  6668. case BuiltinType::Kind::Int:
  6669. case BuiltinType::Kind::Float:
  6670. case BuiltinType::Kind::LitFloat:
  6671. case BuiltinType::Kind::LitInt:
  6672. if (explicitConversion) {
  6673. Second = ICK_Flat_Conversion;
  6674. goto lSuccess;
  6675. }
  6676. break;
  6677. }
  6678. }
  6679. FlattenedTypeIterator::ComparisonResult result =
  6680. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  6681. if (!result.CanConvertElements) {
  6682. return false;
  6683. }
  6684. // Only allow scalar to compound or array with explicit cast
  6685. if (result.IsConvertibleAndLeftLonger()) {
  6686. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  6687. return false;
  6688. }
  6689. }
  6690. // Assignment is valid if elements are exactly the same in type and size; if
  6691. // an explicit conversion is being done, we accept converted elements and a
  6692. // longer right-hand sequence.
  6693. if (!explicitConversion &&
  6694. (!result.AreElementsEqual || result.IsRightLonger()))
  6695. {
  6696. return false;
  6697. }
  6698. Second = ICK_Flat_Conversion;
  6699. goto lSuccess;
  6700. }
  6701. // Base type cast.
  6702. //
  6703. // The rules for aggregate conversions are:
  6704. // 1. A scalar can be replicated to any layout.
  6705. // 2. The result of two vectors is the smaller vector.
  6706. // 3. The result of two matrices is the smaller matrix.
  6707. // 4. The result of a vector and a matrix is:
  6708. // a. If the matrix has one row it's a vector-sized
  6709. // piece of the row.
  6710. // b. If the matrix has one column it's a vector-sized
  6711. // piece of the column.
  6712. // c. Otherwise the number of elements in the vector
  6713. // and matrix must match and the result is the vector.
  6714. // 5. The result of a matrix and a vector is similar to #4.
  6715. //
  6716. bool bCheckElt = false;
  6717. switch (TargetInfo.ShapeKind) {
  6718. case AR_TOBJ_BASIC:
  6719. switch (SourceInfo.ShapeKind)
  6720. {
  6721. case AR_TOBJ_BASIC:
  6722. Second = ICK_Identity;
  6723. break;
  6724. case AR_TOBJ_VECTOR:
  6725. if(1 < SourceInfo.uCols)
  6726. Second = ICK_HLSLVector_Truncation;
  6727. else
  6728. Second = ICK_HLSLVector_Scalar;
  6729. break;
  6730. case AR_TOBJ_MATRIX:
  6731. if(1 < SourceInfo.uRows * SourceInfo.uCols)
  6732. Second = ICK_HLSLVector_Truncation;
  6733. else
  6734. Second = ICK_HLSLVector_Scalar;
  6735. break;
  6736. case AR_TOBJ_OBJECT:
  6737. case AR_TOBJ_INTERFACE:
  6738. case AR_TOBJ_POINTER:
  6739. return false;
  6740. }
  6741. bCheckElt = true;
  6742. break;
  6743. case AR_TOBJ_VECTOR:
  6744. switch (SourceInfo.ShapeKind)
  6745. {
  6746. case AR_TOBJ_BASIC:
  6747. // Conversions between scalars and aggregates are always supported.
  6748. Second = ICK_HLSLVector_Splat;
  6749. break;
  6750. case AR_TOBJ_VECTOR:
  6751. if (TargetInfo.uCols > SourceInfo.uCols) {
  6752. if (SourceInfo.uCols == 1) {
  6753. Second = ICK_HLSLVector_Splat;
  6754. } else {
  6755. return false;
  6756. }
  6757. } else if (TargetInfo.uCols < SourceInfo.uCols) {
  6758. Second = ICK_HLSLVector_Truncation;
  6759. } else {
  6760. Second = ICK_Identity;
  6761. }
  6762. break;
  6763. case AR_TOBJ_MATRIX: {
  6764. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6765. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  6766. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  6767. Second = ICK_HLSLVector_Splat;
  6768. } else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  6769. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  6770. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  6771. return false;
  6772. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  6773. Second = ICK_HLSLVector_Truncation;
  6774. else // equalivalent: O == N*M
  6775. Second = ICK_HLSLVector_Conversion;
  6776. } else if (TargetInfo.uCols != SourceComponents) {
  6777. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  6778. return false;
  6779. } else {
  6780. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  6781. Second = ICK_HLSLVector_Conversion;
  6782. }
  6783. break;
  6784. }
  6785. case AR_TOBJ_OBJECT:
  6786. case AR_TOBJ_INTERFACE:
  6787. case AR_TOBJ_POINTER:
  6788. return false;
  6789. }
  6790. bCheckElt = true;
  6791. break;
  6792. case AR_TOBJ_MATRIX: {
  6793. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  6794. switch (SourceInfo.ShapeKind)
  6795. {
  6796. case AR_TOBJ_BASIC:
  6797. // Conversions between scalars and aggregates are always supported.
  6798. Second = ICK_HLSLVector_Splat;
  6799. break;
  6800. case AR_TOBJ_VECTOR: {
  6801. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  6802. // splat: vector<[..], 1> -> matrix<[..], M, N>
  6803. Second = ICK_HLSLVector_Splat;
  6804. } else if (1 == TargetInfo.uRows || 1 == TargetInfo.uCols) {
  6805. // cases for: vector<[..], O> -> matrix<[..], N, M>, where N == 1 or M == 1
  6806. if (TargetComponents > SourceInfo.uCols) // illegal: N*M > O
  6807. return false;
  6808. else if (TargetComponents < SourceInfo.uCols) // truncation: N*M < O
  6809. Second = ICK_HLSLVector_Truncation;
  6810. else // equalivalent: N*M == O
  6811. Second = ICK_HLSLVector_Conversion;
  6812. } else if (TargetComponents != SourceInfo.uCols) {
  6813. // illegal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O != N*M
  6814. return false;
  6815. } else {
  6816. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  6817. Second = ICK_HLSLVector_Conversion;
  6818. }
  6819. break;
  6820. }
  6821. case AR_TOBJ_MATRIX: {
  6822. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6823. if (1 == SourceComponents && TargetComponents != 1) {
  6824. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  6825. Second = ICK_HLSLVector_Splat;
  6826. } else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  6827. return false;
  6828. } else if(TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  6829. Second = ICK_HLSLVector_Truncation;
  6830. } else {
  6831. Second = ICK_Identity;
  6832. }
  6833. break;
  6834. }
  6835. case AR_TOBJ_OBJECT:
  6836. case AR_TOBJ_INTERFACE:
  6837. case AR_TOBJ_POINTER:
  6838. return false;
  6839. }
  6840. bCheckElt = true;
  6841. break;
  6842. }
  6843. case AR_TOBJ_OBJECT:
  6844. // There are no compatible object assignments that aren't
  6845. // from one type to itself, which is already covered.
  6846. DXASSERT(source != target, "otherwise trivial case was not checked by this function");
  6847. return false;
  6848. default:
  6849. DXASSERT_NOMSG(false);
  6850. return false;
  6851. }
  6852. if (bCheckElt)
  6853. {
  6854. bool precisionLoss = false;
  6855. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  6856. GET_BASIC_BITS(TargetInfo.EltKind) <
  6857. GET_BASIC_BITS(SourceInfo.EltKind))
  6858. {
  6859. precisionLoss = true;
  6860. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  6861. }
  6862. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  6863. {
  6864. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  6865. }
  6866. // enum -> enum not allowed
  6867. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  6868. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  6869. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  6870. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  6871. return false;
  6872. }
  6873. if (SourceInfo.EltKind != TargetInfo.EltKind)
  6874. {
  6875. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  6876. SourceInfo.EltKind == AR_BASIC_UNKNOWN)
  6877. {
  6878. Second = ICK_Flat_Conversion;
  6879. }
  6880. else if (IS_BASIC_BOOL(TargetInfo.EltKind))
  6881. {
  6882. ComponentConversion = ICK_Boolean_Conversion;
  6883. }
  6884. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  6885. {
  6886. // conversion to enum type not allowed
  6887. return false;
  6888. }
  6889. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  6890. {
  6891. // enum -> int/float
  6892. ComponentConversion = ICK_Integral_Conversion;
  6893. }
  6894. else
  6895. {
  6896. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  6897. if (IS_BASIC_AINT(SourceInfo.EltKind))
  6898. {
  6899. if (targetIsInt)
  6900. {
  6901. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  6902. }
  6903. else
  6904. {
  6905. ComponentConversion = ICK_Floating_Integral;
  6906. }
  6907. }
  6908. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  6909. {
  6910. DXASSERT(IS_BASIC_FLOAT(SourceInfo.EltKind), "otherwise should not be checking element types");
  6911. if (targetIsInt)
  6912. {
  6913. ComponentConversion = ICK_Floating_Integral;
  6914. }
  6915. else
  6916. {
  6917. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  6918. }
  6919. } else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  6920. if (targetIsInt)
  6921. ComponentConversion = ICK_Integral_Conversion;
  6922. else
  6923. ComponentConversion = ICK_Floating_Integral;
  6924. }
  6925. }
  6926. }
  6927. }
  6928. lSuccess:
  6929. if (standard)
  6930. {
  6931. if (sourceExpr->isLValue())
  6932. {
  6933. if (needsLValueToRValue) {
  6934. // We don't need LValueToRValue cast before casting a derived object
  6935. // to its base.
  6936. if (Second == ICK_HLSL_Derived_To_Base) {
  6937. standard->First = ICK_Identity;
  6938. } else {
  6939. standard->First = ICK_Lvalue_To_Rvalue;
  6940. }
  6941. } else {
  6942. switch (Second)
  6943. {
  6944. case ICK_NoReturn_Adjustment:
  6945. case ICK_Vector_Conversion:
  6946. case ICK_Vector_Splat:
  6947. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  6948. case ICK_Flat_Conversion:
  6949. case ICK_HLSLVector_Splat:
  6950. standard->First = ICK_Lvalue_To_Rvalue;
  6951. break;
  6952. }
  6953. switch (ComponentConversion)
  6954. {
  6955. case ICK_Integral_Promotion:
  6956. case ICK_Integral_Conversion:
  6957. case ICK_Floating_Promotion:
  6958. case ICK_Floating_Conversion:
  6959. case ICK_Floating_Integral:
  6960. case ICK_Boolean_Conversion:
  6961. standard->First = ICK_Lvalue_To_Rvalue;
  6962. break;
  6963. }
  6964. }
  6965. }
  6966. // Finally fix up the cases for scalar->scalar component conversion, and
  6967. // identity vector/matrix component conversion
  6968. if (ICK_Identity != ComponentConversion) {
  6969. if (Second == ICK_Identity) {
  6970. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  6971. // Scalar to scalar type conversion, use normal mechanism (Second)
  6972. Second = ComponentConversion;
  6973. ComponentConversion = ICK_Identity;
  6974. } else {
  6975. // vector or matrix dimensions are not being changed, but component type
  6976. // is being converted, so change Second to signal the conversion
  6977. Second = ICK_HLSLVector_Conversion;
  6978. }
  6979. }
  6980. }
  6981. standard->Second = Second;
  6982. standard->ComponentConversion = ComponentConversion;
  6983. // For conversion which change to RValue but targeting reference type
  6984. // Hold the conversion to codeGen
  6985. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  6986. standard->First = ICK_Identity;
  6987. standard->Second = ICK_Identity;
  6988. }
  6989. }
  6990. AssignOpt(Remarks, remarks);
  6991. return true;
  6992. }
  6993. Expr* HLSLExternalSource::CastExprToTypeNumeric(Expr* expr, QualType type)
  6994. {
  6995. DXASSERT_NOMSG(expr != nullptr);
  6996. DXASSERT_NOMSG(!type.isNull());
  6997. if (expr->getType() != type) {
  6998. StandardConversionSequence standard;
  6999. TYPE_CONVERSION_REMARKS remarks;
  7000. if (CanConvert(SourceLocation(), expr, type, /*explicitConversion*/false, &remarks, &standard) &&
  7001. (standard.First != ICK_Identity || !standard.isIdentityConversion())) {
  7002. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0) {
  7003. m_sema->Diag(expr->getExprLoc(), diag::warn_hlsl_implicit_vector_truncation);
  7004. }
  7005. ExprResult result = m_sema->PerformImplicitConversion(expr, type, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7006. if (result.isUsable()) {
  7007. return result.get();
  7008. }
  7009. }
  7010. }
  7011. return expr;
  7012. }
  7013. bool HLSLExternalSource::ValidateTypeRequirements(
  7014. SourceLocation loc,
  7015. ArBasicKind elementKind,
  7016. ArTypeObjectKind objectKind,
  7017. bool requiresIntegrals,
  7018. bool requiresNumerics)
  7019. {
  7020. if (requiresIntegrals || requiresNumerics)
  7021. {
  7022. if (!IsObjectKindPrimitiveAggregate(objectKind))
  7023. {
  7024. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  7025. return false;
  7026. }
  7027. }
  7028. if (requiresIntegrals)
  7029. {
  7030. if (!IsBasicKindIntegral(elementKind))
  7031. {
  7032. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  7033. return false;
  7034. }
  7035. }
  7036. else if (requiresNumerics)
  7037. {
  7038. if (!IsBasicKindNumeric(elementKind))
  7039. {
  7040. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  7041. return false;
  7042. }
  7043. }
  7044. return true;
  7045. }
  7046. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  7047. {
  7048. bool isValid = true;
  7049. if (IsBuiltInObjectType(type)) {
  7050. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  7051. isValid = false;
  7052. }
  7053. if (kind == AR_TOBJ_COMPOUND) {
  7054. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  7055. isValid = false;
  7056. }
  7057. return isValid;
  7058. }
  7059. HRESULT HLSLExternalSource::CombineDimensions(QualType leftType, QualType rightType, ArTypeObjectKind leftKind, ArTypeObjectKind rightKind, QualType *resultType)
  7060. {
  7061. UINT leftRows, leftCols;
  7062. UINT rightRows, rightCols;
  7063. GetRowsAndColsForAny(leftType, leftRows, leftCols);
  7064. GetRowsAndColsForAny(rightType, rightRows, rightCols);
  7065. UINT leftTotal = leftRows * leftCols;
  7066. UINT rightTotal = rightRows * rightCols;
  7067. if (rightTotal == 1) {
  7068. *resultType = leftType;
  7069. return S_OK;
  7070. } else if (leftTotal == 1) {
  7071. *resultType = rightType;
  7072. return S_OK;
  7073. } else if (leftRows <= rightRows && leftCols <= rightCols) {
  7074. DXASSERT_NOMSG((leftKind == AR_TOBJ_MATRIX || leftKind == AR_TOBJ_VECTOR) &&
  7075. (rightKind == AR_TOBJ_MATRIX || rightKind == AR_TOBJ_VECTOR));
  7076. if (leftKind == rightKind) {
  7077. *resultType = leftType;
  7078. return S_OK;
  7079. } else {
  7080. // vector & matrix combination - only 1xN is allowed here
  7081. if (leftKind == AR_TOBJ_VECTOR && rightRows == 1) {
  7082. *resultType = leftType;
  7083. return S_OK;
  7084. }
  7085. }
  7086. } else if (rightRows <= leftRows && rightCols <= leftCols) {
  7087. DXASSERT_NOMSG((leftKind == AR_TOBJ_MATRIX || leftKind == AR_TOBJ_VECTOR) &&
  7088. (rightKind == AR_TOBJ_MATRIX || rightKind == AR_TOBJ_VECTOR));
  7089. if (leftKind == rightKind) {
  7090. *resultType = rightType;
  7091. return S_OK;
  7092. } else {
  7093. // matrix & vector combination - only 1xN is allowed here
  7094. if (rightKind == AR_TOBJ_VECTOR && leftRows == 1) {
  7095. *resultType = leftType;
  7096. return S_OK;
  7097. }
  7098. }
  7099. } else if ( (1 == leftRows || 1 == leftCols) &&
  7100. (1 == rightRows || 1 == rightCols)) {
  7101. // Handles cases where 1xN or Nx1 matrices are involved possibly mixed with vectors
  7102. if (leftTotal <= rightTotal) {
  7103. *resultType = leftType;
  7104. return S_OK;
  7105. } else {
  7106. *resultType = rightType;
  7107. return S_OK;
  7108. }
  7109. }
  7110. else if (((leftKind == AR_TOBJ_VECTOR && rightKind == AR_TOBJ_MATRIX) ||
  7111. (leftKind == AR_TOBJ_MATRIX && rightKind == AR_TOBJ_VECTOR)) && leftTotal == rightTotal) {
  7112. *resultType = leftType;
  7113. return S_OK;
  7114. }
  7115. return E_FAIL;
  7116. }
  7117. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  7118. /// <param name="OpLoc">Source location for operator.</param>
  7119. /// <param name="Opc">Kind of binary operator.</param>
  7120. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  7121. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  7122. /// <param name="ResultTy">Result type for operator expression.</param>
  7123. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  7124. /// <param name="CompResultTy">Type of computation result.</param>
  7125. void HLSLExternalSource::CheckBinOpForHLSL(
  7126. SourceLocation OpLoc,
  7127. BinaryOperatorKind Opc,
  7128. ExprResult& LHS,
  7129. ExprResult& RHS,
  7130. QualType& ResultTy,
  7131. QualType& CompLHSTy,
  7132. QualType& CompResultTy)
  7133. {
  7134. // At the start, none of the output types should be valid.
  7135. DXASSERT_NOMSG(ResultTy.isNull());
  7136. DXASSERT_NOMSG(CompLHSTy.isNull());
  7137. DXASSERT_NOMSG(CompResultTy.isNull());
  7138. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7139. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7140. // If either expression is invalid to begin with, propagate that.
  7141. if (LHS.isInvalid() || RHS.isInvalid()) {
  7142. return;
  7143. }
  7144. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  7145. // Handle Assign and Comma operators and return
  7146. switch (Opc)
  7147. {
  7148. case BO_AddAssign:
  7149. case BO_AndAssign:
  7150. case BO_DivAssign:
  7151. case BO_MulAssign:
  7152. case BO_RemAssign:
  7153. case BO_ShlAssign:
  7154. case BO_ShrAssign:
  7155. case BO_SubAssign:
  7156. case BO_OrAssign:
  7157. case BO_XorAssign: {
  7158. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  7159. Sema & S);
  7160. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7161. return;
  7162. }
  7163. } break;
  7164. case BO_Assign: {
  7165. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7166. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7167. return;
  7168. }
  7169. bool complained = false;
  7170. ResultTy = LHS.get()->getType();
  7171. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  7172. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  7173. Sema::AssignmentAction::AA_Assigning, &complained)) {
  7174. return;
  7175. }
  7176. StandardConversionSequence standard;
  7177. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  7178. ExplicitConversionFalse, complained, complained, &standard)) {
  7179. return;
  7180. }
  7181. if (RHS.get()->isLValue()) {
  7182. standard.First = ICK_Lvalue_To_Rvalue;
  7183. }
  7184. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  7185. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  7186. return;
  7187. }
  7188. break;
  7189. case BO_Comma:
  7190. // C performs conversions, C++ doesn't but still checks for type completeness.
  7191. // There are also diagnostics for improper comma use.
  7192. // In the HLSL case these cases don't apply or simply aren't surfaced.
  7193. ResultTy = RHS.get()->getType();
  7194. return;
  7195. }
  7196. // Leave this diagnostic for last to emulate fxc behavior.
  7197. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  7198. bool unsupportedBoolLvalue = isCompoundAssignment &&
  7199. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7200. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7201. // Turn operand inputs into r-values.
  7202. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7203. if (!isCompoundAssignment) {
  7204. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7205. }
  7206. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7207. if (LHS.isInvalid() || RHS.isInvalid()) {
  7208. return;
  7209. }
  7210. // Promote bool to int now if necessary
  7211. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc) &&
  7212. !isCompoundAssignment) {
  7213. LHS = PromoteToIntIfBool(LHS);
  7214. }
  7215. // Gather type info
  7216. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7217. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7218. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7219. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7220. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7221. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7222. // Validate type requirements
  7223. {
  7224. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  7225. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  7226. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  7227. return;
  7228. }
  7229. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  7230. return;
  7231. }
  7232. }
  7233. // Promote rhs bool to int if necessary.
  7234. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7235. RHS = PromoteToIntIfBool(RHS);
  7236. }
  7237. if (unsupportedBoolLvalue) {
  7238. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7239. return;
  7240. }
  7241. // We don't support binary operators on built-in object types other than assignment or commas.
  7242. {
  7243. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  7244. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  7245. bool isValid;
  7246. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  7247. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  7248. isValid = false;
  7249. }
  7250. if (!isValid) {
  7251. return;
  7252. }
  7253. }
  7254. // We don't support equality comparisons on arrays.
  7255. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  7256. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  7257. return;
  7258. }
  7259. // Combine element types for computation.
  7260. ArBasicKind resultElementKind = leftElementKind;
  7261. {
  7262. if (BinaryOperatorKindIsLogical(Opc)) {
  7263. resultElementKind = AR_BASIC_BOOL;
  7264. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  7265. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  7266. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7267. return;
  7268. }
  7269. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  7270. (resultElementKind == AR_BASIC_LITERAL_INT ||
  7271. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  7272. rightElementKind != AR_BASIC_LITERAL_INT &&
  7273. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  7274. // For case like 1<<x.
  7275. resultElementKind = AR_BASIC_UINT32;
  7276. }
  7277. // The following combines the selected/combined element kind above with
  7278. // the dimensions that are legal to implicitly cast. This means that
  7279. // element kind may be taken from one side and the dimensions from the
  7280. // other.
  7281. if (!isCompoundAssignment) {
  7282. // Legal dimension combinations are identical, splat, and truncation.
  7283. // ResultTy will be set to whichever type can be converted to, if legal,
  7284. // with preference for leftType if both are possible.
  7285. if (FAILED(CombineDimensions(leftType, rightType, leftObjectKind, rightObjectKind, &ResultTy))) {
  7286. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7287. return;
  7288. }
  7289. } else {
  7290. ResultTy = LHS.get()->getType();
  7291. }
  7292. // Here, element kind is combined with dimensions for computation type.
  7293. UINT rowCount, colCount;
  7294. ArTypeObjectKind resultObjectKind = (leftObjectKind == rightObjectKind ? leftObjectKind : AR_TOBJ_INVALID);
  7295. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7296. ResultTy = NewSimpleAggregateType(resultObjectKind, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7297. }
  7298. // Perform necessary conversion sequences for LHS and RHS
  7299. if (RHS.get()->getType() != ResultTy) {
  7300. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  7301. }
  7302. if (isCompoundAssignment) {
  7303. bool complained = false;
  7304. StandardConversionSequence standard;
  7305. if (!ValidateCast(OpLoc, RHS.get(), LHS.get()->getType(), ExplicitConversionFalse,
  7306. complained, complained, &standard)) {
  7307. ResultTy = QualType();
  7308. return;
  7309. }
  7310. CompResultTy = ResultTy;
  7311. CompLHSTy = CompResultTy;
  7312. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  7313. // then converts to the result type and then assigns.
  7314. //
  7315. // So int + float promotes the int to float, does a floating-point addition,
  7316. // then the result becomes and int and is assigned.
  7317. ResultTy = LHSTypeAsPossibleLValue;
  7318. } else if (LHS.get()->getType() != ResultTy) {
  7319. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  7320. }
  7321. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  7322. {
  7323. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  7324. // Return bool vector for vector types.
  7325. if (IsVectorType(m_sema, ResultTy)) {
  7326. UINT rowCount, colCount;
  7327. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7328. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  7329. } else if (IsMatrixType(m_sema, ResultTy)) {
  7330. UINT rowCount, colCount;
  7331. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7332. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  7333. } else
  7334. ResultTy = m_context->BoolTy.withConst();
  7335. }
  7336. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  7337. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  7338. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  7339. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  7340. return;
  7341. }
  7342. }
  7343. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  7344. if (resultElementKind == AR_BASIC_FLOAT64) {
  7345. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  7346. return;
  7347. }
  7348. }
  7349. }
  7350. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  7351. /// <param name="OpLoc">Source location for operator.</param>
  7352. /// <param name="Opc">Kind of operator.</param>
  7353. /// <param name="InputExpr">Input expression to the operator.</param>
  7354. /// <param name="VK">Value kind for resulting expression.</param>
  7355. /// <param name="OK">Object kind for resulting expression.</param>
  7356. /// <returns>The result type for the expression.</returns>
  7357. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  7358. SourceLocation OpLoc,
  7359. UnaryOperatorKind Opc,
  7360. ExprResult& InputExpr,
  7361. ExprValueKind& VK,
  7362. ExprObjectKind& OK)
  7363. {
  7364. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  7365. if (InputExpr.isInvalid())
  7366. return QualType();
  7367. // Reject unsupported operators * and &
  7368. switch (Opc) {
  7369. case UO_AddrOf:
  7370. case UO_Deref:
  7371. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  7372. return QualType();
  7373. }
  7374. Expr* expr = InputExpr.get();
  7375. if (expr->isTypeDependent())
  7376. return m_context->DependentTy;
  7377. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  7378. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  7379. if (elementKind == AR_BASIC_ENUM) {
  7380. bool isInc = IsIncrementOp(Opc);
  7381. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  7382. return QualType();
  7383. }
  7384. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7385. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  7386. return QualType();
  7387. } else {
  7388. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  7389. if (InputExpr.isInvalid()) return QualType();
  7390. }
  7391. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  7392. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7393. return QualType();
  7394. }
  7395. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7396. InputExpr = PromoteToIntIfBool(InputExpr);
  7397. expr = InputExpr.get();
  7398. elementKind = GetTypeElementKind(expr->getType());
  7399. }
  7400. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  7401. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  7402. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  7403. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  7404. return QualType();
  7405. }
  7406. if (Opc == UnaryOperatorKind::UO_Minus) {
  7407. if (IS_BASIC_UINT(Opc)) {
  7408. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  7409. }
  7410. }
  7411. // By default, the result type is the operand type.
  7412. // Logical not however should cast to a bool.
  7413. QualType resultType = expr->getType();
  7414. if (Opc == UnaryOperatorKind::UO_LNot) {
  7415. UINT rowCount, colCount;
  7416. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  7417. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  7418. StandardConversionSequence standard;
  7419. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  7420. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  7421. return QualType();
  7422. }
  7423. // Cast argument.
  7424. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7425. if (result.isUsable()) {
  7426. InputExpr = result.get();
  7427. }
  7428. }
  7429. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  7430. if (isPrefix) {
  7431. VK = VK_LValue;
  7432. return resultType;
  7433. }
  7434. else {
  7435. VK = VK_RValue;
  7436. return resultType.getUnqualifiedType();
  7437. }
  7438. }
  7439. clang::QualType HLSLExternalSource::CheckVectorConditional(
  7440. _In_ ExprResult &Cond,
  7441. _In_ ExprResult &LHS,
  7442. _In_ ExprResult &RHS,
  7443. _In_ SourceLocation QuestionLoc)
  7444. {
  7445. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  7446. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7447. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7448. // If either expression is invalid to begin with, propagate that.
  7449. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  7450. return QualType();
  7451. }
  7452. // Gather type info
  7453. QualType condType = GetStructuralForm(Cond.get()->getType());
  7454. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7455. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7456. ArBasicKind condElementKind = GetTypeElementKind(condType);
  7457. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7458. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7459. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  7460. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7461. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7462. QualType ResultTy = leftType;
  7463. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  7464. if (!condIsSimple) {
  7465. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  7466. return QualType();
  7467. }
  7468. UINT rowCountCond, colCountCond;
  7469. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  7470. bool leftIsSimple =
  7471. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  7472. leftObjectKind == AR_TOBJ_MATRIX;
  7473. bool rightIsSimple =
  7474. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  7475. rightObjectKind == AR_TOBJ_MATRIX;
  7476. if (!leftIsSimple || !rightIsSimple) {
  7477. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  7478. if (leftType == rightType) {
  7479. return leftType;
  7480. }
  7481. }
  7482. // NOTE: Limiting this operator to working only on basic numeric types.
  7483. // This is due to extremely limited (and even broken) support for any other case.
  7484. // In the future we may decide to support more cases.
  7485. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  7486. return QualType();
  7487. }
  7488. // Types should be only scalar, vector, or matrix after this point.
  7489. ArBasicKind resultElementKind = leftElementKind;
  7490. // Combine LHS and RHS element types for computation.
  7491. if (leftElementKind != rightElementKind) {
  7492. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  7493. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  7494. return QualType();
  7495. }
  7496. }
  7497. // Combine LHS and RHS dimensions
  7498. if (FAILED(CombineDimensions(leftType, rightType, leftObjectKind, rightObjectKind, &ResultTy))) {
  7499. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  7500. return QualType();
  7501. }
  7502. UINT rowCount, colCount;
  7503. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7504. // If result is scalar, use condition dimensions.
  7505. // Otherwise, condition must either match or is scalar, then use result dimensions
  7506. if (rowCount * colCount == 1) {
  7507. rowCount = rowCountCond;
  7508. colCount = colCountCond;
  7509. }
  7510. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  7511. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  7512. return QualType();
  7513. }
  7514. // Here, element kind is combined with dimensions for result type.
  7515. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7516. // Cast condition to RValue
  7517. if (Cond.get()->isLValue())
  7518. Cond.set(CreateLValueToRValueCast(Cond.get()));
  7519. // Convert condition component type to bool, using result component dimensions
  7520. if (condElementKind != AR_BASIC_BOOL) {
  7521. Cond = CastExprToTypeNumeric(Cond.get(),
  7522. NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal());
  7523. }
  7524. // Cast LHS/RHS to RValue
  7525. if (LHS.get()->isLValue())
  7526. LHS.set(CreateLValueToRValueCast(LHS.get()));
  7527. if (RHS.get()->isLValue())
  7528. RHS.set(CreateLValueToRValueCast(RHS.get()));
  7529. // TODO: Why isn't vector truncation being reported?
  7530. if (leftType != ResultTy) {
  7531. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  7532. }
  7533. if (rightType != ResultTy) {
  7534. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  7535. }
  7536. return ResultTy;
  7537. }
  7538. // Apply type specifier sign to the given QualType.
  7539. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  7540. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  7541. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  7542. _In_ clang::SourceLocation Loc) {
  7543. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  7544. return type;
  7545. }
  7546. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  7547. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  7548. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  7549. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  7550. return type;
  7551. }
  7552. // check if element type is unsigned and check if such vector exists
  7553. // If not create a new one, Make a QualType of the new kind
  7554. ArBasicKind elementKind = GetTypeElementKind(type);
  7555. // Only ints can have signed/unsigend ty
  7556. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  7557. return type;
  7558. }
  7559. else {
  7560. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  7561. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  7562. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  7563. // Get new vector types for a given TypeSpecifierSign.
  7564. if (objKind == AR_TOBJ_VECTOR) {
  7565. UINT colCount = GetHLSLVecSize(type);
  7566. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  7567. return m_context->getTypeDeclType(qts);
  7568. } else if (objKind == AR_TOBJ_MATRIX) {
  7569. UINT rowCount, colCount;
  7570. GetRowsAndCols(type, rowCount, colCount);
  7571. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  7572. return m_context->getTypeDeclType(qts);
  7573. } else {
  7574. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  7575. return m_scalarTypes[newScalarType];
  7576. }
  7577. }
  7578. }
  7579. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  7580. FunctionTemplateDecl *FunctionTemplate,
  7581. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7582. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7583. {
  7584. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  7585. // Get information about the function we have.
  7586. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  7587. DXASSERT(functionMethod != nullptr,
  7588. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  7589. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  7590. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  7591. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  7592. // Handle subscript overloads.
  7593. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  7594. {
  7595. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  7596. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  7597. if (!findResult.Found())
  7598. {
  7599. // This might be a nested type. Do a lookup on the parent.
  7600. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  7601. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  7602. {
  7603. return Sema::TemplateDeductionResult::TDK_Invalid;
  7604. }
  7605. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  7606. if (!findResult.Found())
  7607. {
  7608. return Sema::TemplateDeductionResult::TDK_Invalid;
  7609. }
  7610. DXASSERT(
  7611. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  7612. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  7613. "otherwise FindStructBasicType should have failed - no other types are allowed");
  7614. objectElement = GetFirstElementTypeFromDecl(
  7615. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  7616. }
  7617. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  7618. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7619. FunctionTemplate->getCanonicalDecl());
  7620. return Sema::TemplateDeductionResult::TDK_Success;
  7621. }
  7622. // Reject overload lookups that aren't identifier-based.
  7623. if (!FunctionTemplate->getDeclName().isIdentifier())
  7624. {
  7625. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7626. }
  7627. // Find the table of intrinsics based on the object type.
  7628. const HLSL_INTRINSIC* intrinsics;
  7629. size_t intrinsicCount;
  7630. const char* objectName;
  7631. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  7632. DXASSERT(intrinsics != nullptr,
  7633. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  7634. "or the parser let a user-defined template object through");
  7635. // Look for an intrinsic for which we can match arguments.
  7636. size_t argCount;
  7637. QualType argTypes[g_MaxIntrinsicParamCount + 1];
  7638. StringRef nameIdentifier = FunctionTemplate->getName();
  7639. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  7640. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  7641. while (cursor != end)
  7642. {
  7643. if (!MatchArguments(*cursor, objectElement, Args, argTypes, &argCount))
  7644. {
  7645. ++cursor;
  7646. continue;
  7647. }
  7648. // Currently only intrinsic we allow for explicit template arguments are
  7649. // for Load return types for ByteAddressBuffer/RWByteAddressBuffer
  7650. // TODO: handle template arguments for future intrinsics in a more natural way
  7651. // Check Explicit template arguments
  7652. UINT intrinsicOp = (*cursor)->Op;
  7653. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  7654. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  7655. bool IsBAB =
  7656. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  7657. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  7658. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  7659. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  7660. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  7661. bool isLegalTemplate = false;
  7662. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  7663. auto TemplateDiag =
  7664. !IsBABLoad
  7665. ? diag::err_hlsl_intrinsic_template_arg_unsupported
  7666. : !Is2018 ? diag::err_hlsl_intrinsic_template_arg_requires_2018
  7667. : diag::err_hlsl_intrinsic_template_arg_requires_2018;
  7668. if (IsBABLoad && Is2018 && ExplicitTemplateArgs->size() == 1) {
  7669. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  7670. QualType explicitType = (*ExplicitTemplateArgs)[0].getArgument().getAsType();
  7671. ArTypeObjectKind explicitKind = GetTypeObjectKind(explicitType);
  7672. if (explicitKind == AR_TOBJ_BASIC || explicitKind == AR_TOBJ_VECTOR) {
  7673. isLegalTemplate = GET_BASIC_BITS(GetTypeElementKind(explicitType)) != BPROP_BITS64 ||
  7674. GetNumElements(explicitType) <= 2;
  7675. }
  7676. if (isLegalTemplate) {
  7677. argTypes[0] = explicitType;
  7678. }
  7679. }
  7680. if (!isLegalTemplate) {
  7681. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  7682. return Sema::TemplateDeductionResult::TDK_Invalid;
  7683. }
  7684. } else if (IsBABStore) {
  7685. // Prior to HLSL 2018, Store operation only stored scalar uint.
  7686. if (!Is2018) {
  7687. if (GetNumElements(argTypes[2]) != 1) {
  7688. getSema()->Diag(Args[1]->getLocStart(),
  7689. diag::err_ovl_no_viable_member_function_in_call)
  7690. << intrinsicName;
  7691. return Sema::TemplateDeductionResult::TDK_Invalid;
  7692. }
  7693. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  7694. 32, /*signed*/ false);
  7695. } else {
  7696. // not supporting types > 16 bytes yet.
  7697. if (GET_BASIC_BITS(GetTypeElementKind(argTypes[2])) == BPROP_BITS64 &&
  7698. GetNumElements(argTypes[2]) > 2) {
  7699. getSema()->Diag(Args[1]->getLocStart(),
  7700. diag::err_ovl_no_viable_member_function_in_call)
  7701. << intrinsicName;
  7702. return Sema::TemplateDeductionResult::TDK_Invalid;
  7703. }
  7704. }
  7705. }
  7706. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes, argCount);
  7707. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7708. FunctionTemplate->getCanonicalDecl());
  7709. if (!IsValidateObjectElement(*cursor, objectElement)) {
  7710. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  7711. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  7712. }
  7713. return Sema::TemplateDeductionResult::TDK_Success;
  7714. }
  7715. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7716. }
  7717. void HLSLExternalSource::DiagnoseAssignmentResultForHLSL(
  7718. Sema::AssignConvertType ConvTy,
  7719. SourceLocation Loc,
  7720. QualType DstType, QualType SrcType,
  7721. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  7722. _Out_opt_ bool *Complained)
  7723. {
  7724. if (Complained) *Complained = false;
  7725. // No work to do if there is not type change.
  7726. if (DstType == SrcType) {
  7727. return;
  7728. }
  7729. // Don't generate a warning if the user is casting explicitly
  7730. // or if initializing - our initialization handling already emits this.
  7731. if (Action == Sema::AssignmentAction::AA_Casting ||
  7732. Action == Sema::AssignmentAction::AA_Initializing) {
  7733. return;
  7734. }
  7735. ArBasicKind src = BasicTypeForScalarType(SrcType->getCanonicalTypeUnqualified());
  7736. if (src == AR_BASIC_UNKNOWN || src == AR_BASIC_BOOL) {
  7737. return;
  7738. }
  7739. ArBasicKind dst = BasicTypeForScalarType(DstType->getCanonicalTypeUnqualified());
  7740. if (dst == AR_BASIC_UNKNOWN) {
  7741. return;
  7742. }
  7743. bool warnAboutNarrowing = false;
  7744. switch (dst) {
  7745. case AR_BASIC_FLOAT32:
  7746. case AR_BASIC_INT32:
  7747. case AR_BASIC_UINT32:
  7748. case AR_BASIC_FLOAT16:
  7749. warnAboutNarrowing = src == AR_BASIC_FLOAT64;
  7750. break;
  7751. case AR_BASIC_MIN16FLOAT:
  7752. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  7753. break;
  7754. case AR_BASIC_MIN16INT:
  7755. case AR_BASIC_MIN16UINT:
  7756. case AR_BASIC_MIN12INT:
  7757. case AR_BASIC_MIN10FLOAT:
  7758. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  7759. break;
  7760. }
  7761. // fxc errors looked like this:
  7762. // warning X3205: conversion from larger type to smaller, possible loss of data
  7763. if (warnAboutNarrowing) {
  7764. m_sema->Diag(Loc, diag::warn_hlsl_narrowing) << SrcType << DstType;
  7765. AssignOpt(true, Complained);
  7766. }
  7767. }
  7768. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  7769. {
  7770. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  7771. }
  7772. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  7773. QualType DestType,
  7774. Sema::CheckedConversionKind CCK,
  7775. const SourceRange &OpRange, unsigned &msg,
  7776. CastKind &Kind, CXXCastPath &BasePath,
  7777. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  7778. _Inout_opt_ StandardConversionSequence* standard)
  7779. {
  7780. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  7781. bool explicitConversion
  7782. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  7783. QualType sourceType = SrcExpr.get()->getType();
  7784. bool suppressWarnings = explicitConversion || SuppressWarnings;
  7785. SourceLocation loc = OpRange.getBegin();
  7786. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  7787. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  7788. // so do this here until we figure out why this is needed.
  7789. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  7790. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  7791. }
  7792. return true;
  7793. }
  7794. // ValidateCast includes its own error messages.
  7795. msg = 0;
  7796. return false;
  7797. }
  7798. /// <summary>
  7799. /// Checks if a subscript index argument can be initialized from the given expression.
  7800. /// </summary>
  7801. /// <param name="SrcExpr">Source expression used as argument.</param>
  7802. /// <param name="DestType">Parameter type to initialize.</param>
  7803. /// <remarks>
  7804. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  7805. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  7806. /// </remarks>
  7807. ImplicitConversionSequence
  7808. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  7809. clang::QualType DestType) {
  7810. DXASSERT_NOMSG(SrcExpr != nullptr);
  7811. DXASSERT_NOMSG(!DestType.isNull());
  7812. unsigned int msg = 0;
  7813. CastKind kind;
  7814. CXXCastPath path;
  7815. ImplicitConversionSequence sequence;
  7816. sequence.setStandard();
  7817. ExprResult sourceExpr(SrcExpr);
  7818. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  7819. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7820. SrcExpr->getType(), DestType);
  7821. } else if (!TryStaticCastForHLSL(
  7822. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  7823. msg, kind, path, ListInitializationFalse,
  7824. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  7825. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7826. SrcExpr->getType(), DestType);
  7827. }
  7828. return sequence;
  7829. }
  7830. template <typename T>
  7831. static
  7832. bool IsValueInRange(T value, T minValue, T maxValue) {
  7833. return minValue <= value && value <= maxValue;
  7834. }
  7835. #define D3DX_16F_MAX 6.550400e+004 // max value
  7836. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  7837. static
  7838. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  7839. {
  7840. DXASSERT_NOMSG(minValue != nullptr);
  7841. DXASSERT_NOMSG(maxValue != nullptr);
  7842. switch (basicKind) {
  7843. case AR_BASIC_MIN10FLOAT:
  7844. case AR_BASIC_MIN16FLOAT:
  7845. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  7846. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7847. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  7848. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  7849. }
  7850. DXASSERT(false, "unreachable");
  7851. *minValue = 0; *maxValue = 0;
  7852. return;
  7853. }
  7854. static
  7855. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  7856. {
  7857. DXASSERT_NOMSG(maxValue != nullptr);
  7858. switch (basicKind) {
  7859. case AR_BASIC_BOOL: *maxValue = 1; return;
  7860. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  7861. case AR_BASIC_MIN16UINT:
  7862. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  7863. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  7864. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  7865. }
  7866. DXASSERT(false, "unreachable");
  7867. *maxValue = 0;
  7868. return;
  7869. }
  7870. static
  7871. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  7872. {
  7873. DXASSERT_NOMSG(minValue != nullptr);
  7874. DXASSERT_NOMSG(maxValue != nullptr);
  7875. switch (basicKind) {
  7876. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  7877. case AR_BASIC_MIN12INT:
  7878. case AR_BASIC_MIN16INT:
  7879. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  7880. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  7881. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  7882. }
  7883. DXASSERT(false, "unreachable");
  7884. *minValue = 0; *maxValue = 0;
  7885. return;
  7886. }
  7887. static
  7888. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  7889. {
  7890. if (IS_BASIC_FLOAT(basicKind)) {
  7891. double val;
  7892. if (value.isInt()) {
  7893. val = value.getInt().getLimitedValue();
  7894. } else if (value.isFloat()) {
  7895. llvm::APFloat floatValue = value.getFloat();
  7896. if (!floatValue.isFinite()) {
  7897. return false;
  7898. }
  7899. llvm::APFloat valueFloat = value.getFloat();
  7900. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  7901. val = value.getFloat().convertToFloat();
  7902. }
  7903. else {
  7904. val = value.getFloat().convertToDouble();
  7905. }
  7906. } else {
  7907. return false;
  7908. }
  7909. double minValue, maxValue;
  7910. GetFloatLimits(basicKind, &minValue, &maxValue);
  7911. return IsValueInRange(val, minValue, maxValue);
  7912. }
  7913. else if (IS_BASIC_SINT(basicKind)) {
  7914. if (!value.isInt()) {
  7915. return false;
  7916. }
  7917. int64_t val = value.getInt().getSExtValue();
  7918. int64_t minValue, maxValue;
  7919. GetSignedLimits(basicKind, &minValue, &maxValue);
  7920. return IsValueInRange(val, minValue, maxValue);
  7921. }
  7922. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  7923. if (!value.isInt()) {
  7924. return false;
  7925. }
  7926. uint64_t val = value.getInt().getLimitedValue();
  7927. uint64_t maxValue;
  7928. GetUnsignedLimit(basicKind, &maxValue);
  7929. return IsValueInRange(val, (uint64_t)0, maxValue);
  7930. }
  7931. else {
  7932. return false;
  7933. }
  7934. }
  7935. static
  7936. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  7937. {
  7938. DXASSERT_NOMSG(!targetType.isNull());
  7939. DXASSERT_NOMSG(sourceExpr != nullptr);
  7940. Expr::EvalResult evalResult;
  7941. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  7942. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  7943. return IsValueInBasicRange(targetKind, evalResult.Val);
  7944. }
  7945. }
  7946. return false;
  7947. }
  7948. bool HLSLExternalSource::ValidateCast(
  7949. SourceLocation OpLoc,
  7950. _In_ Expr* sourceExpr,
  7951. QualType target,
  7952. bool explicitConversion,
  7953. bool suppressWarnings,
  7954. bool suppressErrors,
  7955. _Inout_opt_ StandardConversionSequence* standard)
  7956. {
  7957. DXASSERT_NOMSG(sourceExpr != nullptr);
  7958. QualType source = sourceExpr->getType();
  7959. TYPE_CONVERSION_REMARKS remarks;
  7960. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  7961. {
  7962. const bool IsOutputParameter = false;
  7963. //
  7964. // Check whether the lack of explicit-ness matters.
  7965. //
  7966. // Setting explicitForDiagnostics to true in that case will avoid the message
  7967. // saying anything about the implicit nature of the cast, when adding the
  7968. // explicit cast won't make a difference.
  7969. //
  7970. bool explicitForDiagnostics = explicitConversion;
  7971. if (explicitConversion == false)
  7972. {
  7973. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  7974. {
  7975. // Can't convert either way - implicit/explicit doesn't matter.
  7976. explicitForDiagnostics = true;
  7977. }
  7978. }
  7979. if (!suppressErrors)
  7980. {
  7981. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  7982. << explicitForDiagnostics << IsOutputParameter << source << target;
  7983. }
  7984. return false;
  7985. }
  7986. if (!suppressWarnings)
  7987. {
  7988. if (!explicitConversion)
  7989. {
  7990. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  7991. {
  7992. // This is a much more restricted version of the analysis does
  7993. // StandardConversionSequence::getNarrowingKind
  7994. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  7995. {
  7996. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  7997. }
  7998. }
  7999. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  8000. {
  8001. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  8002. }
  8003. }
  8004. }
  8005. return true;
  8006. }
  8007. ////////////////////////////////////////////////////////////////////////////////
  8008. // Functions exported from this translation unit. //
  8009. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  8010. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  8011. SourceLocation OpLoc,
  8012. UnaryOperatorKind Opc,
  8013. ExprResult& InputExpr,
  8014. ExprValueKind& VK,
  8015. ExprObjectKind& OK)
  8016. {
  8017. ExternalSemaSource* externalSource = self.getExternalSource();
  8018. if (externalSource == nullptr) {
  8019. return QualType();
  8020. }
  8021. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8022. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  8023. }
  8024. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  8025. void hlsl::CheckBinOpForHLSL(Sema& self,
  8026. SourceLocation OpLoc,
  8027. BinaryOperatorKind Opc,
  8028. ExprResult& LHS,
  8029. ExprResult& RHS,
  8030. QualType& ResultTy,
  8031. QualType& CompLHSTy,
  8032. QualType& CompResultTy)
  8033. {
  8034. ExternalSemaSource* externalSource = self.getExternalSource();
  8035. if (externalSource == nullptr) {
  8036. return;
  8037. }
  8038. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8039. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  8040. }
  8041. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  8042. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  8043. {
  8044. DXASSERT_NOMSG(Template != nullptr);
  8045. ExternalSemaSource* externalSource = self.getExternalSource();
  8046. if (externalSource == nullptr) {
  8047. return false;
  8048. }
  8049. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8050. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  8051. }
  8052. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  8053. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  8054. FunctionTemplateDecl *FunctionTemplate,
  8055. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8056. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8057. {
  8058. return HLSLExternalSource::FromSema(self)
  8059. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  8060. }
  8061. void hlsl::DiagnoseAssignmentResultForHLSL(Sema* self,
  8062. Sema::AssignConvertType ConvTy,
  8063. SourceLocation Loc,
  8064. QualType DstType, QualType SrcType,
  8065. Expr *SrcExpr, Sema::AssignmentAction Action,
  8066. bool *Complained)
  8067. {
  8068. return HLSLExternalSource::FromSema(self)
  8069. ->DiagnoseAssignmentResultForHLSL(ConvTy, Loc, DstType, SrcType, SrcExpr, Action, Complained);
  8070. }
  8071. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  8072. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  8073. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  8074. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  8075. self->Diag(condExpr->getLocStart(),
  8076. diag::err_hlsl_control_flow_cond_not_scalar)
  8077. << StmtName;
  8078. return;
  8079. }
  8080. condExpr = IC->getSubExpr();
  8081. }
  8082. }
  8083. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  8084. {
  8085. // TODO: handle shorthand cases.
  8086. return left.size() == 0 || right.size() == 0 || left.equals(right);
  8087. }
  8088. void hlsl::DiagnosePackingOffset(
  8089. clang::Sema* self,
  8090. SourceLocation loc,
  8091. clang::QualType type,
  8092. int componentOffset)
  8093. {
  8094. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  8095. if (componentOffset > 0) {
  8096. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8097. ArBasicKind element = source->GetTypeElementKind(type);
  8098. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  8099. // Only perform some simple validation for now.
  8100. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  8101. int count = GetElementCount(type);
  8102. if (count > (4 - componentOffset)) {
  8103. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  8104. }
  8105. }
  8106. }
  8107. }
  8108. void hlsl::DiagnoseRegisterType(
  8109. clang::Sema* self,
  8110. clang::SourceLocation loc,
  8111. clang::QualType type,
  8112. char registerType)
  8113. {
  8114. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8115. ArBasicKind element = source->GetTypeElementKind(type);
  8116. StringRef expected("none");
  8117. bool isValid = true;
  8118. bool isWarning = false;
  8119. switch (element)
  8120. {
  8121. case AR_BASIC_BOOL:
  8122. case AR_BASIC_LITERAL_FLOAT:
  8123. case AR_BASIC_FLOAT16:
  8124. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8125. case AR_BASIC_FLOAT32:
  8126. case AR_BASIC_FLOAT64:
  8127. case AR_BASIC_LITERAL_INT:
  8128. case AR_BASIC_INT8:
  8129. case AR_BASIC_UINT8:
  8130. case AR_BASIC_INT16:
  8131. case AR_BASIC_UINT16:
  8132. case AR_BASIC_INT32:
  8133. case AR_BASIC_UINT32:
  8134. case AR_BASIC_INT64:
  8135. case AR_BASIC_UINT64:
  8136. case AR_BASIC_MIN10FLOAT:
  8137. case AR_BASIC_MIN16FLOAT:
  8138. case AR_BASIC_MIN12INT:
  8139. case AR_BASIC_MIN16INT:
  8140. case AR_BASIC_MIN16UINT:
  8141. expected = "'b', 'c', or 'i'";
  8142. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i' ||
  8143. registerType == 'B' || registerType == 'C' || registerType == 'I';
  8144. break;
  8145. case AR_OBJECT_TEXTURE1D:
  8146. case AR_OBJECT_TEXTURE1D_ARRAY:
  8147. case AR_OBJECT_TEXTURE2D:
  8148. case AR_OBJECT_TEXTURE2D_ARRAY:
  8149. case AR_OBJECT_TEXTURE3D:
  8150. case AR_OBJECT_TEXTURECUBE:
  8151. case AR_OBJECT_TEXTURECUBE_ARRAY:
  8152. case AR_OBJECT_TEXTURE2DMS:
  8153. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  8154. expected = "'t' or 's'";
  8155. isValid = registerType == 't' || registerType == 's' ||
  8156. registerType == 'T' || registerType == 'S';
  8157. break;
  8158. case AR_OBJECT_SAMPLER:
  8159. case AR_OBJECT_SAMPLER1D:
  8160. case AR_OBJECT_SAMPLER2D:
  8161. case AR_OBJECT_SAMPLER3D:
  8162. case AR_OBJECT_SAMPLERCUBE:
  8163. case AR_OBJECT_SAMPLERCOMPARISON:
  8164. expected = "'s' or 't'";
  8165. isValid = registerType == 's' || registerType == 't' ||
  8166. registerType == 'S' || registerType == 'T';
  8167. break;
  8168. case AR_OBJECT_BUFFER:
  8169. expected = "'t'";
  8170. isValid = registerType == 't' || registerType == 'T';
  8171. break;
  8172. case AR_OBJECT_POINTSTREAM:
  8173. case AR_OBJECT_LINESTREAM:
  8174. case AR_OBJECT_TRIANGLESTREAM:
  8175. isValid = false;
  8176. isWarning = true;
  8177. break;
  8178. case AR_OBJECT_INPUTPATCH:
  8179. case AR_OBJECT_OUTPUTPATCH:
  8180. isValid = false;
  8181. isWarning = true;
  8182. break;
  8183. case AR_OBJECT_RWTEXTURE1D:
  8184. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  8185. case AR_OBJECT_RWTEXTURE2D:
  8186. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  8187. case AR_OBJECT_RWTEXTURE3D:
  8188. case AR_OBJECT_RWBUFFER:
  8189. expected = "'u'";
  8190. isValid = registerType == 'u' || registerType == 'U';
  8191. break;
  8192. case AR_OBJECT_BYTEADDRESS_BUFFER:
  8193. case AR_OBJECT_STRUCTURED_BUFFER:
  8194. expected = "'t'";
  8195. isValid = registerType == 't' || registerType == 'T';
  8196. break;
  8197. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  8198. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  8199. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  8200. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8201. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8202. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8203. expected = "'u'";
  8204. isValid = registerType == 'u' || registerType == 'U';
  8205. break;
  8206. case AR_OBJECT_CONSTANT_BUFFER:
  8207. expected = "'b'";
  8208. isValid = registerType == 'b' || registerType == 'B';
  8209. break;
  8210. case AR_OBJECT_TEXTURE_BUFFER:
  8211. expected = "'t'";
  8212. isValid = registerType == 't' || registerType == 'T';
  8213. break;
  8214. case AR_OBJECT_ROVBUFFER:
  8215. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  8216. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  8217. case AR_OBJECT_ROVTEXTURE1D:
  8218. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  8219. case AR_OBJECT_ROVTEXTURE2D:
  8220. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  8221. case AR_OBJECT_ROVTEXTURE3D:
  8222. expected = "'u'";
  8223. isValid = registerType == 'u' || registerType == 'U';
  8224. break;
  8225. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  8226. isWarning = true;
  8227. break; // So we don't care what you tried to bind it to
  8228. };
  8229. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  8230. // a warning instead.
  8231. if (!isValid)
  8232. {
  8233. if (isWarning)
  8234. self->Diag(loc, diag::warn_hlsl_incorrect_bind_semantic) << expected;
  8235. else
  8236. self->Diag(loc, diag::err_hlsl_incorrect_bind_semantic) << expected;
  8237. }
  8238. }
  8239. struct NameLookup {
  8240. FunctionDecl *Found;
  8241. FunctionDecl *Other;
  8242. };
  8243. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  8244. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  8245. FunctionDecl *pFoundDecl = nullptr;
  8246. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  8247. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  8248. if (!pFnDecl) continue;
  8249. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  8250. if (pFoundDecl) {
  8251. return NameLookup{ pFoundDecl, pFnDecl };
  8252. }
  8253. pFoundDecl = pFnDecl;
  8254. }
  8255. return NameLookup{ pFoundDecl, nullptr };
  8256. }
  8257. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  8258. DXASSERT_NOMSG(self != nullptr);
  8259. // Don't bother with global validation if compilation has already failed.
  8260. if (self->getDiagnostics().hasErrorOccurred()) {
  8261. return;
  8262. }
  8263. // Don't check entry function for library.
  8264. if (self->getLangOpts().IsHLSLLibrary) {
  8265. // TODO: validate no recursion start from every function.
  8266. return;
  8267. }
  8268. // TODO: make these error 'real' errors rather than on-the-fly things
  8269. // Validate that the entry point is available.
  8270. ASTContext &Ctx = self->getASTContext();
  8271. DiagnosticsEngine &Diags = self->getDiagnostics();
  8272. FunctionDecl *pEntryPointDecl = nullptr;
  8273. FunctionDecl *pPatchFnDecl = nullptr;
  8274. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  8275. if (!EntryPointName.empty()) {
  8276. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  8277. if (NL.Found && NL.Other) {
  8278. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  8279. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  8280. // string, and so ambiguous points will produce an error earlier on.
  8281. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8282. "ambiguous entry point function");
  8283. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  8284. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  8285. return;
  8286. }
  8287. pEntryPointDecl = NL.Found;
  8288. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  8289. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8290. "missing entry point definition");
  8291. Diags.Report(id);
  8292. return;
  8293. }
  8294. }
  8295. // Validate that there is no recursion; start with the entry function.
  8296. // NOTE: the information gathered here could be used to bypass code generation
  8297. // on functions that are unreachable (as an early form of dead code elimination).
  8298. if (pEntryPointDecl) {
  8299. const auto *shaderModel =
  8300. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  8301. if (shaderModel->IsGS()) {
  8302. // Validate that GS has the maxvertexcount attribute
  8303. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  8304. self->Diag(pEntryPointDecl->getLocation(),
  8305. diag::err_hlsl_missing_maxvertexcount_attr);
  8306. return;
  8307. }
  8308. } else if (shaderModel->IsHS()) {
  8309. if (const HLSLPatchConstantFuncAttr *Attr =
  8310. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8311. NameLookup NL = GetSingleFunctionDeclByName(
  8312. self, Attr->getFunctionName(), /*checkPatch*/ true);
  8313. if (!NL.Found || !NL.Found->hasBody()) {
  8314. unsigned id =
  8315. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8316. "missing patch function definition");
  8317. Diags.Report(id);
  8318. return;
  8319. }
  8320. pPatchFnDecl = NL.Found;
  8321. } else {
  8322. self->Diag(pEntryPointDecl->getLocation(),
  8323. diag::err_hlsl_missing_patchconstantfunc_attr);
  8324. return;
  8325. }
  8326. }
  8327. hlsl::CallGraphWithRecurseGuard CG;
  8328. CG.BuildForEntry(pEntryPointDecl);
  8329. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  8330. if (pResult) {
  8331. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8332. "recursive functions not allowed");
  8333. Diags.Report(pResult->getSourceRange().getBegin(), id);
  8334. }
  8335. if (pPatchFnDecl) {
  8336. CG.BuildForEntry(pPatchFnDecl);
  8337. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  8338. if (pPatchFnDecl) {
  8339. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8340. "recursive functions not allowed (via patch function)");
  8341. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  8342. }
  8343. }
  8344. }
  8345. }
  8346. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  8347. Sema& S,
  8348. std::vector<hlsl::UnusualAnnotation *>& annotations)
  8349. {
  8350. bool packoffsetOverriddenReported = false;
  8351. auto && iter = annotations.begin();
  8352. auto && end = annotations.end();
  8353. for (; iter != end; ++iter) {
  8354. switch ((*iter)->getKind()) {
  8355. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8356. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  8357. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  8358. if (!packoffsetOverriddenReported) {
  8359. auto newIter = iter;
  8360. ++newIter;
  8361. while (newIter != end) {
  8362. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  8363. if (other != nullptr &&
  8364. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  8365. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  8366. packoffsetOverriddenReported = true;
  8367. break;
  8368. }
  8369. ++newIter;
  8370. }
  8371. }
  8372. break;
  8373. }
  8374. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8375. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  8376. // Check whether this will conflict with other register assignments of the same type.
  8377. auto newIter = iter;
  8378. ++newIter;
  8379. while (newIter != end) {
  8380. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  8381. // Same register bank and profile, but different number.
  8382. if (other != nullptr &&
  8383. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  8384. other->RegisterType == registerAssignment->RegisterType &&
  8385. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  8386. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  8387. // Obvious conflict - report it up front.
  8388. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  8389. }
  8390. ++newIter;
  8391. }
  8392. break;
  8393. }
  8394. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8395. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  8396. // No common validation to be performed.
  8397. break;
  8398. }
  8399. }
  8400. }
  8401. }
  8402. clang::OverloadingResult
  8403. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  8404. clang::OverloadCandidateSet &set,
  8405. clang::OverloadCandidateSet::iterator &Best) {
  8406. return HLSLExternalSource::FromSema(&S)
  8407. ->GetBestViableFunction(Loc, set, Best);
  8408. }
  8409. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  8410. const InitializedEntity &Entity,
  8411. const InitializationKind &Kind,
  8412. MultiExprArg Args,
  8413. bool TopLevelOfInitList,
  8414. InitializationSequence *initSequence) {
  8415. return HLSLExternalSource::FromSema(self)
  8416. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  8417. }
  8418. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  8419. const clang::InitListExpr *InitList) {
  8420. unsigned totalSize = 0;
  8421. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  8422. const clang::Expr *EltInit = InitList->getInit(i);
  8423. QualType EltInitTy = EltInit->getType();
  8424. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  8425. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  8426. } else {
  8427. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  8428. }
  8429. }
  8430. return totalSize;
  8431. }
  8432. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  8433. _In_ clang::Sema* sema,
  8434. _In_ const clang::InitListExpr *InitList,
  8435. _In_ const clang::QualType EltTy) {
  8436. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  8437. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  8438. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  8439. if (totalSize > 0 && (totalSize % eltSize)==0) {
  8440. return totalSize / eltSize;
  8441. } else {
  8442. return 0;
  8443. }
  8444. }
  8445. bool hlsl::IsConversionToLessOrEqualElements(
  8446. _In_ clang::Sema* self,
  8447. const clang::ExprResult& sourceExpr,
  8448. const clang::QualType& targetType,
  8449. bool explicitConversion)
  8450. {
  8451. return HLSLExternalSource::FromSema(self)
  8452. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  8453. }
  8454. bool hlsl::LookupMatrixMemberExprForHLSL(
  8455. Sema* self,
  8456. Expr& BaseExpr,
  8457. DeclarationName MemberName,
  8458. bool IsArrow,
  8459. SourceLocation OpLoc,
  8460. SourceLocation MemberLoc,
  8461. ExprResult* result)
  8462. {
  8463. return HLSLExternalSource::FromSema(self)
  8464. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8465. }
  8466. bool hlsl::LookupVectorMemberExprForHLSL(
  8467. Sema* self,
  8468. Expr& BaseExpr,
  8469. DeclarationName MemberName,
  8470. bool IsArrow,
  8471. SourceLocation OpLoc,
  8472. SourceLocation MemberLoc,
  8473. ExprResult* result)
  8474. {
  8475. return HLSLExternalSource::FromSema(self)
  8476. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8477. }
  8478. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  8479. _In_ clang::Sema* self,
  8480. _In_ clang::Expr* E)
  8481. {
  8482. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  8483. }
  8484. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  8485. QualType DestType,
  8486. Sema::CheckedConversionKind CCK,
  8487. const SourceRange &OpRange, unsigned &msg,
  8488. CastKind &Kind, CXXCastPath &BasePath,
  8489. bool ListInitialization,
  8490. bool SuppressDiagnostics,
  8491. _Inout_opt_ StandardConversionSequence* standard)
  8492. {
  8493. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  8494. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  8495. SuppressDiagnostics, SuppressDiagnostics, standard);
  8496. }
  8497. clang::ExprResult hlsl::PerformHLSLConversion(
  8498. _In_ clang::Sema* self,
  8499. _In_ clang::Expr* From,
  8500. _In_ clang::QualType targetType,
  8501. _In_ const clang::StandardConversionSequence &SCS,
  8502. _In_ clang::Sema::CheckedConversionKind CCK)
  8503. {
  8504. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  8505. }
  8506. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  8507. _In_ clang::Sema* self,
  8508. _In_ clang::Expr* SrcExpr,
  8509. clang::QualType DestType)
  8510. {
  8511. return HLSLExternalSource::FromSema(self)
  8512. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  8513. }
  8514. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  8515. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  8516. {
  8517. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  8518. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  8519. if (hlslSource->Initialize(context)) {
  8520. context.setExternalSource(externalSource);
  8521. }
  8522. }
  8523. ////////////////////////////////////////////////////////////////////////////////
  8524. // FlattenedTypeIterator implementation //
  8525. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  8526. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  8527. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8528. {
  8529. if (pushTrackerForType(type, nullptr)) {
  8530. considerLeaf();
  8531. }
  8532. }
  8533. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  8534. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  8535. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8536. {
  8537. if (!args.empty()) {
  8538. MultiExprArg::iterator ii = args.begin();
  8539. MultiExprArg::iterator ie = args.end();
  8540. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  8541. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8542. if (!considerLeaf()) {
  8543. m_typeTrackers.clear();
  8544. }
  8545. }
  8546. }
  8547. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  8548. QualType FlattenedTypeIterator::getCurrentElement() const
  8549. {
  8550. return m_typeTrackers.back().Type;
  8551. }
  8552. /// <summary>Get the number of repeated current elements.</summary>
  8553. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  8554. {
  8555. const FlattenedTypeTracker& back = m_typeTrackers.back();
  8556. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  8557. }
  8558. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  8559. bool FlattenedTypeIterator::hasCurrentElement() const
  8560. {
  8561. return m_typeTrackers.size() > 0;
  8562. }
  8563. /// <summary>Consumes count elements on this iterator.</summary>
  8564. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  8565. {
  8566. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8567. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  8568. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8569. if (tracker.IterKind == FK_IncompleteArray)
  8570. {
  8571. tracker.Count += count;
  8572. m_springLoaded = true;
  8573. }
  8574. else
  8575. {
  8576. tracker.Count -= count;
  8577. m_springLoaded = false;
  8578. if (m_typeTrackers.back().Count == 0)
  8579. {
  8580. advanceLeafTracker();
  8581. }
  8582. }
  8583. }
  8584. unsigned int FlattenedTypeIterator::countRemaining()
  8585. {
  8586. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  8587. size_t result = 0;
  8588. while (hasCurrentElement() && !m_springLoaded)
  8589. {
  8590. size_t pending = getCurrentElementSize();
  8591. result += pending;
  8592. advanceCurrentElement(pending);
  8593. }
  8594. return result;
  8595. }
  8596. void FlattenedTypeIterator::advanceLeafTracker()
  8597. {
  8598. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8599. for (;;)
  8600. {
  8601. consumeLeaf();
  8602. if (m_typeTrackers.empty()) {
  8603. return;
  8604. }
  8605. if (considerLeaf()) {
  8606. return;
  8607. }
  8608. }
  8609. }
  8610. bool FlattenedTypeIterator::considerLeaf()
  8611. {
  8612. if (m_typeTrackers.empty()) {
  8613. return false;
  8614. }
  8615. m_typeDepth++;
  8616. if (m_typeDepth > MaxTypeDepth) {
  8617. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  8618. m_typeTrackers.clear();
  8619. m_typeDepth--;
  8620. return false;
  8621. }
  8622. bool result = false;
  8623. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8624. tracker.IsConsidered = true;
  8625. switch (tracker.IterKind) {
  8626. case FlattenedIterKind::FK_Expressions:
  8627. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  8628. result = considerLeaf();
  8629. }
  8630. break;
  8631. case FlattenedIterKind::FK_Fields:
  8632. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  8633. result = considerLeaf();
  8634. } else {
  8635. // Pop empty struct.
  8636. m_typeTrackers.pop_back();
  8637. }
  8638. break;
  8639. case FlattenedIterKind::FK_Bases:
  8640. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  8641. result = considerLeaf();
  8642. } else {
  8643. // Pop empty base.
  8644. m_typeTrackers.pop_back();
  8645. }
  8646. break;
  8647. case FlattenedIterKind::FK_IncompleteArray:
  8648. m_springLoaded = true; // fall through.
  8649. default:
  8650. case FlattenedIterKind::FK_Simple: {
  8651. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  8652. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  8653. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT) {
  8654. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  8655. result = considerLeaf();
  8656. }
  8657. } else {
  8658. result = true;
  8659. }
  8660. }
  8661. }
  8662. m_typeDepth--;
  8663. return result;
  8664. }
  8665. void FlattenedTypeIterator::consumeLeaf()
  8666. {
  8667. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  8668. for (;;) {
  8669. if (m_typeTrackers.empty()) {
  8670. return;
  8671. }
  8672. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8673. // Reach a leaf which is not considered before.
  8674. // Stop here.
  8675. if (!tracker.IsConsidered) {
  8676. break;
  8677. }
  8678. switch (tracker.IterKind) {
  8679. case FlattenedIterKind::FK_Expressions:
  8680. ++tracker.CurrentExpr;
  8681. if (tracker.CurrentExpr == tracker.EndExpr) {
  8682. m_typeTrackers.pop_back();
  8683. topConsumed = false;
  8684. } else {
  8685. return;
  8686. }
  8687. break;
  8688. case FlattenedIterKind::FK_Fields:
  8689. ++tracker.CurrentField;
  8690. if (tracker.CurrentField == tracker.EndField) {
  8691. m_typeTrackers.pop_back();
  8692. topConsumed = false;
  8693. } else {
  8694. return;
  8695. }
  8696. break;
  8697. case FlattenedIterKind::FK_Bases:
  8698. ++tracker.CurrentBase;
  8699. if (tracker.CurrentBase == tracker.EndBase) {
  8700. m_typeTrackers.pop_back();
  8701. topConsumed = false;
  8702. } else {
  8703. return;
  8704. }
  8705. break;
  8706. case FlattenedIterKind::FK_IncompleteArray:
  8707. if (m_draining) {
  8708. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  8709. m_incompleteCount = tracker.Count;
  8710. m_typeTrackers.pop_back();
  8711. }
  8712. return;
  8713. default:
  8714. case FlattenedIterKind::FK_Simple: {
  8715. m_springLoaded = false;
  8716. if (!topConsumed) {
  8717. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  8718. --tracker.Count;
  8719. }
  8720. else {
  8721. topConsumed = false;
  8722. }
  8723. if (tracker.Count == 0) {
  8724. m_typeTrackers.pop_back();
  8725. } else {
  8726. return;
  8727. }
  8728. }
  8729. }
  8730. }
  8731. }
  8732. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  8733. {
  8734. Expr* e = *expression;
  8735. Stmt::StmtClass expressionClass = e->getStmtClass();
  8736. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  8737. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  8738. if (initExpr->getNumInits() == 0) {
  8739. return false;
  8740. }
  8741. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  8742. MultiExprArg::iterator ii = inits.begin();
  8743. MultiExprArg::iterator ie = inits.end();
  8744. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  8745. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8746. return true;
  8747. }
  8748. return pushTrackerForType(e->getType(), expression);
  8749. }
  8750. // TODO: improve this to provide a 'peek' at intermediate types,
  8751. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  8752. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  8753. {
  8754. if (type->isVoidType()) {
  8755. return false;
  8756. }
  8757. if (type->isFunctionType()) {
  8758. return false;
  8759. }
  8760. if (m_firstType.isNull()) {
  8761. m_firstType = type;
  8762. }
  8763. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  8764. QualType elementType;
  8765. unsigned int elementCount;
  8766. const RecordType* recordType;
  8767. RecordDecl::field_iterator fi, fe;
  8768. switch (objectKind)
  8769. {
  8770. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  8771. // TODO: handle multi-dimensional arrays
  8772. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  8773. elementCount = GetArraySize(type);
  8774. if (elementCount == 0) {
  8775. if (type->isIncompleteArrayType()) {
  8776. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  8777. return true;
  8778. }
  8779. return false;
  8780. }
  8781. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8782. elementType, elementCount, nullptr));
  8783. return true;
  8784. case ArTypeObjectKind::AR_TOBJ_BASIC:
  8785. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  8786. return true;
  8787. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  8788. recordType = type->getAsStructureType();
  8789. if (recordType == nullptr)
  8790. recordType = dyn_cast<RecordType>(type.getTypePtr());
  8791. fi = recordType->getDecl()->field_begin();
  8792. fe = recordType->getDecl()->field_end();
  8793. bool bAddTracker = false;
  8794. // Skip empty struct.
  8795. if (fi != fe) {
  8796. m_typeTrackers.push_back(
  8797. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  8798. type = (*fi)->getType();
  8799. bAddTracker = true;
  8800. }
  8801. if (CXXRecordDecl *cxxRecordDecl =
  8802. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  8803. CXXRecordDecl::base_class_iterator bi, be;
  8804. bi = cxxRecordDecl->bases_begin();
  8805. be = cxxRecordDecl->bases_end();
  8806. if (bi != be) {
  8807. // Add type tracker for base.
  8808. // Add base after child to make sure base considered first.
  8809. m_typeTrackers.push_back(
  8810. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  8811. bAddTracker = true;
  8812. }
  8813. }
  8814. return bAddTracker;
  8815. }
  8816. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  8817. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8818. m_source.GetMatrixOrVectorElementType(type),
  8819. GetElementCount(type), nullptr));
  8820. return true;
  8821. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  8822. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8823. m_source.GetMatrixOrVectorElementType(type),
  8824. GetHLSLVecSize(type), nullptr));
  8825. return true;
  8826. case ArTypeObjectKind::AR_TOBJ_OBJECT: {
  8827. // Object have no sub-types.
  8828. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8829. type.getCanonicalType(), 1, expression));
  8830. return true;
  8831. }
  8832. default:
  8833. DXASSERT(false, "unreachable");
  8834. return false;
  8835. }
  8836. }
  8837. FlattenedTypeIterator::ComparisonResult
  8838. FlattenedTypeIterator::CompareIterators(
  8839. HLSLExternalSource& source,
  8840. SourceLocation loc,
  8841. FlattenedTypeIterator& leftIter,
  8842. FlattenedTypeIterator& rightIter)
  8843. {
  8844. FlattenedTypeIterator::ComparisonResult result;
  8845. result.LeftCount = 0;
  8846. result.RightCount = 0;
  8847. result.AreElementsEqual = true; // Until proven otherwise.
  8848. result.CanConvertElements = true; // Until proven otherwise.
  8849. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  8850. {
  8851. Expr* actualExpr = rightIter.getExprOrNull();
  8852. bool hasExpr = actualExpr != nullptr;
  8853. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  8854. StandardConversionSequence standard;
  8855. ExprResult convertedExpr;
  8856. if (!source.CanConvert(loc,
  8857. hasExpr ? actualExpr : &scratchExpr,
  8858. leftIter.getCurrentElement(),
  8859. ExplicitConversionFalse,
  8860. nullptr,
  8861. &standard)) {
  8862. result.AreElementsEqual = false;
  8863. result.CanConvertElements = false;
  8864. break;
  8865. }
  8866. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  8867. {
  8868. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  8869. leftIter.getCurrentElement(),
  8870. standard,
  8871. Sema::AA_Casting,
  8872. Sema::CCK_ImplicitConversion);
  8873. }
  8874. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  8875. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  8876. {
  8877. result.AreElementsEqual = false;
  8878. }
  8879. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  8880. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  8881. // If we need to apply conversions to the expressions, then advance a single element.
  8882. if (hasExpr && convertedExpr.isUsable()) {
  8883. rightIter.replaceExpr(convertedExpr.get());
  8884. advance = 1;
  8885. }
  8886. leftIter.advanceCurrentElement(advance);
  8887. rightIter.advanceCurrentElement(advance);
  8888. result.LeftCount += advance;
  8889. result.RightCount += advance;
  8890. }
  8891. result.LeftCount += leftIter.countRemaining();
  8892. result.RightCount += rightIter.countRemaining();
  8893. return result;
  8894. }
  8895. FlattenedTypeIterator::ComparisonResult
  8896. FlattenedTypeIterator::CompareTypes(
  8897. HLSLExternalSource& source,
  8898. SourceLocation leftLoc, SourceLocation rightLoc,
  8899. QualType left, QualType right)
  8900. {
  8901. FlattenedTypeIterator leftIter(leftLoc, left, source);
  8902. FlattenedTypeIterator rightIter(rightLoc, right, source);
  8903. return CompareIterators(source, leftLoc, leftIter, rightIter);
  8904. }
  8905. FlattenedTypeIterator::ComparisonResult
  8906. FlattenedTypeIterator::CompareTypesForInit(
  8907. HLSLExternalSource& source, QualType left, MultiExprArg args,
  8908. SourceLocation leftLoc, SourceLocation rightLoc)
  8909. {
  8910. FlattenedTypeIterator leftIter(leftLoc, left, source);
  8911. FlattenedTypeIterator rightIter(rightLoc, args, source);
  8912. return CompareIterators(source, leftLoc, leftIter, rightIter);
  8913. }
  8914. ////////////////////////////////////////////////////////////////////////////////
  8915. // Attribute processing support. //
  8916. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  8917. {
  8918. int64_t value = 0;
  8919. if (Attr.getNumArgs() > index)
  8920. {
  8921. Expr *E = nullptr;
  8922. if (!Attr.isArgExpr(index)) {
  8923. // For case arg is constant variable.
  8924. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  8925. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  8926. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  8927. Sema::LookupNameKind::LookupOrdinaryName));
  8928. if (!decl) {
  8929. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8930. return value;
  8931. }
  8932. Expr *init = decl->getInit();
  8933. if (!init) {
  8934. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8935. return value;
  8936. }
  8937. E = init;
  8938. } else
  8939. E = Attr.getArgAsExpr(index);
  8940. clang::APValue ArgNum;
  8941. bool displayError = false;
  8942. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  8943. {
  8944. displayError = true;
  8945. }
  8946. else
  8947. {
  8948. if (ArgNum.isInt())
  8949. {
  8950. value = ArgNum.getInt().getSExtValue();
  8951. }
  8952. else if (ArgNum.isFloat())
  8953. {
  8954. llvm::APSInt floatInt;
  8955. bool isPrecise;
  8956. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  8957. {
  8958. value = floatInt.getSExtValue();
  8959. }
  8960. else
  8961. {
  8962. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8963. }
  8964. }
  8965. else
  8966. {
  8967. displayError = true;
  8968. }
  8969. if (value < 0)
  8970. {
  8971. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8972. }
  8973. }
  8974. if (displayError)
  8975. {
  8976. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  8977. << Attr.getName() << AANT_ArgumentIntegerConstant
  8978. << E->getSourceRange();
  8979. }
  8980. }
  8981. return (int)value;
  8982. }
  8983. // TODO: support float arg directly.
  8984. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  8985. unsigned index = 0) {
  8986. int value = 0;
  8987. if (Attr.getNumArgs() > index) {
  8988. Expr *E = Attr.getArgAsExpr(index);
  8989. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  8990. llvm::APFloat flV = FL->getValue();
  8991. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  8992. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  8993. value = intV.getLimitedValue();
  8994. } else {
  8995. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  8996. value = intV.getLimitedValue();
  8997. }
  8998. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  8999. llvm::APInt intV =
  9000. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  9001. value = intV.getLimitedValue();
  9002. } else {
  9003. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  9004. << Attr.getName();
  9005. }
  9006. }
  9007. return value;
  9008. }
  9009. static Stmt* IgnoreParensAndDecay(Stmt* S)
  9010. {
  9011. for (;;)
  9012. {
  9013. switch (S->getStmtClass())
  9014. {
  9015. case Stmt::ParenExprClass:
  9016. S = cast<ParenExpr>(S)->getSubExpr();
  9017. break;
  9018. case Stmt::ImplicitCastExprClass:
  9019. {
  9020. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  9021. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  9022. castExpr->getCastKind() != CK_NoOp &&
  9023. castExpr->getCastKind() != CK_LValueToRValue)
  9024. {
  9025. return S;
  9026. }
  9027. S = castExpr->getSubExpr();
  9028. }
  9029. break;
  9030. default:
  9031. return S;
  9032. }
  9033. }
  9034. }
  9035. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  9036. {
  9037. DXASSERT_NOMSG(E != nullptr);
  9038. Expr* subscriptExpr = E->getIdx();
  9039. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  9040. if (subscriptExpr == nullptr ||
  9041. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  9042. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  9043. {
  9044. S.Diag(
  9045. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  9046. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  9047. return nullptr;
  9048. }
  9049. return E->getBase();
  9050. }
  9051. static bool IsValidClipPlaneDecl(Decl* D)
  9052. {
  9053. Decl::Kind kind = D->getKind();
  9054. if (kind == Decl::Var)
  9055. {
  9056. VarDecl* varDecl = cast<VarDecl>(D);
  9057. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  9058. varDecl->getType().isConstQualified())
  9059. {
  9060. return false;
  9061. }
  9062. return true;
  9063. }
  9064. else if (kind == Decl::Field)
  9065. {
  9066. return true;
  9067. }
  9068. return false;
  9069. }
  9070. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  9071. {
  9072. Stmt* cursor = E;
  9073. // clip plane expressions are a linear path, so no need to traverse the tree here.
  9074. while (cursor != nullptr)
  9075. {
  9076. bool supported = true;
  9077. cursor = IgnoreParensAndDecay(cursor);
  9078. switch (cursor->getStmtClass())
  9079. {
  9080. case Stmt::ArraySubscriptExprClass:
  9081. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  9082. if (cursor == nullptr)
  9083. {
  9084. // nullptr indicates failure, and the error message has already been printed out
  9085. return nullptr;
  9086. }
  9087. break;
  9088. case Stmt::DeclRefExprClass:
  9089. {
  9090. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  9091. Decl* decl = declRef->getDecl();
  9092. supported = IsValidClipPlaneDecl(decl);
  9093. cursor = supported ? nullptr : cursor;
  9094. }
  9095. break;
  9096. case Stmt::MemberExprClass:
  9097. {
  9098. MemberExpr* member = cast<MemberExpr>(cursor);
  9099. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  9100. cursor = supported ? member->getBase() : cursor;
  9101. }
  9102. break;
  9103. default:
  9104. supported = false;
  9105. break;
  9106. }
  9107. if (!supported)
  9108. {
  9109. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  9110. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  9111. return nullptr;
  9112. }
  9113. }
  9114. // Validate that the type is a float4.
  9115. QualType expressionType = E->getType();
  9116. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  9117. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  9118. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  9119. {
  9120. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  9121. return nullptr;
  9122. }
  9123. return E;
  9124. }
  9125. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  9126. {
  9127. Expr* clipExprs[6];
  9128. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  9129. {
  9130. if (A.getNumArgs() <= index)
  9131. {
  9132. clipExprs[index] = nullptr;
  9133. continue;
  9134. }
  9135. Expr *E = A.getArgAsExpr(index);
  9136. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  9137. }
  9138. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  9139. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  9140. A.getAttributeSpellingListIndex());
  9141. }
  9142. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  9143. {
  9144. int argValue = ValidateAttributeIntArg(S, Attr);
  9145. // Default value is 1.
  9146. if (Attr.getNumArgs() == 0) argValue = 1;
  9147. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  9148. argValue, Attr.getAttributeSpellingListIndex());
  9149. }
  9150. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  9151. {
  9152. Stmt::StmtClass stClass = St->getStmtClass();
  9153. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  9154. {
  9155. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9156. << Attr.getName();
  9157. }
  9158. }
  9159. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  9160. {
  9161. Stmt::StmtClass stClass = St->getStmtClass();
  9162. if (stClass != Stmt::SwitchStmtClass)
  9163. {
  9164. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9165. << Attr.getName();
  9166. }
  9167. }
  9168. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  9169. {
  9170. Stmt::StmtClass stClass = St->getStmtClass();
  9171. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  9172. {
  9173. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9174. << Attr.getName();
  9175. }
  9176. }
  9177. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  9178. {
  9179. // values is an optional comma-separated list of potential values.
  9180. if (A.getNumArgs() <= index)
  9181. return StringRef();
  9182. Expr* E = A.getArgAsExpr(index);
  9183. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  9184. {
  9185. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  9186. << A.getName();
  9187. return StringRef();
  9188. }
  9189. StringLiteral* sl = cast<StringLiteral>(E);
  9190. StringRef result = sl->getString();
  9191. // Return result with no additional validation.
  9192. if (values == nullptr)
  9193. {
  9194. return result;
  9195. }
  9196. const char* value = values;
  9197. while (*value != '\0')
  9198. {
  9199. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  9200. // Look for a match.
  9201. const char* argData = result.data();
  9202. size_t argDataLen = result.size();
  9203. while (argDataLen != 0 && *argData == *value && *value)
  9204. {
  9205. ++argData;
  9206. ++value;
  9207. --argDataLen;
  9208. }
  9209. // Match found if every input character matched.
  9210. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  9211. {
  9212. return result;
  9213. }
  9214. // Move to next separator.
  9215. while (*value != '\0' && *value != ',')
  9216. {
  9217. ++value;
  9218. }
  9219. // Move to the start of the next item if any.
  9220. if (*value == ',') value++;
  9221. }
  9222. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  9223. // No match found.
  9224. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  9225. << A.getName() << values;
  9226. return StringRef();
  9227. }
  9228. static
  9229. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  9230. {
  9231. if (D->isFunctionOrFunctionTemplate())
  9232. {
  9233. return true;
  9234. }
  9235. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  9236. return false;
  9237. }
  9238. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  9239. {
  9240. DXASSERT_NOMSG(D != nullptr);
  9241. DXASSERT_NOMSG(!A.isInvalid());
  9242. Attr* declAttr = nullptr;
  9243. Handled = true;
  9244. switch (A.getKind())
  9245. {
  9246. case AttributeList::AT_HLSLIn:
  9247. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  9248. A.getAttributeSpellingListIndex());
  9249. break;
  9250. case AttributeList::AT_HLSLOut:
  9251. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  9252. A.getAttributeSpellingListIndex());
  9253. break;
  9254. case AttributeList::AT_HLSLInOut:
  9255. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  9256. A.getAttributeSpellingListIndex());
  9257. break;
  9258. case AttributeList::AT_HLSLNoInterpolation:
  9259. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  9260. A.getAttributeSpellingListIndex());
  9261. break;
  9262. case AttributeList::AT_HLSLLinear:
  9263. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  9264. A.getAttributeSpellingListIndex());
  9265. break;
  9266. case AttributeList::AT_HLSLNoPerspective:
  9267. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  9268. A.getAttributeSpellingListIndex());
  9269. break;
  9270. case AttributeList::AT_HLSLSample:
  9271. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  9272. A.getAttributeSpellingListIndex());
  9273. break;
  9274. case AttributeList::AT_HLSLCentroid:
  9275. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  9276. A.getAttributeSpellingListIndex());
  9277. break;
  9278. case AttributeList::AT_HLSLPrecise:
  9279. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  9280. A.getAttributeSpellingListIndex());
  9281. break;
  9282. case AttributeList::AT_HLSLShared:
  9283. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  9284. A.getAttributeSpellingListIndex());
  9285. break;
  9286. case AttributeList::AT_HLSLGroupShared:
  9287. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  9288. A.getAttributeSpellingListIndex());
  9289. break;
  9290. case AttributeList::AT_HLSLUniform:
  9291. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  9292. A.getAttributeSpellingListIndex());
  9293. break;
  9294. case AttributeList::AT_HLSLColumnMajor:
  9295. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  9296. A.getAttributeSpellingListIndex());
  9297. break;
  9298. case AttributeList::AT_HLSLRowMajor:
  9299. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  9300. A.getAttributeSpellingListIndex());
  9301. break;
  9302. case AttributeList::AT_HLSLUnorm:
  9303. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  9304. A.getAttributeSpellingListIndex());
  9305. break;
  9306. case AttributeList::AT_HLSLSnorm:
  9307. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  9308. A.getAttributeSpellingListIndex());
  9309. break;
  9310. case AttributeList::AT_HLSLPoint:
  9311. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  9312. A.getAttributeSpellingListIndex());
  9313. break;
  9314. case AttributeList::AT_HLSLLine:
  9315. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  9316. A.getAttributeSpellingListIndex());
  9317. break;
  9318. case AttributeList::AT_HLSLLineAdj:
  9319. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  9320. A.getAttributeSpellingListIndex());
  9321. break;
  9322. case AttributeList::AT_HLSLTriangle:
  9323. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  9324. A.getAttributeSpellingListIndex());
  9325. break;
  9326. case AttributeList::AT_HLSLTriangleAdj:
  9327. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  9328. A.getAttributeSpellingListIndex());
  9329. break;
  9330. case AttributeList::AT_HLSLGloballyCoherent:
  9331. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  9332. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9333. break;
  9334. default:
  9335. Handled = false;
  9336. break;
  9337. }
  9338. if (declAttr != nullptr)
  9339. {
  9340. DXASSERT_NOMSG(Handled);
  9341. D->addAttr(declAttr);
  9342. return;
  9343. }
  9344. Handled = true;
  9345. switch (A.getKind())
  9346. {
  9347. // These apply to statements, not declarations. The warning messages clarify this properly.
  9348. case AttributeList::AT_HLSLUnroll:
  9349. case AttributeList::AT_HLSLAllowUAVCondition:
  9350. case AttributeList::AT_HLSLLoop:
  9351. case AttributeList::AT_HLSLFastOpt:
  9352. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9353. << A.getName();
  9354. return;
  9355. case AttributeList::AT_HLSLBranch:
  9356. case AttributeList::AT_HLSLFlatten:
  9357. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9358. << A.getName();
  9359. return;
  9360. case AttributeList::AT_HLSLForceCase:
  9361. case AttributeList::AT_HLSLCall:
  9362. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9363. << A.getName();
  9364. return;
  9365. // These are the cases that actually apply to declarations.
  9366. case AttributeList::AT_HLSLClipPlanes:
  9367. declAttr = HandleClipPlanes(S, A);
  9368. break;
  9369. case AttributeList::AT_HLSLDomain:
  9370. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  9371. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  9372. break;
  9373. case AttributeList::AT_HLSLEarlyDepthStencil:
  9374. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9375. break;
  9376. case AttributeList::AT_HLSLInstance:
  9377. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  9378. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9379. break;
  9380. case AttributeList::AT_HLSLMaxTessFactor:
  9381. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  9382. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  9383. break;
  9384. case AttributeList::AT_HLSLNumThreads:
  9385. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  9386. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  9387. A.getAttributeSpellingListIndex());
  9388. break;
  9389. case AttributeList::AT_HLSLRootSignature:
  9390. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  9391. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  9392. A.getAttributeSpellingListIndex());
  9393. break;
  9394. case AttributeList::AT_HLSLOutputControlPoints:
  9395. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  9396. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9397. break;
  9398. case AttributeList::AT_HLSLOutputTopology:
  9399. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  9400. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  9401. break;
  9402. case AttributeList::AT_HLSLPartitioning:
  9403. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  9404. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  9405. break;
  9406. case AttributeList::AT_HLSLPatchConstantFunc:
  9407. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  9408. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  9409. break;
  9410. case AttributeList::AT_HLSLShader:
  9411. declAttr = ::new (S.Context) HLSLShaderAttr(
  9412. A.getRange(), S.Context,
  9413. ValidateAttributeStringArg(S, A,
  9414. "compute,vertex,pixel,hull,domain,geometry,raygeneration,intersection,anyhit,closesthit,miss,callable"),
  9415. A.getAttributeSpellingListIndex());
  9416. break;
  9417. case AttributeList::AT_HLSLMaxVertexCount:
  9418. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  9419. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9420. break;
  9421. case AttributeList::AT_HLSLExperimental:
  9422. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  9423. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  9424. A.getAttributeSpellingListIndex());
  9425. break;
  9426. case AttributeList::AT_NoInline:
  9427. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9428. break;
  9429. default:
  9430. Handled = false;
  9431. break; // SPIRV Change: was return;
  9432. }
  9433. if (declAttr != nullptr)
  9434. {
  9435. DXASSERT_NOMSG(Handled);
  9436. D->addAttr(declAttr);
  9437. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  9438. // and prevent code generation.
  9439. ValidateAttributeTargetIsFunction(S, D, A);
  9440. return; // SPIRV Change
  9441. }
  9442. // SPIRV Change Starts
  9443. Handled = true;
  9444. switch (A.getKind())
  9445. {
  9446. case AttributeList::AT_VKBuiltIn:
  9447. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  9448. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation,BaseVertex,BaseInstance,DrawIndex,DeviceIndex"),
  9449. A.getAttributeSpellingListIndex());
  9450. break;
  9451. case AttributeList::AT_VKLocation:
  9452. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  9453. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9454. break;
  9455. case AttributeList::AT_VKBinding:
  9456. declAttr = ::new (S.Context) VKBindingAttr(A.getRange(), S.Context,
  9457. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1),
  9458. A.getAttributeSpellingListIndex());
  9459. break;
  9460. case AttributeList::AT_VKCounterBinding:
  9461. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  9462. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9463. break;
  9464. case AttributeList::AT_VKPushConstant:
  9465. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  9466. A.getAttributeSpellingListIndex());
  9467. break;
  9468. case AttributeList::AT_VKOffset:
  9469. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  9470. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9471. break;
  9472. case AttributeList::AT_VKInputAttachmentIndex:
  9473. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  9474. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  9475. A.getAttributeSpellingListIndex());
  9476. break;
  9477. case AttributeList::AT_VKConstantId:
  9478. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  9479. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9480. break;
  9481. default:
  9482. Handled = false;
  9483. return;
  9484. }
  9485. if (declAttr != nullptr)
  9486. {
  9487. DXASSERT_NOMSG(Handled);
  9488. D->addAttr(declAttr);
  9489. }
  9490. // SPIRV Change Ends
  9491. }
  9492. /// <summary>Processes an attribute for a statement.</summary>
  9493. /// <param name="S">Sema with context.</param>
  9494. /// <param name="St">Statement annotated.</param>
  9495. /// <param name="A">Single parsed attribute to process.</param>
  9496. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  9497. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  9498. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  9499. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  9500. {
  9501. // | Construct | Allowed Attributes |
  9502. // +------------------+--------------------------------------------+
  9503. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  9504. // | if | branch, flatten |
  9505. // | switch | branch, flatten, forcecase, call |
  9506. Attr * result = nullptr;
  9507. Handled = true;
  9508. switch (A.getKind())
  9509. {
  9510. case AttributeList::AT_HLSLUnroll:
  9511. ValidateAttributeOnLoop(S, St, A);
  9512. result = HandleUnrollAttribute(S, A);
  9513. break;
  9514. case AttributeList::AT_HLSLAllowUAVCondition:
  9515. ValidateAttributeOnLoop(S, St, A);
  9516. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  9517. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9518. break;
  9519. case AttributeList::AT_HLSLLoop:
  9520. ValidateAttributeOnLoop(S, St, A);
  9521. result = ::new (S.Context) HLSLLoopAttr(
  9522. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9523. break;
  9524. case AttributeList::AT_HLSLFastOpt:
  9525. ValidateAttributeOnLoop(S, St, A);
  9526. result = ::new (S.Context) HLSLFastOptAttr(
  9527. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9528. break;
  9529. case AttributeList::AT_HLSLBranch:
  9530. ValidateAttributeOnSwitchOrIf(S, St, A);
  9531. result = ::new (S.Context) HLSLBranchAttr(
  9532. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9533. break;
  9534. case AttributeList::AT_HLSLFlatten:
  9535. ValidateAttributeOnSwitchOrIf(S, St, A);
  9536. result = ::new (S.Context) HLSLFlattenAttr(
  9537. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9538. break;
  9539. case AttributeList::AT_HLSLForceCase:
  9540. ValidateAttributeOnSwitch(S, St, A);
  9541. result = ::new (S.Context) HLSLForceCaseAttr(
  9542. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9543. break;
  9544. case AttributeList::AT_HLSLCall:
  9545. ValidateAttributeOnSwitch(S, St, A);
  9546. result = ::new (S.Context) HLSLCallAttr(
  9547. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9548. break;
  9549. default:
  9550. Handled = false;
  9551. break;
  9552. }
  9553. return result;
  9554. }
  9555. ////////////////////////////////////////////////////////////////////////////////
  9556. // Implementation of Sema members. //
  9557. Decl* Sema::ActOnStartHLSLBuffer(
  9558. Scope* bufferScope,
  9559. bool cbuffer, SourceLocation KwLoc,
  9560. IdentifierInfo *Ident, SourceLocation IdentLoc,
  9561. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  9562. SourceLocation LBrace)
  9563. {
  9564. // For anonymous namespace, take the location of the left brace.
  9565. SourceLocation Loc = Ident ? IdentLoc : LBrace;
  9566. DeclContext* lexicalParent = getCurLexicalContext();
  9567. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9568. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  9569. Ident, IdentLoc, BufferAttributes, LBrace);
  9570. // Keep track of the currently active buffer.
  9571. HLSLBuffers.push_back(result);
  9572. // Validate unusual annotations and emit diagnostics.
  9573. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  9574. auto && unusualIter = BufferAttributes.begin();
  9575. auto && unusualEnd = BufferAttributes.end();
  9576. char expectedRegisterType = cbuffer ? 'b' : 't';
  9577. for (; unusualIter != unusualEnd; ++unusualIter) {
  9578. switch ((*unusualIter)->getKind()) {
  9579. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9580. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  9581. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  9582. break;
  9583. }
  9584. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9585. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  9586. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  9587. Diag(registerAssignment->Loc, cbuffer ? diag::err_hlsl_unsupported_cbuffer_register :
  9588. diag::err_hlsl_unsupported_tbuffer_register);
  9589. } else if (registerAssignment->ShaderProfile.size() > 0) {
  9590. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  9591. }
  9592. break;
  9593. }
  9594. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9595. // Ignore semantic declarations.
  9596. break;
  9597. }
  9598. }
  9599. }
  9600. PushOnScopeChains(result, bufferScope);
  9601. PushDeclContext(bufferScope, result);
  9602. ActOnDocumentableDecl(result);
  9603. return result;
  9604. }
  9605. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  9606. {
  9607. DXASSERT_NOMSG(Dcl != nullptr);
  9608. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9609. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  9610. HLSLBuffers.pop_back();
  9611. PopDeclContext();
  9612. }
  9613. Decl* Sema::getActiveHLSLBuffer() const
  9614. {
  9615. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  9616. }
  9617. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  9618. DeclGroupPtrTy &dcl, bool iscbuf) {
  9619. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9620. HLSLBuffers.pop_back();
  9621. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9622. Decl *decl = dcl.get().getSingleDecl();
  9623. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  9624. IdentifierInfo *Ident = namedDecl->getIdentifier();
  9625. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  9626. SourceLocation Loc = decl->getLocation();
  9627. // Prevent array type in template. The only way to specify an array in the template type
  9628. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  9629. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  9630. QualType declType = cast<VarDecl>(namedDecl)->getType();
  9631. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  9632. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  9633. declType = arrayType->getElementType();
  9634. }
  9635. // Check to make that sure only structs are allowed as parameter types for
  9636. // ConstantBuffer and TextureBuffer.
  9637. if (!declType->isStructureType()) {
  9638. Diag(decl->getLocStart(),
  9639. diag::err_hlsl_typeintemplateargument_requires_struct)
  9640. << declType;
  9641. return nullptr;
  9642. }
  9643. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  9644. DeclContext *lexicalParent = getCurLexicalContext();
  9645. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9646. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  9647. KwLoc, Ident, Loc, hlslAttrs, Loc);
  9648. // set relation
  9649. namedDecl->setDeclContext(result);
  9650. result->addDecl(namedDecl);
  9651. // move attribute from constant to constant buffer
  9652. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  9653. namedDecl->setUnusualAnnotations(hlslAttrs);
  9654. return result;
  9655. }
  9656. bool Sema::IsOnHLSLBufferView() {
  9657. // nullptr will not pushed for cbuffer.
  9658. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  9659. }
  9660. void Sema::ActOnStartHLSLBufferView() {
  9661. // Push nullptr to mark HLSLBufferView.
  9662. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9663. HLSLBuffers.emplace_back(nullptr);
  9664. }
  9665. HLSLBufferDecl::HLSLBufferDecl(
  9666. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  9667. IdentifierInfo *Id, SourceLocation IdLoc,
  9668. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9669. SourceLocation LBrace)
  9670. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  9671. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  9672. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  9673. if (!BufferAttributes.empty()) {
  9674. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9675. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  9676. }
  9677. }
  9678. HLSLBufferDecl *
  9679. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  9680. bool constantbuffer, SourceLocation KwLoc,
  9681. IdentifierInfo *Id, SourceLocation IdLoc,
  9682. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9683. SourceLocation LBrace) {
  9684. DeclContext *DC = C.getTranslationUnitDecl();
  9685. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  9686. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  9687. if (DC != lexicalParent) {
  9688. result->setLexicalDeclContext(lexicalParent);
  9689. }
  9690. return result;
  9691. }
  9692. const char *HLSLBufferDecl::getDeclKindName() const {
  9693. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  9694. "ConstantBuffer"};
  9695. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  9696. return HLSLBufferNames[index];
  9697. }
  9698. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  9699. assert(NewDecl != nullptr);
  9700. if (!getLangOpts().HLSL) {
  9701. return;
  9702. }
  9703. if (!D.UnusualAnnotations.empty()) {
  9704. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9705. getASTContext(), D.UnusualAnnotations.data(),
  9706. D.UnusualAnnotations.size()));
  9707. D.UnusualAnnotations.clear();
  9708. }
  9709. }
  9710. /// Checks whether a usage attribute is compatible with those seen so far and
  9711. /// maintains history.
  9712. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  9713. bool &usageOut) {
  9714. switch (kind) {
  9715. case AttributeList::AT_HLSLIn:
  9716. if (usageIn)
  9717. return false;
  9718. usageIn = true;
  9719. break;
  9720. case AttributeList::AT_HLSLOut:
  9721. if (usageOut)
  9722. return false;
  9723. usageOut = true;
  9724. break;
  9725. default:
  9726. assert(kind == AttributeList::AT_HLSLInOut);
  9727. if (usageOut || usageIn)
  9728. return false;
  9729. usageIn = usageOut = true;
  9730. break;
  9731. }
  9732. return true;
  9733. }
  9734. // Diagnose valid/invalid modifiers for HLSL.
  9735. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC,
  9736. TypeSourceInfo *TInfo, bool isParameter) {
  9737. assert(getLangOpts().HLSL &&
  9738. "otherwise this is called without checking language first");
  9739. // NOTE: some tests may declare templates.
  9740. if (DC->isNamespace() || DC->isDependentContext()) return true;
  9741. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  9742. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  9743. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  9744. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  9745. bool result = true;
  9746. bool isTypedef = storage == DeclSpec::SCS_typedef;
  9747. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  9748. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  9749. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  9750. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  9751. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  9752. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  9753. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  9754. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  9755. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  9756. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  9757. // Function declarations are not allowed in parameter declaration
  9758. // TODO : Remove this check once we support function declarations/pointers in HLSL
  9759. if (isParameter && isFunction) {
  9760. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  9761. D.setInvalidType();
  9762. return false;
  9763. }
  9764. assert(
  9765. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  9766. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  9767. (isParameter ? 1 : 0))
  9768. && "exactly one type of declarator is being processed");
  9769. // qt/pType captures either the type being modified, or the return type in the
  9770. // case of a function (or method).
  9771. QualType qt = TInfo->getType();
  9772. const Type* pType = qt.getTypePtrOrNull();
  9773. // Early checks - these are not simple attribution errors, but constructs that
  9774. // are fundamentally unsupported,
  9775. // and so we avoid errors that might indicate they can be repaired.
  9776. if (DC->isRecord()) {
  9777. unsigned int nestedDiagId = 0;
  9778. if (isTypedef) {
  9779. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  9780. }
  9781. if (nestedDiagId) {
  9782. Diag(D.getLocStart(), nestedDiagId);
  9783. D.setInvalidType();
  9784. return false;
  9785. }
  9786. }
  9787. const char* declarationType =
  9788. (isLocalVar) ? "local variable" :
  9789. (isTypedef) ? "typedef" :
  9790. (isFunction) ? "function" :
  9791. (isMethod) ? "method" :
  9792. (isGlobal) ? "global variable" :
  9793. (isParameter) ? "parameter" :
  9794. (isField) ? "field" : "<unknown>";
  9795. if (pType && D.isFunctionDeclarator()) {
  9796. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  9797. if (pFP) {
  9798. qt = pFP->getReturnType();
  9799. pType = qt.getTypePtrOrNull();
  9800. }
  9801. }
  9802. // Check for deprecated effect object type here, warn, and invalidate decl
  9803. bool bDeprecatedEffectObject = false;
  9804. bool bIsObject = false;
  9805. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  9806. bIsObject = true;
  9807. if (bDeprecatedEffectObject) {
  9808. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  9809. D.setInvalidType();
  9810. return false;
  9811. }
  9812. // Add methods if not ready.
  9813. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9814. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  9815. } else if (qt->isArrayType()) {
  9816. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  9817. while (eltQt->isArrayType())
  9818. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  9819. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  9820. // Add methods if not ready.
  9821. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9822. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  9823. }
  9824. }
  9825. if (isExtern) {
  9826. if (!(isFunction || isGlobal)) {
  9827. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  9828. << declarationType;
  9829. result = false;
  9830. }
  9831. }
  9832. if (isStatic) {
  9833. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  9834. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  9835. << declarationType;
  9836. result = false;
  9837. }
  9838. }
  9839. if (isVolatile) {
  9840. if (!(isLocalVar || isTypedef)) {
  9841. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  9842. << declarationType;
  9843. result = false;
  9844. }
  9845. }
  9846. if (isConst) {
  9847. if (isField && !isStatic) {
  9848. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  9849. << declarationType;
  9850. result = false;
  9851. }
  9852. }
  9853. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9854. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  9855. if (hasSignSpec) {
  9856. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  9857. // vectors or matrices can only have unsigned integer types.
  9858. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  9859. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  9860. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  9861. << g_ArBasicTypeNames[basicKind];
  9862. result = false;
  9863. }
  9864. }
  9865. else {
  9866. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  9867. result = false;
  9868. }
  9869. }
  9870. // Validate attributes
  9871. clang::AttributeList
  9872. *pPrecise = nullptr,
  9873. *pShared = nullptr,
  9874. *pGroupShared = nullptr,
  9875. *pUniform = nullptr,
  9876. *pUsage = nullptr,
  9877. *pNoInterpolation = nullptr,
  9878. *pLinear = nullptr,
  9879. *pNoPerspective = nullptr,
  9880. *pSample = nullptr,
  9881. *pCentroid = nullptr,
  9882. *pAnyLinear = nullptr, // first linear attribute found
  9883. *pTopology = nullptr;
  9884. bool usageIn = false;
  9885. bool usageOut = false;
  9886. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  9887. pAttr != NULL; pAttr = pAttr->getNext()) {
  9888. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  9889. continue;
  9890. switch (pAttr->getKind()) {
  9891. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  9892. pPrecise = pAttr;
  9893. break;
  9894. case AttributeList::AT_HLSLShared:
  9895. if (!isGlobal) {
  9896. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9897. << pAttr->getName() << declarationType << pAttr->getRange();
  9898. result = false;
  9899. }
  9900. if (isStatic) {
  9901. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9902. << "'static'" << pAttr->getName() << declarationType
  9903. << pAttr->getRange();
  9904. result = false;
  9905. }
  9906. pShared = pAttr;
  9907. break;
  9908. case AttributeList::AT_HLSLGroupShared:
  9909. if (!isGlobal) {
  9910. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9911. << pAttr->getName() << declarationType << pAttr->getRange();
  9912. result = false;
  9913. }
  9914. if (isExtern) {
  9915. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9916. << "'extern'" << pAttr->getName() << declarationType
  9917. << pAttr->getRange();
  9918. result = false;
  9919. }
  9920. pGroupShared = pAttr;
  9921. break;
  9922. case AttributeList::AT_HLSLGloballyCoherent:
  9923. if (!bIsObject) {
  9924. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9925. << pAttr->getName() << "non-UAV type";
  9926. result = false;
  9927. }
  9928. break;
  9929. case AttributeList::AT_HLSLUniform:
  9930. if (!(isGlobal || isParameter)) {
  9931. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9932. << pAttr->getName() << declarationType << pAttr->getRange();
  9933. result = false;
  9934. }
  9935. if (isStatic) {
  9936. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9937. << "'static'" << pAttr->getName() << declarationType
  9938. << pAttr->getRange();
  9939. result = false;
  9940. }
  9941. pUniform = pAttr;
  9942. break;
  9943. case AttributeList::AT_HLSLIn:
  9944. case AttributeList::AT_HLSLOut:
  9945. case AttributeList::AT_HLSLInOut:
  9946. if (!isParameter) {
  9947. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  9948. << pAttr->getName() << pAttr->getRange();
  9949. result = false;
  9950. }
  9951. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  9952. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  9953. << pAttr->getName() << pAttr->getRange();
  9954. result = false;
  9955. }
  9956. pUsage = pAttr;
  9957. break;
  9958. case AttributeList::AT_HLSLNoInterpolation:
  9959. if (!(isParameter || isField || isFunction)) {
  9960. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9961. << pAttr->getName() << declarationType << pAttr->getRange();
  9962. result = false;
  9963. }
  9964. if (pNoInterpolation) {
  9965. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9966. << pAttr->getName() << pAttr->getRange();
  9967. }
  9968. pNoInterpolation = pAttr;
  9969. break;
  9970. case AttributeList::AT_HLSLLinear:
  9971. case AttributeList::AT_HLSLNoPerspective:
  9972. case AttributeList::AT_HLSLSample:
  9973. case AttributeList::AT_HLSLCentroid:
  9974. if (!(isParameter || isField || isFunction)) {
  9975. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9976. << pAttr->getName() << declarationType << pAttr->getRange();
  9977. result = false;
  9978. }
  9979. if (nullptr == pAnyLinear)
  9980. pAnyLinear = pAttr;
  9981. switch (pAttr->getKind()) {
  9982. case AttributeList::AT_HLSLLinear:
  9983. if (pLinear) {
  9984. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9985. << pAttr->getName() << pAttr->getRange();
  9986. }
  9987. pLinear = pAttr;
  9988. break;
  9989. case AttributeList::AT_HLSLNoPerspective:
  9990. if (pNoPerspective) {
  9991. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9992. << pAttr->getName() << pAttr->getRange();
  9993. }
  9994. pNoPerspective = pAttr;
  9995. break;
  9996. case AttributeList::AT_HLSLSample:
  9997. if (pSample) {
  9998. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9999. << pAttr->getName() << pAttr->getRange();
  10000. }
  10001. pSample = pAttr;
  10002. break;
  10003. case AttributeList::AT_HLSLCentroid:
  10004. if (pCentroid) {
  10005. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10006. << pAttr->getName() << pAttr->getRange();
  10007. }
  10008. pCentroid = pAttr;
  10009. break;
  10010. }
  10011. break;
  10012. case AttributeList::AT_HLSLPoint:
  10013. case AttributeList::AT_HLSLLine:
  10014. case AttributeList::AT_HLSLLineAdj:
  10015. case AttributeList::AT_HLSLTriangle:
  10016. case AttributeList::AT_HLSLTriangleAdj:
  10017. if (!(isParameter)) {
  10018. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10019. << pAttr->getName() << declarationType << pAttr->getRange();
  10020. result = false;
  10021. }
  10022. if (pTopology) {
  10023. if (pTopology->getKind() == pAttr->getKind()) {
  10024. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10025. << pAttr->getName() << pAttr->getRange();
  10026. } else {
  10027. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10028. << pAttr->getName() << pTopology->getName()
  10029. << declarationType << pAttr->getRange();
  10030. result = false;
  10031. }
  10032. }
  10033. pTopology = pAttr;
  10034. break;
  10035. default:
  10036. break;
  10037. }
  10038. }
  10039. if (pNoInterpolation && pAnyLinear) {
  10040. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10041. << pNoInterpolation->getName() << pAnyLinear->getName()
  10042. << declarationType << pNoInterpolation->getRange();
  10043. result = false;
  10044. }
  10045. if (pSample && pCentroid) {
  10046. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  10047. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  10048. }
  10049. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  10050. pNoInterpolation ? pNoInterpolation : pTopology);
  10051. if (pUniform && pNonUniformAttr) {
  10052. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10053. << pNonUniformAttr->getName()
  10054. << pUniform->getName() << declarationType << pUniform->getRange();
  10055. result = false;
  10056. }
  10057. if (pAnyLinear && pTopology) {
  10058. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  10059. << pTopology->getName()
  10060. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  10061. result = false;
  10062. }
  10063. if (pNoInterpolation && pTopology) {
  10064. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10065. << pTopology->getName()
  10066. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  10067. result = false;
  10068. }
  10069. if (pUniform && pUsage) {
  10070. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  10071. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10072. << pUsage->getName() << pUniform->getName() << declarationType
  10073. << pUniform->getRange();
  10074. result = false;
  10075. }
  10076. }
  10077. // Validate that stream-ouput objects are marked as inout
  10078. if (isParameter && !(usageIn && usageOut) &&
  10079. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  10080. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  10081. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  10082. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  10083. result = false;
  10084. }
  10085. // SPIRV change starts
  10086. #ifdef ENABLE_SPIRV_CODEGEN
  10087. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  10088. if (!getLangOpts().SPIRV) {
  10089. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  10090. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  10091. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  10092. << g_ArBasicTypeNames[basicKind];
  10093. result = false;
  10094. }
  10095. }
  10096. #endif // ENABLE_SPIRV_CODEGEN
  10097. // SPIRV change ends
  10098. // Validate unusual annotations.
  10099. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  10100. auto && unusualIter = D.UnusualAnnotations.begin();
  10101. auto && unusualEnd = D.UnusualAnnotations.end();
  10102. for (; unusualIter != unusualEnd; ++unusualIter) {
  10103. switch ((*unusualIter)->getKind()) {
  10104. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10105. hlsl::ConstantPacking *constantPacking =
  10106. cast<hlsl::ConstantPacking>(*unusualIter);
  10107. if (!isGlobal || HLSLBuffers.size() == 0) {
  10108. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  10109. continue;
  10110. }
  10111. if (constantPacking->ComponentOffset > 0) {
  10112. // Validate that this will fit.
  10113. if (!qt.isNull()) {
  10114. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  10115. constantPacking->ComponentOffset);
  10116. }
  10117. }
  10118. break;
  10119. }
  10120. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10121. hlsl::RegisterAssignment *registerAssignment =
  10122. cast<hlsl::RegisterAssignment>(*unusualIter);
  10123. if (registerAssignment->IsValid) {
  10124. if (!qt.isNull()) {
  10125. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  10126. registerAssignment->RegisterType);
  10127. }
  10128. }
  10129. break;
  10130. }
  10131. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10132. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  10133. if (isTypedef || isLocalVar) {
  10134. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  10135. << "semantic" << declarationType;
  10136. }
  10137. break;
  10138. }
  10139. }
  10140. }
  10141. if (!result) {
  10142. D.setInvalidType();
  10143. }
  10144. return result;
  10145. }
  10146. // Diagnose HLSL types on lookup
  10147. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  10148. const DeclarationNameInfo declName = R.getLookupNameInfo();
  10149. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  10150. if (idInfo) {
  10151. StringRef nameIdentifier = idInfo->getName();
  10152. HLSLScalarType parsedType;
  10153. int rowCount, colCount;
  10154. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  10155. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  10156. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  10157. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  10158. }
  10159. }
  10160. return true;
  10161. }
  10162. static QualType getUnderlyingType(QualType Type)
  10163. {
  10164. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  10165. {
  10166. if (const TypedefNameDecl* pDecl = TD->getDecl())
  10167. Type = pDecl->getUnderlyingType();
  10168. else
  10169. break;
  10170. }
  10171. return Type;
  10172. }
  10173. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  10174. /// <param name="self">Sema with context.</param>
  10175. /// <param name="type">QualType to inspect.</param>
  10176. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  10177. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  10178. void hlsl::GetHLSLAttributedTypes(
  10179. _In_ clang::Sema* self,
  10180. clang::QualType type,
  10181. _Inout_opt_ const clang::AttributedType** ppMatrixOrientation,
  10182. _Inout_opt_ const clang::AttributedType** ppNorm)
  10183. {
  10184. if (ppMatrixOrientation)
  10185. *ppMatrixOrientation = nullptr;
  10186. if (ppNorm)
  10187. *ppNorm = nullptr;
  10188. // Note: we clear output pointers once set so we can stop searching
  10189. QualType Desugared = getUnderlyingType(type);
  10190. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  10191. while (AT && (ppMatrixOrientation || ppNorm)) {
  10192. AttributedType::Kind Kind = AT->getAttrKind();
  10193. if (Kind == AttributedType::attr_hlsl_row_major ||
  10194. Kind == AttributedType::attr_hlsl_column_major)
  10195. {
  10196. if (ppMatrixOrientation)
  10197. {
  10198. *ppMatrixOrientation = AT;
  10199. ppMatrixOrientation = nullptr;
  10200. }
  10201. }
  10202. else if (Kind == AttributedType::attr_hlsl_unorm ||
  10203. Kind == AttributedType::attr_hlsl_snorm)
  10204. {
  10205. if (ppNorm)
  10206. {
  10207. *ppNorm = AT;
  10208. ppNorm = nullptr;
  10209. }
  10210. }
  10211. Desugared = getUnderlyingType(AT->getEquivalentType());
  10212. AT = dyn_cast<AttributedType>(Desugared);
  10213. }
  10214. // Unwrap component type on vector or matrix and check snorm/unorm
  10215. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  10216. AT = dyn_cast<AttributedType>(Desugared);
  10217. while (AT && ppNorm) {
  10218. AttributedType::Kind Kind = AT->getAttrKind();
  10219. if (Kind == AttributedType::attr_hlsl_unorm ||
  10220. Kind == AttributedType::attr_hlsl_snorm)
  10221. {
  10222. *ppNorm = AT;
  10223. ppNorm = nullptr;
  10224. }
  10225. Desugared = getUnderlyingType(AT->getEquivalentType());
  10226. AT = dyn_cast<AttributedType>(Desugared);
  10227. }
  10228. }
  10229. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  10230. /// <param name="self">Sema with context.</param>
  10231. /// <param name="type">QualType to check.</param>
  10232. bool hlsl::IsMatrixType(
  10233. _In_ clang::Sema* self,
  10234. _In_ clang::QualType type)
  10235. {
  10236. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  10237. }
  10238. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  10239. /// <param name="self">Sema with context.</param>
  10240. /// <param name="type">QualType to check.</param>
  10241. bool hlsl::IsVectorType(
  10242. _In_ clang::Sema* self,
  10243. _In_ clang::QualType type)
  10244. {
  10245. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  10246. }
  10247. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  10248. /// <param name="self">Sema with context.</param>
  10249. /// <param name="type">Matrix or Vector type.</param>
  10250. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  10251. _In_ clang::QualType type)
  10252. {
  10253. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  10254. // without losing the AttributedType on the template parameter
  10255. if (const Type* pType = type.getTypePtrOrNull()) {
  10256. // A non-dependent template specialization type is always "sugar",
  10257. // typically for a RecordType. For example, a class template
  10258. // specialization type of @c vector<int> will refer to a tag type for
  10259. // the instantiation @c std::vector<int, std::allocator<int>>.
  10260. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  10261. // If we have enough arguments, pull them from the template directly, rather than doing
  10262. // the extra lookups.
  10263. if (pTemplate->getNumArgs() > 0)
  10264. return pTemplate->getArg(0).getAsType();
  10265. QualType templateRecord = pTemplate->desugar();
  10266. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  10267. if (pTemplateRecordType) {
  10268. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  10269. if (pTemplateTagType) {
  10270. const ClassTemplateSpecializationDecl *specializationDecl =
  10271. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  10272. pTemplateTagType->getDecl());
  10273. if (specializationDecl) {
  10274. return specializationDecl->getTemplateArgs()[0].getAsType();
  10275. }
  10276. }
  10277. }
  10278. }
  10279. }
  10280. return QualType();
  10281. }
  10282. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  10283. /// <param name="self">Sema with context.</param>
  10284. /// <param name="type">Input type.</param>
  10285. clang::QualType hlsl::GetOriginalElementType(
  10286. _In_ clang::Sema* self,
  10287. _In_ clang::QualType type)
  10288. {
  10289. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  10290. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  10291. return GetOriginalMatrixOrVectorElementType(type);
  10292. }
  10293. return type;
  10294. }
  10295. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  10296. switch (A->getKind()) {
  10297. // Parameter modifiers
  10298. case clang::attr::HLSLIn:
  10299. Out << "in ";
  10300. break;
  10301. case clang::attr::HLSLInOut:
  10302. Out << "inout ";
  10303. break;
  10304. case clang::attr::HLSLOut:
  10305. Out << "out ";
  10306. break;
  10307. // Interpolation modifiers
  10308. case clang::attr::HLSLLinear:
  10309. Out << "linear ";
  10310. break;
  10311. case clang::attr::HLSLCentroid:
  10312. Out << "centroid ";
  10313. break;
  10314. case clang::attr::HLSLNoInterpolation:
  10315. Out << "nointerpolation ";
  10316. break;
  10317. case clang::attr::HLSLNoPerspective:
  10318. Out << "noperspective ";
  10319. break;
  10320. case clang::attr::HLSLSample:
  10321. Out << "sample ";
  10322. break;
  10323. // Function attributes
  10324. case clang::attr::HLSLClipPlanes:
  10325. {
  10326. Attr * noconst = const_cast<Attr*>(A);
  10327. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  10328. if (!ACast->getClipPlane1())
  10329. break;
  10330. Indent(Indentation, Out);
  10331. Out << "[clipplanes(";
  10332. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  10333. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  10334. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  10335. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  10336. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  10337. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  10338. Out << ")]\n";
  10339. break;
  10340. }
  10341. case clang::attr::HLSLDomain:
  10342. {
  10343. Attr * noconst = const_cast<Attr*>(A);
  10344. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  10345. Indent(Indentation, Out);
  10346. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  10347. break;
  10348. }
  10349. case clang::attr::HLSLEarlyDepthStencil:
  10350. Indent(Indentation, Out);
  10351. Out << "[earlydepthstencil]\n";
  10352. break;
  10353. case clang::attr::HLSLInstance: //TODO - test
  10354. {
  10355. Attr * noconst = const_cast<Attr*>(A);
  10356. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  10357. Indent(Indentation, Out);
  10358. Out << "[instance(" << ACast->getCount() << ")]\n";
  10359. break;
  10360. }
  10361. case clang::attr::HLSLMaxTessFactor: //TODO - test
  10362. {
  10363. Attr * noconst = const_cast<Attr*>(A);
  10364. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  10365. Indent(Indentation, Out);
  10366. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  10367. break;
  10368. }
  10369. case clang::attr::HLSLNumThreads: //TODO - test
  10370. {
  10371. Attr * noconst = const_cast<Attr*>(A);
  10372. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  10373. Indent(Indentation, Out);
  10374. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  10375. break;
  10376. }
  10377. case clang::attr::HLSLRootSignature:
  10378. {
  10379. Attr * noconst = const_cast<Attr*>(A);
  10380. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  10381. Indent(Indentation, Out);
  10382. Out << "[RootSignature(" << ACast->getSignatureName() << ")]\n";
  10383. break;
  10384. }
  10385. case clang::attr::HLSLOutputControlPoints:
  10386. {
  10387. Attr * noconst = const_cast<Attr*>(A);
  10388. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  10389. Indent(Indentation, Out);
  10390. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  10391. break;
  10392. }
  10393. case clang::attr::HLSLOutputTopology:
  10394. {
  10395. Attr * noconst = const_cast<Attr*>(A);
  10396. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  10397. Indent(Indentation, Out);
  10398. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  10399. break;
  10400. }
  10401. case clang::attr::HLSLPartitioning:
  10402. {
  10403. Attr * noconst = const_cast<Attr*>(A);
  10404. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  10405. Indent(Indentation, Out);
  10406. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  10407. break;
  10408. }
  10409. case clang::attr::HLSLPatchConstantFunc:
  10410. {
  10411. Attr * noconst = const_cast<Attr*>(A);
  10412. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  10413. Indent(Indentation, Out);
  10414. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  10415. break;
  10416. }
  10417. case clang::attr::HLSLShader:
  10418. {
  10419. Attr * noconst = const_cast<Attr*>(A);
  10420. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  10421. Indent(Indentation, Out);
  10422. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  10423. break;
  10424. }
  10425. case clang::attr::HLSLExperimental:
  10426. {
  10427. Attr * noconst = const_cast<Attr*>(A);
  10428. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  10429. Indent(Indentation, Out);
  10430. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  10431. break;
  10432. }
  10433. case clang::attr::HLSLMaxVertexCount:
  10434. {
  10435. Attr * noconst = const_cast<Attr*>(A);
  10436. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  10437. Indent(Indentation, Out);
  10438. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  10439. break;
  10440. }
  10441. case clang::attr::NoInline:
  10442. Indent(Indentation, Out);
  10443. Out << "[noinline]\n";
  10444. break;
  10445. // Statement attributes
  10446. case clang::attr::HLSLAllowUAVCondition:
  10447. Indent(Indentation, Out);
  10448. Out << "[allow_uav_condition]\n";
  10449. break;
  10450. case clang::attr::HLSLBranch:
  10451. Indent(Indentation, Out);
  10452. Out << "[branch]\n";
  10453. break;
  10454. case clang::attr::HLSLCall:
  10455. Indent(Indentation, Out);
  10456. Out << "[call]\n";
  10457. break;
  10458. case clang::attr::HLSLFastOpt:
  10459. Indent(Indentation, Out);
  10460. Out << "[fastopt]\n";
  10461. break;
  10462. case clang::attr::HLSLFlatten:
  10463. Indent(Indentation, Out);
  10464. Out << "[flatten]\n";
  10465. break;
  10466. case clang::attr::HLSLForceCase:
  10467. Indent(Indentation, Out);
  10468. Out << "[forcecase]\n";
  10469. break;
  10470. case clang::attr::HLSLLoop:
  10471. Indent(Indentation, Out);
  10472. Out << "[loop]\n";
  10473. break;
  10474. case clang::attr::HLSLUnroll:
  10475. {
  10476. Attr * noconst = const_cast<Attr*>(A);
  10477. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  10478. Indent(Indentation, Out);
  10479. Out << "[unroll(" << ACast->getCount() << ")]\n";
  10480. break;
  10481. }
  10482. // Variable modifiers
  10483. case clang::attr::HLSLGroupShared:
  10484. Out << "groupshared ";
  10485. break;
  10486. case clang::attr::HLSLPrecise:
  10487. Out << "precise ";
  10488. break;
  10489. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  10490. break;
  10491. case clang::attr::HLSLShared:
  10492. Out << "shared ";
  10493. break;
  10494. case clang::attr::HLSLUniform:
  10495. Out << "uniform ";
  10496. break;
  10497. // These four cases are printed in TypePrinter::printAttributedBefore
  10498. case clang::attr::HLSLColumnMajor:
  10499. case clang::attr::HLSLRowMajor:
  10500. case clang::attr::HLSLSnorm:
  10501. case clang::attr::HLSLUnorm:
  10502. break;
  10503. case clang::attr::HLSLPoint:
  10504. Out << "point ";
  10505. break;
  10506. case clang::attr::HLSLLine:
  10507. Out << "line ";
  10508. break;
  10509. case clang::attr::HLSLLineAdj:
  10510. Out << "lineadj ";
  10511. break;
  10512. case clang::attr::HLSLTriangle:
  10513. Out << "triangle ";
  10514. break;
  10515. case clang::attr::HLSLTriangleAdj:
  10516. Out << "triangleadj ";
  10517. break;
  10518. case clang::attr::HLSLGloballyCoherent:
  10519. Out << "globallycoherent ";
  10520. break;
  10521. default:
  10522. A->printPretty(Out, Policy);
  10523. break;
  10524. }
  10525. }
  10526. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  10527. switch (AttrKind){
  10528. case clang::attr::HLSLAllowUAVCondition:
  10529. case clang::attr::HLSLBranch:
  10530. case clang::attr::HLSLCall:
  10531. case clang::attr::HLSLCentroid:
  10532. case clang::attr::HLSLClipPlanes:
  10533. case clang::attr::HLSLColumnMajor:
  10534. case clang::attr::HLSLDomain:
  10535. case clang::attr::HLSLEarlyDepthStencil:
  10536. case clang::attr::HLSLFastOpt:
  10537. case clang::attr::HLSLFlatten:
  10538. case clang::attr::HLSLForceCase:
  10539. case clang::attr::HLSLGroupShared:
  10540. case clang::attr::HLSLIn:
  10541. case clang::attr::HLSLInOut:
  10542. case clang::attr::HLSLInstance:
  10543. case clang::attr::HLSLLinear:
  10544. case clang::attr::HLSLLoop:
  10545. case clang::attr::HLSLMaxTessFactor:
  10546. case clang::attr::HLSLNoInterpolation:
  10547. case clang::attr::HLSLNoPerspective:
  10548. case clang::attr::HLSLNumThreads:
  10549. case clang::attr::HLSLRootSignature:
  10550. case clang::attr::HLSLOut:
  10551. case clang::attr::HLSLOutputControlPoints:
  10552. case clang::attr::HLSLOutputTopology:
  10553. case clang::attr::HLSLPartitioning:
  10554. case clang::attr::HLSLPatchConstantFunc:
  10555. case clang::attr::HLSLMaxVertexCount:
  10556. case clang::attr::HLSLPrecise:
  10557. case clang::attr::HLSLRowMajor:
  10558. case clang::attr::HLSLSample:
  10559. case clang::attr::HLSLSemantic:
  10560. case clang::attr::HLSLShared:
  10561. case clang::attr::HLSLSnorm:
  10562. case clang::attr::HLSLUniform:
  10563. case clang::attr::HLSLUnorm:
  10564. case clang::attr::HLSLUnroll:
  10565. case clang::attr::HLSLPoint:
  10566. case clang::attr::HLSLLine:
  10567. case clang::attr::HLSLLineAdj:
  10568. case clang::attr::HLSLTriangle:
  10569. case clang::attr::HLSLTriangleAdj:
  10570. case clang::attr::HLSLGloballyCoherent:
  10571. case clang::attr::NoInline:
  10572. return true;
  10573. }
  10574. return false;
  10575. }
  10576. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  10577. if (ClipPlane) {
  10578. Out << ", ";
  10579. ClipPlane->printPretty(Out, 0, Policy);
  10580. }
  10581. }
  10582. bool hlsl::IsObjectType(
  10583. _In_ clang::Sema* self,
  10584. _In_ clang::QualType type,
  10585. _Inout_opt_ bool *isDeprecatedEffectObject)
  10586. {
  10587. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  10588. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  10589. if (isDeprecatedEffectObject)
  10590. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  10591. return true;
  10592. }
  10593. if (isDeprecatedEffectObject)
  10594. *isDeprecatedEffectObject = false;
  10595. return false;
  10596. }
  10597. bool hlsl::CanConvert(
  10598. _In_ clang::Sema* self,
  10599. clang::SourceLocation loc,
  10600. _In_ clang::Expr* sourceExpr,
  10601. clang::QualType target,
  10602. bool explicitConversion,
  10603. _Inout_opt_ clang::StandardConversionSequence* standard)
  10604. {
  10605. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  10606. }
  10607. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  10608. {
  10609. for (unsigned i = 0; i != Indentation; ++i)
  10610. Out << " ";
  10611. }
  10612. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  10613. {
  10614. DXASSERT_NOMSG(self != nullptr);
  10615. DXASSERT_NOMSG(table != nullptr);
  10616. HLSLExternalSource* source = (HLSLExternalSource*)self;
  10617. source->RegisterIntrinsicTable(table);
  10618. }
  10619. clang::QualType hlsl::CheckVectorConditional(
  10620. _In_ clang::Sema* self,
  10621. _In_ clang::ExprResult &Cond,
  10622. _In_ clang::ExprResult &LHS,
  10623. _In_ clang::ExprResult &RHS,
  10624. _In_ clang::SourceLocation QuestionLoc)
  10625. {
  10626. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  10627. }
  10628. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  10629. UINT count;
  10630. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  10631. }
  10632. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  10633. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  10634. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  10635. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  10636. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  10637. llvm::APSInt index;
  10638. if (RHS->EvaluateAsInt(index, Context)) {
  10639. int64_t intIndex = index.getLimitedValue();
  10640. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  10641. if (IsVectorType(this, LHSQualType)) {
  10642. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  10643. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  10644. // we also have to check the first subscript oprator by recursively calling
  10645. // this funciton for the first CXXOperatorCallExpr
  10646. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  10647. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  10648. }
  10649. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  10650. Diag(RHS->getExprLoc(),
  10651. diag::err_hlsl_vector_element_index_out_of_bounds)
  10652. << (int)intIndex;
  10653. }
  10654. }
  10655. else if (IsMatrixType(this, LHSQualType)) {
  10656. uint32_t rowCount, colCount;
  10657. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  10658. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  10659. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  10660. << (int)intIndex;
  10661. }
  10662. }
  10663. }
  10664. }
  10665. clang::QualType ApplyTypeSpecSignToParsedType(
  10666. _In_ clang::Sema* self,
  10667. _In_ clang::QualType &type,
  10668. _In_ clang::TypeSpecifierSign TSS,
  10669. _In_ clang::SourceLocation Loc
  10670. )
  10671. {
  10672. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  10673. }