SemaHLSL.cpp 431 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503
  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 "clang/Sema/SemaHLSL.h"
  33. #include "dxc/Support/Global.h"
  34. #include "dxc/Support/WinIncludes.h"
  35. #include "dxc/Support/WinAdapter.h"
  36. #include "dxc/dxcapi.internal.h"
  37. #include "dxc/HlslIntrinsicOp.h"
  38. #include "gen_intrin_main_tables_15.h"
  39. #include "dxc/HLSL/HLOperations.h"
  40. #include "dxc/DXIL/DxilShaderModel.h"
  41. #include <array>
  42. #include <float.h>
  43. enum ArBasicKind {
  44. AR_BASIC_BOOL,
  45. AR_BASIC_LITERAL_FLOAT,
  46. AR_BASIC_FLOAT16,
  47. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  48. AR_BASIC_FLOAT32,
  49. AR_BASIC_FLOAT64,
  50. AR_BASIC_LITERAL_INT,
  51. AR_BASIC_INT8,
  52. AR_BASIC_UINT8,
  53. AR_BASIC_INT16,
  54. AR_BASIC_UINT16,
  55. AR_BASIC_INT32,
  56. AR_BASIC_UINT32,
  57. AR_BASIC_INT64,
  58. AR_BASIC_UINT64,
  59. AR_BASIC_MIN10FLOAT,
  60. AR_BASIC_MIN16FLOAT,
  61. AR_BASIC_MIN12INT,
  62. AR_BASIC_MIN16INT,
  63. AR_BASIC_MIN16UINT,
  64. AR_BASIC_ENUM,
  65. AR_BASIC_COUNT,
  66. //
  67. // Pseudo-entries for intrinsic tables and such.
  68. //
  69. AR_BASIC_NONE,
  70. AR_BASIC_UNKNOWN,
  71. AR_BASIC_NOCAST,
  72. //
  73. // The following pseudo-entries represent higher-level
  74. // object types that are treated as units.
  75. //
  76. AR_BASIC_POINTER,
  77. AR_BASIC_ENUM_CLASS,
  78. AR_OBJECT_NULL,
  79. AR_OBJECT_STRING_LITERAL,
  80. AR_OBJECT_STRING,
  81. // AR_OBJECT_TEXTURE,
  82. AR_OBJECT_TEXTURE1D,
  83. AR_OBJECT_TEXTURE1D_ARRAY,
  84. AR_OBJECT_TEXTURE2D,
  85. AR_OBJECT_TEXTURE2D_ARRAY,
  86. AR_OBJECT_TEXTURE3D,
  87. AR_OBJECT_TEXTURECUBE,
  88. AR_OBJECT_TEXTURECUBE_ARRAY,
  89. AR_OBJECT_TEXTURE2DMS,
  90. AR_OBJECT_TEXTURE2DMS_ARRAY,
  91. AR_OBJECT_SAMPLER,
  92. AR_OBJECT_SAMPLER1D,
  93. AR_OBJECT_SAMPLER2D,
  94. AR_OBJECT_SAMPLER3D,
  95. AR_OBJECT_SAMPLERCUBE,
  96. AR_OBJECT_SAMPLERCOMPARISON,
  97. AR_OBJECT_BUFFER,
  98. //
  99. // View objects are only used as variable/types within the Effects
  100. // framework, for example in calls to OMSetRenderTargets.
  101. //
  102. AR_OBJECT_RENDERTARGETVIEW,
  103. AR_OBJECT_DEPTHSTENCILVIEW,
  104. //
  105. // Shader objects are only used as variable/types within the Effects
  106. // framework, for example as a result of CompileShader().
  107. //
  108. AR_OBJECT_COMPUTESHADER,
  109. AR_OBJECT_DOMAINSHADER,
  110. AR_OBJECT_GEOMETRYSHADER,
  111. AR_OBJECT_HULLSHADER,
  112. AR_OBJECT_PIXELSHADER,
  113. AR_OBJECT_VERTEXSHADER,
  114. AR_OBJECT_PIXELFRAGMENT,
  115. AR_OBJECT_VERTEXFRAGMENT,
  116. AR_OBJECT_STATEBLOCK,
  117. AR_OBJECT_RASTERIZER,
  118. AR_OBJECT_DEPTHSTENCIL,
  119. AR_OBJECT_BLEND,
  120. AR_OBJECT_POINTSTREAM,
  121. AR_OBJECT_LINESTREAM,
  122. AR_OBJECT_TRIANGLESTREAM,
  123. AR_OBJECT_INPUTPATCH,
  124. AR_OBJECT_OUTPUTPATCH,
  125. AR_OBJECT_RWTEXTURE1D,
  126. AR_OBJECT_RWTEXTURE1D_ARRAY,
  127. AR_OBJECT_RWTEXTURE2D,
  128. AR_OBJECT_RWTEXTURE2D_ARRAY,
  129. AR_OBJECT_RWTEXTURE3D,
  130. AR_OBJECT_RWBUFFER,
  131. AR_OBJECT_BYTEADDRESS_BUFFER,
  132. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  133. AR_OBJECT_STRUCTURED_BUFFER,
  134. AR_OBJECT_RWSTRUCTURED_BUFFER,
  135. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  136. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  137. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  138. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  139. AR_OBJECT_CONSTANT_BUFFER,
  140. AR_OBJECT_TEXTURE_BUFFER,
  141. AR_OBJECT_ROVBUFFER,
  142. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  143. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  144. AR_OBJECT_ROVTEXTURE1D,
  145. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  146. AR_OBJECT_ROVTEXTURE2D,
  147. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  148. AR_OBJECT_ROVTEXTURE3D,
  149. // SPIRV change starts
  150. #ifdef ENABLE_SPIRV_CODEGEN
  151. AR_OBJECT_VK_SUBPASS_INPUT,
  152. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  153. #endif // ENABLE_SPIRV_CODEGEN
  154. // SPIRV change ends
  155. AR_OBJECT_INNER, // Used for internal type object
  156. AR_OBJECT_LEGACY_EFFECT,
  157. AR_OBJECT_WAVE,
  158. AR_OBJECT_RAY_DESC,
  159. AR_OBJECT_ACCELARATION_STRUCT,
  160. AR_OBJECT_USER_DEFINED_TYPE,
  161. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  162. // subobjects
  163. AR_OBJECT_STATE_OBJECT_CONFIG,
  164. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  165. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  166. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  167. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  168. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  169. AR_OBJECT_TRIANGLE_HIT_GROUP,
  170. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  171. AR_BASIC_MAXIMUM_COUNT
  172. };
  173. #define AR_BASIC_TEXTURE_MS_CASES \
  174. case AR_OBJECT_TEXTURE2DMS: \
  175. case AR_OBJECT_TEXTURE2DMS_ARRAY
  176. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  177. case AR_OBJECT_TEXTURE1D: \
  178. case AR_OBJECT_TEXTURE1D_ARRAY: \
  179. case AR_OBJECT_TEXTURE2D: \
  180. case AR_OBJECT_TEXTURE2D_ARRAY: \
  181. case AR_OBJECT_TEXTURE3D: \
  182. case AR_OBJECT_TEXTURECUBE: \
  183. case AR_OBJECT_TEXTURECUBE_ARRAY
  184. #define AR_BASIC_TEXTURE_CASES \
  185. AR_BASIC_TEXTURE_MS_CASES: \
  186. AR_BASIC_NON_TEXTURE_MS_CASES
  187. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  188. case AR_OBJECT_SAMPLER: \
  189. case AR_OBJECT_SAMPLER1D: \
  190. case AR_OBJECT_SAMPLER2D: \
  191. case AR_OBJECT_SAMPLER3D: \
  192. case AR_OBJECT_SAMPLERCUBE
  193. #define AR_BASIC_ROBJECT_CASES \
  194. case AR_OBJECT_BLEND: \
  195. case AR_OBJECT_RASTERIZER: \
  196. case AR_OBJECT_DEPTHSTENCIL: \
  197. case AR_OBJECT_STATEBLOCK
  198. //
  199. // Properties of entries in the ArBasicKind enumeration.
  200. // These properties are intended to allow easy identification
  201. // of classes of basic kinds. More specific checks on the
  202. // actual kind values could then be done.
  203. //
  204. // The first four bits are used as a subtype indicator,
  205. // such as bit count for primitive kinds or specific
  206. // types for non-primitive-data kinds.
  207. #define BPROP_SUBTYPE_MASK 0x0000000f
  208. // Bit counts must be ordered from smaller to larger.
  209. #define BPROP_BITS0 0x00000000
  210. #define BPROP_BITS8 0x00000001
  211. #define BPROP_BITS10 0x00000002
  212. #define BPROP_BITS12 0x00000003
  213. #define BPROP_BITS16 0x00000004
  214. #define BPROP_BITS32 0x00000005
  215. #define BPROP_BITS64 0x00000006
  216. #define BPROP_BITS_NON_PRIM 0x00000007
  217. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  218. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  219. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  220. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  221. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  222. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  223. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  224. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  225. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  226. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  227. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  228. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  229. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  230. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  231. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  232. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  233. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  234. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  235. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  236. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  237. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  238. #define BPROP_ENUM 0x00800000 // Whether the type is a enum
  239. #define GET_BPROP_PRIM_KIND(_Props) \
  240. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  241. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  242. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  243. #define IS_BPROP_PRIMITIVE(_Props) \
  244. (((_Props) & BPROP_PRIMITIVE) != 0)
  245. #define IS_BPROP_BOOL(_Props) \
  246. (((_Props) & BPROP_BOOLEAN) != 0)
  247. #define IS_BPROP_FLOAT(_Props) \
  248. (((_Props) & BPROP_FLOATING) != 0)
  249. #define IS_BPROP_SINT(_Props) \
  250. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  251. BPROP_INTEGER)
  252. #define IS_BPROP_UINT(_Props) \
  253. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  254. (BPROP_INTEGER | BPROP_UNSIGNED))
  255. #define IS_BPROP_AINT(_Props) \
  256. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  257. #define IS_BPROP_STREAM(_Props) \
  258. (((_Props) & BPROP_STREAM) != 0)
  259. #define IS_BPROP_SAMPLER(_Props) \
  260. (((_Props) & BPROP_SAMPLER) != 0)
  261. #define IS_BPROP_TEXTURE(_Props) \
  262. (((_Props) & BPROP_TEXTURE) != 0)
  263. #define IS_BPROP_OBJECT(_Props) \
  264. (((_Props) & BPROP_OBJECT) != 0)
  265. #define IS_BPROP_MIN_PRECISION(_Props) \
  266. (((_Props) & BPROP_MIN_PRECISION) != 0)
  267. #define IS_BPROP_UNSIGNABLE(_Props) \
  268. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  269. #define IS_BPROP_ENUM(_Props) \
  270. (((_Props) & BPROP_ENUM) != 0)
  271. const UINT g_uBasicKindProps[] =
  272. {
  273. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  274. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  275. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  276. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  277. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  278. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  279. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  280. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  281. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  282. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  283. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  284. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  285. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  286. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  287. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  288. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  289. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  290. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  291. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  292. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  293. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  294. BPROP_OTHER, // AR_BASIC_COUNT
  295. //
  296. // Pseudo-entries for intrinsic tables and such.
  297. //
  298. 0, // AR_BASIC_NONE
  299. BPROP_OTHER, // AR_BASIC_UNKNOWN
  300. BPROP_OTHER, // AR_BASIC_NOCAST
  301. //
  302. // The following pseudo-entries represent higher-level
  303. // object types that are treated as units.
  304. //
  305. BPROP_POINTER, // AR_BASIC_POINTER
  306. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  307. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  308. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING_LITERAL
  309. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  310. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  311. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  312. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  313. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  314. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  315. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  316. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  317. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  318. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  319. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  320. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  321. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  322. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  323. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  324. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  325. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  326. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  327. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  328. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  329. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  330. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  331. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  332. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  333. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  334. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  335. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  336. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  337. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  338. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  339. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  340. BPROP_OBJECT, // AR_OBJECT_BLEND
  341. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  342. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  343. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  344. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  345. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  346. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  347. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  348. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  349. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  350. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  351. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  352. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  353. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  354. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  355. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  356. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  357. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  358. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  359. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  360. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  361. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  362. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  363. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  364. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  365. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  366. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  367. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  368. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  369. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  370. // SPIRV change starts
  371. #ifdef ENABLE_SPIRV_CODEGEN
  372. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  373. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  374. #endif // ENABLE_SPIRV_CODEGEN
  375. // SPIRV change ends
  376. BPROP_OBJECT, // AR_OBJECT_INNER
  377. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  378. BPROP_OBJECT, // AR_OBJECT_WAVE
  379. LICOMPTYPE_RAYDESC, // AR_OBJECT_RAY_DESC
  380. LICOMPTYPE_ACCELERATION_STRUCT, // AR_OBJECT_ACCELARATION_STRUCT
  381. LICOMPTYPE_USER_DEFINED_TYPE, // AR_OBJECT_USER_DEFINED_TYPE
  382. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  383. // subobjects
  384. 0, //AR_OBJECT_STATE_OBJECT_CONFIG,
  385. 0, //AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  386. 0, //AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  387. 0, //AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  388. 0, //AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  389. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  390. 0, //AR_OBJECT_TRIANGLE_HIT_GROUP,
  391. 0, //AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  392. // AR_BASIC_MAXIMUM_COUNT
  393. };
  394. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  395. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  396. #define GET_BASIC_BITS(_Kind) \
  397. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  398. #define GET_BASIC_PRIM_KIND(_Kind) \
  399. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  400. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  401. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  402. #define IS_BASIC_PRIMITIVE(_Kind) \
  403. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  404. #define IS_BASIC_BOOL(_Kind) \
  405. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  406. #define IS_BASIC_FLOAT(_Kind) \
  407. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  408. #define IS_BASIC_SINT(_Kind) \
  409. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  410. #define IS_BASIC_UINT(_Kind) \
  411. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  412. #define IS_BASIC_AINT(_Kind) \
  413. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  414. #define IS_BASIC_STREAM(_Kind) \
  415. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  416. #define IS_BASIC_SAMPLER(_Kind) \
  417. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  418. #define IS_BASIC_TEXTURE(_Kind) \
  419. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  420. #define IS_BASIC_OBJECT(_Kind) \
  421. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  422. #define IS_BASIC_MIN_PRECISION(_Kind) \
  423. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  424. #define IS_BASIC_UNSIGNABLE(_Kind) \
  425. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  426. #define IS_BASIC_ENUM(_Kind) \
  427. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  428. #define BITWISE_ENUM_OPS(_Type) \
  429. inline _Type operator|(_Type F1, _Type F2) \
  430. { \
  431. return (_Type)((UINT)F1 | (UINT)F2); \
  432. } \
  433. inline _Type operator&(_Type F1, _Type F2) \
  434. { \
  435. return (_Type)((UINT)F1 & (UINT)F2); \
  436. } \
  437. inline _Type& operator|=(_Type& F1, _Type F2) \
  438. { \
  439. F1 = F1 | F2; \
  440. return F1; \
  441. } \
  442. inline _Type& operator&=(_Type& F1, _Type F2) \
  443. { \
  444. F1 = F1 & F2; \
  445. return F1; \
  446. } \
  447. inline _Type& operator&=(_Type& F1, UINT F2) \
  448. { \
  449. F1 = (_Type)((UINT)F1 & F2); \
  450. return F1; \
  451. }
  452. enum ArTypeObjectKind {
  453. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  454. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  455. AR_TOBJ_BASIC, // Represents a primitive type.
  456. AR_TOBJ_COMPOUND, // Represents a struct or class.
  457. AR_TOBJ_INTERFACE, // Represents an interface.
  458. AR_TOBJ_POINTER, // Represents a pointer to another type.
  459. AR_TOBJ_OBJECT, // Represents a built-in object.
  460. AR_TOBJ_ARRAY, // Represents an array of other types.
  461. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  462. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  463. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  464. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  465. // indexer object used to implement .mips[1].
  466. AR_TOBJ_STRING, // Represents a string
  467. };
  468. enum TYPE_CONVERSION_FLAGS
  469. {
  470. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  471. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  472. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  473. };
  474. enum TYPE_CONVERSION_REMARKS
  475. {
  476. TYPE_CONVERSION_NONE = 0x00000000,
  477. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  478. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  479. TYPE_CONVERSION_TO_VOID = 0x00000004,
  480. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  481. };
  482. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  483. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  484. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  485. #define AR_TPROP_VOID 0x0000000000000001
  486. #define AR_TPROP_CONST 0x0000000000000002
  487. #define AR_TPROP_IMP_CONST 0x0000000000000004
  488. #define AR_TPROP_OBJECT 0x0000000000000008
  489. #define AR_TPROP_SCALAR 0x0000000000000010
  490. #define AR_TPROP_UNSIGNED 0x0000000000000020
  491. #define AR_TPROP_NUMERIC 0x0000000000000040
  492. #define AR_TPROP_INTEGRAL 0x0000000000000080
  493. #define AR_TPROP_FLOATING 0x0000000000000100
  494. #define AR_TPROP_LITERAL 0x0000000000000200
  495. #define AR_TPROP_POINTER 0x0000000000000400
  496. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  497. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  498. #define AR_TPROP_INH_IFACE 0x0000000000002000
  499. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  500. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  501. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  502. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  503. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  504. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  505. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  506. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  507. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  508. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  509. #define AR_TPROP_INDEXABLE 0x0000000001000000
  510. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  511. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  512. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  513. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  514. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  515. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  516. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  517. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  518. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  519. #define AR_TPROP_ALL 0xffffffffffffffff
  520. #define AR_TPROP_HAS_OBJECTS \
  521. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  522. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  523. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  524. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  525. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  526. #define AR_TPROP_HAS_BASIC_RESOURCES \
  527. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  528. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  529. AR_TPROP_HAS_UAVS)
  530. #define AR_TPROP_UNION_BITS \
  531. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  532. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  533. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  534. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  535. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  536. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  537. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  538. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  539. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  540. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  541. #define AR_TINFO_PACK_SCALAR 0x00000010
  542. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  543. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  544. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  545. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  546. #define AR_TINFO_PACK_CBUFFER 0
  547. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  548. #define AR_TINFO_SIMPLE_OBJECTS \
  549. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  550. struct ArTypeInfo {
  551. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  552. ArBasicKind EltKind; // The primitive type of elements in this type.
  553. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  554. UINT uRows;
  555. UINT uCols;
  556. UINT uTotalElts;
  557. };
  558. using namespace clang;
  559. using namespace clang::sema;
  560. using namespace hlsl;
  561. extern const char *HLSLScalarTypeNames[];
  562. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  563. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  564. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  565. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  566. static const SourceLocation NoLoc; // no source location attribution available
  567. static const SourceRange NoRange; // no source range attribution available
  568. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  569. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  570. static const bool IsConstexprFalse = false; // function is not constexpr
  571. static const bool ListInitializationFalse = false;// not performing a list initialization
  572. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  573. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  574. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  575. static const int OneRow = 1; // a single row for a type
  576. static const bool MipsFalse = false; // a type does not support the .mips member
  577. static const bool MipsTrue = true; // a type supports the .mips member
  578. static const bool SampleFalse = false; // a type does not support the .sample member
  579. static const bool SampleTrue = true; // a type supports the .sample member
  580. static const size_t MaxVectorSize = 4; // maximum size for a vector
  581. static
  582. QualType GetOrCreateTemplateSpecialization(
  583. ASTContext& context,
  584. Sema& sema,
  585. _In_ ClassTemplateDecl* templateDecl,
  586. ArrayRef<TemplateArgument> templateArgs
  587. )
  588. {
  589. DXASSERT_NOMSG(templateDecl);
  590. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  591. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  592. for (const TemplateArgument& Arg : templateArgs) {
  593. if (Arg.getKind() == TemplateArgument::Type) {
  594. // the class template need to use CanonicalType
  595. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  596. }else
  597. templateArgsForDecl.emplace_back(Arg);
  598. }
  599. // First, try looking up existing specialization
  600. void* InsertPos = nullptr;
  601. ClassTemplateSpecializationDecl* specializationDecl =
  602. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  603. if (specializationDecl) {
  604. // Instantiate the class template if not yet.
  605. if (specializationDecl->getInstantiatedFrom().isNull()) {
  606. // InstantiateClassTemplateSpecialization returns true if it finds an
  607. // error.
  608. DXVERIFY_NOMSG(false ==
  609. sema.InstantiateClassTemplateSpecialization(
  610. NoLoc, specializationDecl,
  611. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  612. true));
  613. }
  614. return context.getTemplateSpecializationType(
  615. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  616. context.getTypeDeclType(specializationDecl));
  617. }
  618. specializationDecl = ClassTemplateSpecializationDecl::Create(
  619. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  620. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  621. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  622. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  623. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  624. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  625. specializationDecl->setImplicit(true);
  626. QualType canonType = context.getTypeDeclType(specializationDecl);
  627. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  628. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  629. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  630. for (unsigned i = 0; i < templateArgs.size(); i++) {
  631. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  632. }
  633. return context.getTemplateSpecializationType(
  634. TemplateName(templateDecl), templateArgumentList, canonType);
  635. }
  636. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  637. static
  638. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  639. _In_ ClassTemplateDecl* matrixTemplateDecl,
  640. QualType elementType, uint64_t rowCount, uint64_t colCount)
  641. {
  642. DXASSERT_NOMSG(sema);
  643. TemplateArgument templateArgs[3] = {
  644. TemplateArgument(elementType),
  645. TemplateArgument(
  646. context,
  647. llvm::APSInt(
  648. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  649. context.IntTy),
  650. TemplateArgument(
  651. context,
  652. llvm::APSInt(
  653. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  654. context.IntTy)};
  655. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  656. #ifdef DBG
  657. // Verify that we can read the field member from the template record.
  658. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  659. "type of non-dependent specialization is not a RecordType");
  660. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  661. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  662. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  663. #endif
  664. return matrixSpecializationType;
  665. }
  666. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  667. static
  668. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  669. _In_ ClassTemplateDecl* vectorTemplateDecl,
  670. QualType elementType, uint64_t colCount)
  671. {
  672. DXASSERT_NOMSG(sema);
  673. DXASSERT_NOMSG(vectorTemplateDecl);
  674. TemplateArgument templateArgs[2] = {
  675. TemplateArgument(elementType),
  676. TemplateArgument(
  677. context,
  678. llvm::APSInt(
  679. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  680. context.IntTy)};
  681. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  682. #ifdef DBG
  683. // Verify that we can read the field member from the template record.
  684. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  685. "type of non-dependent specialization is not a RecordType");
  686. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  687. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  688. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  689. #endif
  690. return vectorSpecializationType;
  691. }
  692. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  693. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  694. static const unsigned kAtomicDstOperandIdx = 1;
  695. static const ArTypeObjectKind g_ScalarTT[] =
  696. {
  697. AR_TOBJ_SCALAR,
  698. AR_TOBJ_UNKNOWN
  699. };
  700. static const ArTypeObjectKind g_VectorTT[] =
  701. {
  702. AR_TOBJ_VECTOR,
  703. AR_TOBJ_UNKNOWN
  704. };
  705. static const ArTypeObjectKind g_MatrixTT[] =
  706. {
  707. AR_TOBJ_MATRIX,
  708. AR_TOBJ_UNKNOWN
  709. };
  710. static const ArTypeObjectKind g_AnyTT[] =
  711. {
  712. AR_TOBJ_SCALAR,
  713. AR_TOBJ_VECTOR,
  714. AR_TOBJ_MATRIX,
  715. AR_TOBJ_UNKNOWN
  716. };
  717. static const ArTypeObjectKind g_ObjectTT[] =
  718. {
  719. AR_TOBJ_OBJECT,
  720. AR_TOBJ_UNKNOWN
  721. };
  722. static const ArTypeObjectKind g_NullTT[] =
  723. {
  724. AR_TOBJ_VOID,
  725. AR_TOBJ_UNKNOWN
  726. };
  727. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  728. {
  729. g_NullTT,
  730. g_ScalarTT,
  731. g_VectorTT,
  732. g_MatrixTT,
  733. g_AnyTT,
  734. g_ObjectTT,
  735. };
  736. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  737. //
  738. // The first one is used to name the representative group, so make
  739. // sure its name will make sense in error messages.
  740. //
  741. static const ArBasicKind g_BoolCT[] =
  742. {
  743. AR_BASIC_BOOL,
  744. AR_BASIC_UNKNOWN
  745. };
  746. static const ArBasicKind g_IntCT[] =
  747. {
  748. AR_BASIC_INT32,
  749. AR_BASIC_LITERAL_INT,
  750. AR_BASIC_UNKNOWN
  751. };
  752. static const ArBasicKind g_UIntCT[] =
  753. {
  754. AR_BASIC_UINT32,
  755. AR_BASIC_LITERAL_INT,
  756. AR_BASIC_UNKNOWN
  757. };
  758. // We use the first element for default if matching kind is missing in the list.
  759. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  760. static const ArBasicKind g_AnyIntCT[] =
  761. {
  762. AR_BASIC_INT32,
  763. AR_BASIC_INT16,
  764. AR_BASIC_UINT32,
  765. AR_BASIC_UINT16,
  766. AR_BASIC_INT64,
  767. AR_BASIC_UINT64,
  768. AR_BASIC_LITERAL_INT,
  769. AR_BASIC_UNKNOWN
  770. };
  771. static const ArBasicKind g_AnyInt32CT[] =
  772. {
  773. AR_BASIC_INT32,
  774. AR_BASIC_UINT32,
  775. AR_BASIC_LITERAL_INT,
  776. AR_BASIC_UNKNOWN
  777. };
  778. static const ArBasicKind g_UIntOnlyCT[] =
  779. {
  780. AR_BASIC_UINT32,
  781. AR_BASIC_UINT64,
  782. AR_BASIC_LITERAL_INT,
  783. AR_BASIC_NOCAST,
  784. AR_BASIC_UNKNOWN
  785. };
  786. static const ArBasicKind g_FloatCT[] =
  787. {
  788. AR_BASIC_FLOAT32,
  789. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  790. AR_BASIC_LITERAL_FLOAT,
  791. AR_BASIC_UNKNOWN
  792. };
  793. static const ArBasicKind g_AnyFloatCT[] =
  794. {
  795. AR_BASIC_FLOAT32,
  796. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  797. AR_BASIC_FLOAT16,
  798. AR_BASIC_FLOAT64,
  799. AR_BASIC_LITERAL_FLOAT,
  800. AR_BASIC_MIN10FLOAT,
  801. AR_BASIC_MIN16FLOAT,
  802. AR_BASIC_UNKNOWN
  803. };
  804. static const ArBasicKind g_FloatLikeCT[] =
  805. {
  806. AR_BASIC_FLOAT32,
  807. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  808. AR_BASIC_FLOAT16,
  809. AR_BASIC_LITERAL_FLOAT,
  810. AR_BASIC_MIN10FLOAT,
  811. AR_BASIC_MIN16FLOAT,
  812. AR_BASIC_UNKNOWN
  813. };
  814. static const ArBasicKind g_FloatDoubleCT[] =
  815. {
  816. AR_BASIC_FLOAT32,
  817. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  818. AR_BASIC_FLOAT64,
  819. AR_BASIC_LITERAL_FLOAT,
  820. AR_BASIC_UNKNOWN
  821. };
  822. static const ArBasicKind g_DoubleCT[] =
  823. {
  824. AR_BASIC_FLOAT64,
  825. AR_BASIC_LITERAL_FLOAT,
  826. AR_BASIC_UNKNOWN
  827. };
  828. static const ArBasicKind g_DoubleOnlyCT[] =
  829. {
  830. AR_BASIC_FLOAT64,
  831. AR_BASIC_NOCAST,
  832. AR_BASIC_UNKNOWN
  833. };
  834. static const ArBasicKind g_NumericCT[] =
  835. {
  836. AR_BASIC_LITERAL_FLOAT,
  837. AR_BASIC_FLOAT32,
  838. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  839. AR_BASIC_FLOAT16,
  840. AR_BASIC_FLOAT64,
  841. AR_BASIC_MIN10FLOAT,
  842. AR_BASIC_MIN16FLOAT,
  843. AR_BASIC_LITERAL_INT,
  844. AR_BASIC_INT16,
  845. AR_BASIC_INT32,
  846. AR_BASIC_UINT16,
  847. AR_BASIC_UINT32,
  848. AR_BASIC_MIN12INT,
  849. AR_BASIC_MIN16INT,
  850. AR_BASIC_MIN16UINT,
  851. AR_BASIC_INT64,
  852. AR_BASIC_UINT64,
  853. AR_BASIC_UNKNOWN
  854. };
  855. static const ArBasicKind g_Numeric32CT[] =
  856. {
  857. AR_BASIC_LITERAL_FLOAT,
  858. AR_BASIC_FLOAT32,
  859. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  860. AR_BASIC_LITERAL_INT,
  861. AR_BASIC_INT32,
  862. AR_BASIC_UINT32,
  863. AR_BASIC_UNKNOWN
  864. };
  865. static const ArBasicKind g_Numeric32OnlyCT[] =
  866. {
  867. AR_BASIC_LITERAL_FLOAT,
  868. AR_BASIC_FLOAT32,
  869. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  870. AR_BASIC_LITERAL_INT,
  871. AR_BASIC_INT32,
  872. AR_BASIC_UINT32,
  873. AR_BASIC_NOCAST,
  874. AR_BASIC_UNKNOWN
  875. };
  876. static const ArBasicKind g_AnyCT[] =
  877. {
  878. AR_BASIC_LITERAL_FLOAT,
  879. AR_BASIC_FLOAT32,
  880. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  881. AR_BASIC_FLOAT16,
  882. AR_BASIC_FLOAT64,
  883. AR_BASIC_MIN10FLOAT,
  884. AR_BASIC_MIN16FLOAT,
  885. AR_BASIC_LITERAL_INT,
  886. AR_BASIC_INT16,
  887. AR_BASIC_UINT16,
  888. AR_BASIC_INT32,
  889. AR_BASIC_UINT32,
  890. AR_BASIC_MIN12INT,
  891. AR_BASIC_MIN16INT,
  892. AR_BASIC_MIN16UINT,
  893. AR_BASIC_BOOL,
  894. AR_BASIC_INT64,
  895. AR_BASIC_UINT64,
  896. AR_BASIC_UNKNOWN
  897. };
  898. static const ArBasicKind g_Sampler1DCT[] =
  899. {
  900. AR_OBJECT_SAMPLER1D,
  901. AR_BASIC_UNKNOWN
  902. };
  903. static const ArBasicKind g_Sampler2DCT[] =
  904. {
  905. AR_OBJECT_SAMPLER2D,
  906. AR_BASIC_UNKNOWN
  907. };
  908. static const ArBasicKind g_Sampler3DCT[] =
  909. {
  910. AR_OBJECT_SAMPLER3D,
  911. AR_BASIC_UNKNOWN
  912. };
  913. static const ArBasicKind g_SamplerCUBECT[] =
  914. {
  915. AR_OBJECT_SAMPLERCUBE,
  916. AR_BASIC_UNKNOWN
  917. };
  918. static const ArBasicKind g_SamplerCmpCT[] =
  919. {
  920. AR_OBJECT_SAMPLERCOMPARISON,
  921. AR_BASIC_UNKNOWN
  922. };
  923. static const ArBasicKind g_SamplerCT[] =
  924. {
  925. AR_OBJECT_SAMPLER,
  926. AR_BASIC_UNKNOWN
  927. };
  928. static const ArBasicKind g_RayDescCT[] =
  929. {
  930. AR_OBJECT_RAY_DESC,
  931. AR_BASIC_UNKNOWN
  932. };
  933. static const ArBasicKind g_AccelarationStructCT[] =
  934. {
  935. AR_OBJECT_ACCELARATION_STRUCT,
  936. AR_BASIC_UNKNOWN
  937. };
  938. static const ArBasicKind g_UDTCT[] =
  939. {
  940. AR_OBJECT_USER_DEFINED_TYPE,
  941. AR_BASIC_UNKNOWN
  942. };
  943. static const ArBasicKind g_StringCT[] =
  944. {
  945. AR_OBJECT_STRING_LITERAL,
  946. AR_OBJECT_STRING,
  947. AR_BASIC_UNKNOWN
  948. };
  949. static const ArBasicKind g_NullCT[] =
  950. {
  951. AR_OBJECT_NULL,
  952. AR_BASIC_UNKNOWN
  953. };
  954. static const ArBasicKind g_WaveCT[] =
  955. {
  956. AR_OBJECT_WAVE,
  957. AR_BASIC_UNKNOWN
  958. };
  959. static const ArBasicKind g_UInt64CT[] =
  960. {
  961. AR_BASIC_UINT64,
  962. AR_BASIC_UNKNOWN
  963. };
  964. static const ArBasicKind g_Float16CT[] =
  965. {
  966. AR_BASIC_FLOAT16,
  967. AR_BASIC_LITERAL_FLOAT,
  968. AR_BASIC_UNKNOWN
  969. };
  970. static const ArBasicKind g_Int16CT[] =
  971. {
  972. AR_BASIC_INT16,
  973. AR_BASIC_LITERAL_INT,
  974. AR_BASIC_UNKNOWN
  975. };
  976. static const ArBasicKind g_UInt16CT[] =
  977. {
  978. AR_BASIC_UINT16,
  979. AR_BASIC_LITERAL_INT,
  980. AR_BASIC_UNKNOWN
  981. };
  982. static const ArBasicKind g_Numeric16OnlyCT[] =
  983. {
  984. AR_BASIC_FLOAT16,
  985. AR_BASIC_INT16,
  986. AR_BASIC_UINT16,
  987. AR_BASIC_LITERAL_FLOAT,
  988. AR_BASIC_LITERAL_INT,
  989. AR_BASIC_NOCAST,
  990. AR_BASIC_UNKNOWN
  991. };
  992. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  993. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  994. {
  995. g_NullCT, // LICOMPTYPE_VOID
  996. g_BoolCT, // LICOMPTYPE_BOOL
  997. g_IntCT, // LICOMPTYPE_INT
  998. g_UIntCT, // LICOMPTYPE_UINT
  999. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  1000. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  1001. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  1002. g_FloatCT, // LICOMPTYPE_FLOAT
  1003. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  1004. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  1005. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  1006. g_DoubleCT, // LICOMPTYPE_DOUBLE
  1007. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  1008. g_NumericCT, // LICOMPTYPE_NUMERIC
  1009. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  1010. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  1011. g_AnyCT, // LICOMPTYPE_ANY
  1012. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  1013. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  1014. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  1015. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  1016. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  1017. g_SamplerCT, // LICOMPTYPE_SAMPLER
  1018. g_StringCT, // LICOMPTYPE_STRING
  1019. g_WaveCT, // LICOMPTYPE_WAVE
  1020. g_UInt64CT, // LICOMPTYPE_UINT64
  1021. g_Float16CT, // LICOMPTYPE_FLOAT16
  1022. g_Int16CT, // LICOMPTYPE_INT16
  1023. g_UInt16CT, // LICOMPTYPE_UINT16
  1024. g_Numeric16OnlyCT, // LICOMPTYPE_NUMERIC16_ONLY
  1025. g_RayDescCT, // LICOMPTYPE_RAYDESC
  1026. g_AccelarationStructCT, // LICOMPTYPE_ACCELERATION_STRUCT,
  1027. g_UDTCT, // LICOMPTYPE_USER_DEFINED_TYPE
  1028. };
  1029. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT);
  1030. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  1031. // Basic kind objects that are represented as HLSL structures or templates.
  1032. static
  1033. const ArBasicKind g_ArBasicKindsAsTypes[] =
  1034. {
  1035. AR_OBJECT_BUFFER, // Buffer
  1036. // AR_OBJECT_TEXTURE,
  1037. AR_OBJECT_TEXTURE1D, // Texture1D
  1038. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1039. AR_OBJECT_TEXTURE2D, // Texture2D
  1040. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1041. AR_OBJECT_TEXTURE3D, // Texture3D
  1042. AR_OBJECT_TEXTURECUBE, // TextureCube
  1043. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1044. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1045. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1046. AR_OBJECT_SAMPLER,
  1047. //AR_OBJECT_SAMPLER1D,
  1048. //AR_OBJECT_SAMPLER2D,
  1049. //AR_OBJECT_SAMPLER3D,
  1050. //AR_OBJECT_SAMPLERCUBE,
  1051. AR_OBJECT_SAMPLERCOMPARISON,
  1052. AR_OBJECT_POINTSTREAM,
  1053. AR_OBJECT_LINESTREAM,
  1054. AR_OBJECT_TRIANGLESTREAM,
  1055. AR_OBJECT_INPUTPATCH,
  1056. AR_OBJECT_OUTPUTPATCH,
  1057. AR_OBJECT_RWTEXTURE1D,
  1058. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1059. AR_OBJECT_RWTEXTURE2D,
  1060. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1061. AR_OBJECT_RWTEXTURE3D,
  1062. AR_OBJECT_RWBUFFER,
  1063. AR_OBJECT_BYTEADDRESS_BUFFER,
  1064. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1065. AR_OBJECT_STRUCTURED_BUFFER,
  1066. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1067. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1068. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1069. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1070. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1071. AR_OBJECT_ROVBUFFER,
  1072. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1073. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1074. AR_OBJECT_ROVTEXTURE1D,
  1075. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1076. AR_OBJECT_ROVTEXTURE2D,
  1077. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1078. AR_OBJECT_ROVTEXTURE3D,
  1079. // SPIRV change starts
  1080. #ifdef ENABLE_SPIRV_CODEGEN
  1081. AR_OBJECT_VK_SUBPASS_INPUT,
  1082. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1083. #endif // ENABLE_SPIRV_CODEGEN
  1084. // SPIRV change ends
  1085. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1086. AR_OBJECT_WAVE,
  1087. AR_OBJECT_RAY_DESC,
  1088. AR_OBJECT_ACCELARATION_STRUCT,
  1089. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  1090. // subobjects
  1091. AR_OBJECT_STATE_OBJECT_CONFIG,
  1092. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1093. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1094. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1095. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1096. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1097. AR_OBJECT_TRIANGLE_HIT_GROUP,
  1098. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP
  1099. };
  1100. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1101. static
  1102. const uint8_t g_ArBasicKindsTemplateCount[] =
  1103. {
  1104. 1, // AR_OBJECT_BUFFER
  1105. // AR_OBJECT_TEXTURE,
  1106. 1, // AR_OBJECT_TEXTURE1D
  1107. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1108. 1, // AR_OBJECT_TEXTURE2D
  1109. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1110. 1, // AR_OBJECT_TEXTURE3D
  1111. 1, // AR_OBJECT_TEXTURECUBE
  1112. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1113. 2, // AR_OBJECT_TEXTURE2DMS
  1114. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1115. 0, // AR_OBJECT_SAMPLER
  1116. //AR_OBJECT_SAMPLER1D,
  1117. //AR_OBJECT_SAMPLER2D,
  1118. //AR_OBJECT_SAMPLER3D,
  1119. //AR_OBJECT_SAMPLERCUBE,
  1120. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1121. 1, // AR_OBJECT_POINTSTREAM
  1122. 1, // AR_OBJECT_LINESTREAM
  1123. 1, // AR_OBJECT_TRIANGLESTREAM
  1124. 2, // AR_OBJECT_INPUTPATCH
  1125. 2, // AR_OBJECT_OUTPUTPATCH
  1126. 1, // AR_OBJECT_RWTEXTURE1D
  1127. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1128. 1, // AR_OBJECT_RWTEXTURE2D
  1129. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1130. 1, // AR_OBJECT_RWTEXTURE3D
  1131. 1, // AR_OBJECT_RWBUFFER
  1132. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1133. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1134. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1135. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1136. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1137. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1138. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1139. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1140. 1, // AR_OBJECT_ROVBUFFER
  1141. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1142. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1143. 1, // AR_OBJECT_ROVTEXTURE1D
  1144. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1145. 1, // AR_OBJECT_ROVTEXTURE2D
  1146. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1147. 1, // AR_OBJECT_ROVTEXTURE3D
  1148. // SPIRV change starts
  1149. #ifdef ENABLE_SPIRV_CODEGEN
  1150. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1151. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1152. #endif // ENABLE_SPIRV_CODEGEN
  1153. // SPIRV change ends
  1154. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1155. 0, // AR_OBJECT_WAVE
  1156. 0, // AR_OBJECT_RAY_DESC
  1157. 0, // AR_OBJECT_ACCELARATION_STRUCT
  1158. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1159. 0, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1160. 0, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1161. 0, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1162. 0, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1163. 0, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1164. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1165. 0, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1166. 0, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1167. };
  1168. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1169. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1170. struct SubscriptOperatorRecord
  1171. {
  1172. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1173. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1174. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1175. };
  1176. // Subscript operators for objects that are represented as HLSL structures or templates.
  1177. static
  1178. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1179. {
  1180. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1181. // AR_OBJECT_TEXTURE,
  1182. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1183. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1184. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1185. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1186. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1187. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1188. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1189. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1190. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1191. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1192. //AR_OBJECT_SAMPLER1D,
  1193. //AR_OBJECT_SAMPLER2D,
  1194. //AR_OBJECT_SAMPLER3D,
  1195. //AR_OBJECT_SAMPLERCUBE,
  1196. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1197. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1198. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1199. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1200. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1201. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1202. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1203. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1204. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1205. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1206. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1207. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1208. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1209. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1210. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1211. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1212. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1213. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1214. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1215. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1216. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1217. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1218. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1219. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1220. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1221. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1222. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1223. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1224. // SPIRV change starts
  1225. #ifdef ENABLE_SPIRV_CODEGEN
  1226. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1227. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1228. #endif // ENABLE_SPIRV_CODEGEN
  1229. // SPIRV change ends
  1230. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1231. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_WAVE
  1232. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_DESC
  1233. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ACCELARATION_STRUCT
  1234. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1235. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1236. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1237. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1238. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1239. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1240. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1241. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1242. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1243. };
  1244. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1245. // Type names for ArBasicKind values.
  1246. static
  1247. const char* g_ArBasicTypeNames[] =
  1248. {
  1249. "bool", "float", "half", "half", "float", "double",
  1250. "int", "sbyte", "byte", "short", "ushort",
  1251. "int", "uint", "long", "ulong",
  1252. "min10float", "min16float",
  1253. "min12int", "min16int", "min16uint",
  1254. "enum",
  1255. "<count>",
  1256. "<none>",
  1257. "<unknown>",
  1258. "<nocast>",
  1259. "<pointer>",
  1260. "enum class",
  1261. "null",
  1262. "literal string",
  1263. "string",
  1264. // "texture",
  1265. "Texture1D",
  1266. "Texture1DArray",
  1267. "Texture2D",
  1268. "Texture2DArray",
  1269. "Texture3D",
  1270. "TextureCube",
  1271. "TextureCubeArray",
  1272. "Texture2DMS",
  1273. "Texture2DMSArray",
  1274. "SamplerState",
  1275. "sampler1D",
  1276. "sampler2D",
  1277. "sampler3D",
  1278. "samplerCUBE",
  1279. "SamplerComparisonState",
  1280. "Buffer",
  1281. "RenderTargetView",
  1282. "DepthStencilView",
  1283. "ComputeShader",
  1284. "DomainShader",
  1285. "GeometryShader",
  1286. "HullShader",
  1287. "PixelShader",
  1288. "VertexShader",
  1289. "pixelfragment",
  1290. "vertexfragment",
  1291. "StateBlock",
  1292. "Rasterizer",
  1293. "DepthStencil",
  1294. "Blend",
  1295. "PointStream",
  1296. "LineStream",
  1297. "TriangleStream",
  1298. "InputPatch",
  1299. "OutputPatch",
  1300. "RWTexture1D",
  1301. "RWTexture1DArray",
  1302. "RWTexture2D",
  1303. "RWTexture2DArray",
  1304. "RWTexture3D",
  1305. "RWBuffer",
  1306. "ByteAddressBuffer",
  1307. "RWByteAddressBuffer",
  1308. "StructuredBuffer",
  1309. "RWStructuredBuffer",
  1310. "RWStructuredBuffer(Incrementable)",
  1311. "RWStructuredBuffer(Decrementable)",
  1312. "AppendStructuredBuffer",
  1313. "ConsumeStructuredBuffer",
  1314. "ConstantBuffer",
  1315. "TextureBuffer",
  1316. "RasterizerOrderedBuffer",
  1317. "RasterizerOrderedByteAddressBuffer",
  1318. "RasterizerOrderedStructuredBuffer",
  1319. "RasterizerOrderedTexture1D",
  1320. "RasterizerOrderedTexture1DArray",
  1321. "RasterizerOrderedTexture2D",
  1322. "RasterizerOrderedTexture2DArray",
  1323. "RasterizerOrderedTexture3D",
  1324. // SPIRV change starts
  1325. #ifdef ENABLE_SPIRV_CODEGEN
  1326. "SubpassInput",
  1327. "SubpassInputMS",
  1328. #endif // ENABLE_SPIRV_CODEGEN
  1329. // SPIRV change ends
  1330. "<internal inner type object>",
  1331. "deprecated effect object",
  1332. "wave_t",
  1333. "RayDesc",
  1334. "RaytracingAccelerationStructure",
  1335. "user defined type",
  1336. "BuiltInTriangleIntersectionAttributes",
  1337. // subobjects
  1338. "StateObjectConfig",
  1339. "GlobalRootSignature",
  1340. "LocalRootSignature",
  1341. "SubobjectToExportsAssociation",
  1342. "RaytracingShaderConfig",
  1343. "RaytracingPipelineConfig",
  1344. "TriangleHitGroup",
  1345. "ProceduralPrimitiveHitGroup"
  1346. };
  1347. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1348. static bool IsValidBasicKind(ArBasicKind kind) {
  1349. return kind != AR_BASIC_COUNT &&
  1350. kind != AR_BASIC_NONE &&
  1351. kind != AR_BASIC_UNKNOWN &&
  1352. kind != AR_BASIC_NOCAST &&
  1353. kind != AR_BASIC_POINTER &&
  1354. kind != AR_OBJECT_RENDERTARGETVIEW &&
  1355. kind != AR_OBJECT_DEPTHSTENCILVIEW &&
  1356. kind != AR_OBJECT_COMPUTESHADER &&
  1357. kind != AR_OBJECT_DOMAINSHADER &&
  1358. kind != AR_OBJECT_GEOMETRYSHADER &&
  1359. kind != AR_OBJECT_HULLSHADER &&
  1360. kind != AR_OBJECT_PIXELSHADER &&
  1361. kind != AR_OBJECT_VERTEXSHADER &&
  1362. kind != AR_OBJECT_PIXELFRAGMENT &&
  1363. kind != AR_OBJECT_VERTEXFRAGMENT;
  1364. }
  1365. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1366. #define DXASSERT_VALIDBASICKIND(kind) \
  1367. DXASSERT(IsValidBasicKind(kind), "otherwise caller is using a special flag or an unsupported kind value");
  1368. static
  1369. const char* g_DeprecatedEffectObjectNames[] =
  1370. {
  1371. // These are case insensitive in fxc, but we'll just create two case aliases
  1372. // to capture the majority of cases
  1373. "texture", "Texture",
  1374. "pixelshader", "PixelShader",
  1375. "vertexshader", "VertexShader",
  1376. // These are case sensitive in fxc
  1377. "pixelfragment", // 13
  1378. "vertexfragment", // 14
  1379. "ComputeShader", // 13
  1380. "DomainShader", // 12
  1381. "GeometryShader", // 14
  1382. "HullShader", // 10
  1383. "BlendState", // 10
  1384. "DepthStencilState",// 17
  1385. "DepthStencilView", // 16
  1386. "RasterizerState", // 15
  1387. "RenderTargetView", // 16
  1388. };
  1389. static hlsl::ParameterModifier
  1390. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1391. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1392. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1393. }
  1394. if (pArg->qwUsage == AR_QUAL_OUT) {
  1395. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1396. }
  1397. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1398. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1399. }
  1400. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1401. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1402. // The first argument is the return value, which isn't included.
  1403. for (UINT i = 1; i < pIntrinsic->uNumArgs; ++i) {
  1404. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1405. }
  1406. }
  1407. static bool IsAtomicOperation(IntrinsicOp op) {
  1408. switch (op) {
  1409. case IntrinsicOp::IOP_InterlockedAdd:
  1410. case IntrinsicOp::IOP_InterlockedAnd:
  1411. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1412. case IntrinsicOp::IOP_InterlockedCompareStore:
  1413. case IntrinsicOp::IOP_InterlockedExchange:
  1414. case IntrinsicOp::IOP_InterlockedMax:
  1415. case IntrinsicOp::IOP_InterlockedMin:
  1416. case IntrinsicOp::IOP_InterlockedOr:
  1417. case IntrinsicOp::IOP_InterlockedXor:
  1418. case IntrinsicOp::MOP_InterlockedAdd:
  1419. case IntrinsicOp::MOP_InterlockedAnd:
  1420. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1421. case IntrinsicOp::MOP_InterlockedCompareStore:
  1422. case IntrinsicOp::MOP_InterlockedExchange:
  1423. case IntrinsicOp::MOP_InterlockedMax:
  1424. case IntrinsicOp::MOP_InterlockedMin:
  1425. case IntrinsicOp::MOP_InterlockedOr:
  1426. case IntrinsicOp::MOP_InterlockedXor:
  1427. return true;
  1428. default:
  1429. return false;
  1430. }
  1431. }
  1432. static bool IsBuiltinTable(LPCSTR tableName) {
  1433. return tableName == kBuiltinIntrinsicTableName;
  1434. }
  1435. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1436. LPCSTR tableName, LPCSTR lowering,
  1437. const HLSL_INTRINSIC *pIntrinsic) {
  1438. unsigned opcode = (unsigned)pIntrinsic->Op;
  1439. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1440. QualType Ty = FD->getReturnType();
  1441. if (pIntrinsic->iOverloadParamIndex != -1) {
  1442. const FunctionProtoType *FT =
  1443. FD->getFunctionType()->getAs<FunctionProtoType>();
  1444. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1445. }
  1446. // TODO: refine the code for getting element type
  1447. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1448. Ty = VecTy->getElementType();
  1449. }
  1450. if (Ty->isUnsignedIntegerType()) {
  1451. opcode = hlsl::GetUnsignedOpcode(opcode);
  1452. }
  1453. }
  1454. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1455. if (pIntrinsic->bReadNone)
  1456. FD->addAttr(ConstAttr::CreateImplicit(context));
  1457. if (pIntrinsic->bReadOnly)
  1458. FD->addAttr(PureAttr::CreateImplicit(context));
  1459. }
  1460. static
  1461. FunctionDecl *AddHLSLIntrinsicFunction(
  1462. ASTContext &context, _In_ NamespaceDecl *NS,
  1463. LPCSTR tableName, LPCSTR lowering,
  1464. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1465. _In_count_(functionArgTypeCount) QualType *functionArgQualTypes,
  1466. _In_range_(0, g_MaxIntrinsicParamCount - 1) size_t functionArgTypeCount) {
  1467. DXASSERT(functionArgTypeCount - 1 <= g_MaxIntrinsicParamCount,
  1468. "otherwise g_MaxIntrinsicParamCount should be larger");
  1469. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1470. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1471. InitParamMods(pIntrinsic, paramMods);
  1472. // Change dest address into reference type for atomic.
  1473. if (IsBuiltinTable(tableName)) {
  1474. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1475. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1476. "else operation was misrecognized");
  1477. functionArgQualTypes[kAtomicDstOperandIdx] =
  1478. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1479. }
  1480. }
  1481. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1482. // Change out/inout param to reference type.
  1483. if (paramMods[i-1].isAnyOut()) {
  1484. QualType Ty = functionArgQualTypes[i];
  1485. // Aggregate type will be indirect param convert to pointer type.
  1486. // Don't need add reference for it.
  1487. if ((!Ty->isArrayType() && !Ty->isRecordType()) ||
  1488. hlsl::IsHLSLVecMatType(Ty)) {
  1489. functionArgQualTypes[i] = context.getLValueReferenceType(Ty);
  1490. }
  1491. }
  1492. }
  1493. IdentifierInfo &functionId = context.Idents.get(
  1494. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1495. DeclarationName functionName(&functionId);
  1496. QualType functionType = context.getFunctionType(
  1497. functionArgQualTypes[0],
  1498. ArrayRef<QualType>(functionArgQualTypes + 1,
  1499. functionArgQualTypes + functionArgTypeCount),
  1500. clang::FunctionProtoType::ExtProtoInfo(), paramMods);
  1501. FunctionDecl *functionDecl = FunctionDecl::Create(
  1502. context, currentDeclContext, NoLoc,
  1503. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1504. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1505. currentDeclContext->addDecl(functionDecl);
  1506. functionDecl->setLexicalDeclContext(currentDeclContext);
  1507. // put under hlsl namespace
  1508. functionDecl->setDeclContext(NS);
  1509. // Add intrinsic attribute
  1510. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1511. ParmVarDecl *paramDecls[g_MaxIntrinsicParamCount];
  1512. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1513. IdentifierInfo &parameterId = context.Idents.get(
  1514. StringRef(pIntrinsic->pArgs[i].pName), tok::TokenKind::identifier);
  1515. ParmVarDecl *paramDecl =
  1516. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1517. functionArgQualTypes[i], nullptr,
  1518. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1519. functionDecl->addDecl(paramDecl);
  1520. paramDecls[i - 1] = paramDecl;
  1521. }
  1522. functionDecl->setParams(
  1523. ArrayRef<ParmVarDecl *>(paramDecls, functionArgTypeCount - 1));
  1524. functionDecl->setImplicit(true);
  1525. return functionDecl;
  1526. }
  1527. /// <summary>
  1528. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1529. /// </summary>
  1530. static
  1531. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1532. {
  1533. DXASSERT_NOMSG(expr != nullptr);
  1534. expr = expr->IgnoreParens();
  1535. return
  1536. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1537. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1538. }
  1539. /// <summary>
  1540. /// Silences diagnostics for the initialization sequence, typically because they have already
  1541. /// been emitted.
  1542. /// </summary>
  1543. static
  1544. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1545. {
  1546. DXASSERT_NOMSG(initSequence != nullptr);
  1547. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1548. }
  1549. class UsedIntrinsic
  1550. {
  1551. public:
  1552. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1553. {
  1554. // The canonical representations are unique'd in an ASTContext, and so these
  1555. // should be stable.
  1556. return RHS.getTypePtr() - LHS.getTypePtr();
  1557. }
  1558. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1559. {
  1560. // The intrinsics are defined in a single static table, and so should be stable.
  1561. return RHS - LHS;
  1562. }
  1563. int compare(const UsedIntrinsic& other) const
  1564. {
  1565. // Check whether it's the same instance.
  1566. if (this == &other) return 0;
  1567. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1568. if (result != 0) return result;
  1569. // At this point, it's the exact same intrinsic name.
  1570. // Compare the arguments for ordering then.
  1571. DXASSERT(m_argLength == other.m_argLength, "intrinsics aren't overloaded on argument count, so we should never create a key with different #s");
  1572. for (size_t i = 0; i < m_argLength; i++) {
  1573. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1574. if (argComparison != 0) return argComparison;
  1575. }
  1576. // Exactly the same.
  1577. return 0;
  1578. }
  1579. public:
  1580. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, _In_count_(argCount) QualType* args, size_t argCount)
  1581. : m_argLength(argCount), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1582. {
  1583. std::copy(args, args + argCount, m_args);
  1584. }
  1585. void setFunctionDecl(FunctionDecl* value) const
  1586. {
  1587. DXASSERT(value != nullptr, "no reason to clear this out");
  1588. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1589. m_functionDecl = value;
  1590. }
  1591. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1592. bool operator==(const UsedIntrinsic& other) const
  1593. {
  1594. return compare(other) == 0;
  1595. }
  1596. bool operator<(const UsedIntrinsic& other) const
  1597. {
  1598. return compare(other) < 0;
  1599. }
  1600. private:
  1601. QualType m_args[g_MaxIntrinsicParamCount+1];
  1602. size_t m_argLength;
  1603. const HLSL_INTRINSIC* m_intrinsicSource;
  1604. mutable FunctionDecl* m_functionDecl;
  1605. };
  1606. template <typename T>
  1607. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1608. {
  1609. if (ptr != nullptr)
  1610. {
  1611. *ptr = value;
  1612. }
  1613. }
  1614. static bool CombineBasicTypes(ArBasicKind LeftKind,
  1615. ArBasicKind RightKind,
  1616. _Out_ ArBasicKind* pOutKind)
  1617. {
  1618. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1619. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1620. return false;
  1621. }
  1622. if (LeftKind == RightKind) {
  1623. *pOutKind = LeftKind;
  1624. return true;
  1625. }
  1626. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1627. UINT uRightProps = GetBasicKindProps(RightKind);
  1628. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1629. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1630. UINT uBothFlags = uLeftProps & uRightProps;
  1631. UINT uEitherFlags = uLeftProps | uRightProps;
  1632. // Notes: all numeric types have either BPROP_FLOATING or BPROP_INTEGER (even bool)
  1633. // unsigned only applies to non-literal ints, not bool or enum
  1634. // literals, bool, and enum are all BPROP_BITS0
  1635. if (uBothFlags & BPROP_BOOLEAN) {
  1636. *pOutKind = AR_BASIC_BOOL;
  1637. return true;
  1638. }
  1639. bool bFloatResult = 0 != (uEitherFlags & BPROP_FLOATING);
  1640. if (uBothFlags & BPROP_LITERAL) {
  1641. *pOutKind = bFloatResult ? AR_BASIC_LITERAL_FLOAT : AR_BASIC_LITERAL_INT;
  1642. return true;
  1643. }
  1644. // Starting approximation of result properties:
  1645. // - float if either are float, otherwise int (see Notes above)
  1646. // - min/partial precision if both have same flag
  1647. // - if not float, add unsigned if either is unsigned
  1648. UINT uResultFlags =
  1649. (uBothFlags & (BPROP_INTEGER | BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION)) |
  1650. (uEitherFlags & BPROP_FLOATING) |
  1651. (!bFloatResult ? (uEitherFlags & BPROP_UNSIGNED) : 0);
  1652. // If one is literal/bool/enum, use min/partial precision from the other
  1653. if (uEitherFlags & (BPROP_LITERAL | BPROP_BOOLEAN | BPROP_ENUM)) {
  1654. uResultFlags |= uEitherFlags & (BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION);
  1655. }
  1656. // Now if we have partial precision, we know the result must be half
  1657. if (uResultFlags & BPROP_PARTIAL_PRECISION) {
  1658. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1659. return true;
  1660. }
  1661. // uBits are already initialized to max of either side, so now:
  1662. // if only one is float, get result props from float side
  1663. // min16float + int -> min16float
  1664. // also take min precision from that side
  1665. if (bFloatResult && 0 == (uBothFlags & BPROP_FLOATING)) {
  1666. uResultFlags = (uLeftProps & BPROP_FLOATING) ? uLeftProps : uRightProps;
  1667. uBits = GET_BPROP_BITS(uResultFlags);
  1668. uResultFlags &= ~BPROP_LITERAL;
  1669. }
  1670. bool bMinPrecisionResult = uResultFlags & BPROP_MIN_PRECISION;
  1671. // if uBits is 0 here, upgrade to 32-bits
  1672. // this happens if bool, literal or enum on both sides,
  1673. // or if float came from literal side
  1674. if (uBits == BPROP_BITS0)
  1675. uBits = BPROP_BITS32;
  1676. DXASSERT(uBits != BPROP_BITS0, "CombineBasicTypes: uBits should not be zero at this point");
  1677. DXASSERT(uBits != BPROP_BITS8, "CombineBasicTypes: 8-bit types not supported at this time");
  1678. if (bMinPrecisionResult) {
  1679. DXASSERT(uBits < BPROP_BITS32, "CombineBasicTypes: min-precision result must be less than 32-bits");
  1680. } else {
  1681. DXASSERT(uBits > BPROP_BITS12, "CombineBasicTypes: 10 or 12 bit result must be min precision");
  1682. }
  1683. if (bFloatResult) {
  1684. DXASSERT(uBits != BPROP_BITS12, "CombineBasicTypes: 12-bit result must be int");
  1685. } else {
  1686. DXASSERT(uBits != BPROP_BITS10, "CombineBasicTypes: 10-bit result must be float");
  1687. }
  1688. if (uBits == BPROP_BITS12) {
  1689. DXASSERT(!(uResultFlags & BPROP_UNSIGNED), "CombineBasicTypes: 12-bit result must not be unsigned");
  1690. }
  1691. if (bFloatResult) {
  1692. switch (uBits) {
  1693. case BPROP_BITS10:
  1694. *pOutKind = AR_BASIC_MIN10FLOAT;
  1695. break;
  1696. case BPROP_BITS16:
  1697. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  1698. break;
  1699. case BPROP_BITS32:
  1700. *pOutKind = AR_BASIC_FLOAT32;
  1701. break;
  1702. case BPROP_BITS64:
  1703. *pOutKind = AR_BASIC_FLOAT64;
  1704. break;
  1705. default:
  1706. DXASSERT(false, "Unexpected bit count for float result");
  1707. break;
  1708. }
  1709. } else {
  1710. // int or unsigned int
  1711. switch (uBits) {
  1712. case BPROP_BITS12:
  1713. *pOutKind = AR_BASIC_MIN12INT;
  1714. break;
  1715. case BPROP_BITS16:
  1716. if (uResultFlags & BPROP_UNSIGNED)
  1717. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  1718. else
  1719. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  1720. break;
  1721. case BPROP_BITS32:
  1722. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT32 : AR_BASIC_INT32;
  1723. break;
  1724. case BPROP_BITS64:
  1725. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT64 : AR_BASIC_INT64;
  1726. break;
  1727. default:
  1728. DXASSERT(false, "Unexpected bit count for int result");
  1729. break;
  1730. }
  1731. }
  1732. return true;
  1733. }
  1734. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1735. {
  1736. };
  1737. static
  1738. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1739. {
  1740. DXASSERT_NOMSG(intrinsics != nullptr);
  1741. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1742. switch (kind)
  1743. {
  1744. case AR_OBJECT_TRIANGLESTREAM:
  1745. case AR_OBJECT_POINTSTREAM:
  1746. case AR_OBJECT_LINESTREAM:
  1747. *intrinsics = g_StreamMethods;
  1748. *intrinsicCount = _countof(g_StreamMethods);
  1749. break;
  1750. case AR_OBJECT_TEXTURE1D:
  1751. *intrinsics = g_Texture1DMethods;
  1752. *intrinsicCount = _countof(g_Texture1DMethods);
  1753. break;
  1754. case AR_OBJECT_TEXTURE1D_ARRAY:
  1755. *intrinsics = g_Texture1DArrayMethods;
  1756. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1757. break;
  1758. case AR_OBJECT_TEXTURE2D:
  1759. *intrinsics = g_Texture2DMethods;
  1760. *intrinsicCount = _countof(g_Texture2DMethods);
  1761. break;
  1762. case AR_OBJECT_TEXTURE2DMS:
  1763. *intrinsics = g_Texture2DMSMethods;
  1764. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1765. break;
  1766. case AR_OBJECT_TEXTURE2D_ARRAY:
  1767. *intrinsics = g_Texture2DArrayMethods;
  1768. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1769. break;
  1770. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1771. *intrinsics = g_Texture2DArrayMSMethods;
  1772. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1773. break;
  1774. case AR_OBJECT_TEXTURE3D:
  1775. *intrinsics = g_Texture3DMethods;
  1776. *intrinsicCount = _countof(g_Texture3DMethods);
  1777. break;
  1778. case AR_OBJECT_TEXTURECUBE:
  1779. *intrinsics = g_TextureCUBEMethods;
  1780. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1781. break;
  1782. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1783. *intrinsics = g_TextureCUBEArrayMethods;
  1784. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1785. break;
  1786. case AR_OBJECT_BUFFER:
  1787. *intrinsics = g_BufferMethods;
  1788. *intrinsicCount = _countof(g_BufferMethods);
  1789. break;
  1790. case AR_OBJECT_RWTEXTURE1D:
  1791. case AR_OBJECT_ROVTEXTURE1D:
  1792. *intrinsics = g_RWTexture1DMethods;
  1793. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1794. break;
  1795. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1796. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1797. *intrinsics = g_RWTexture1DArrayMethods;
  1798. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1799. break;
  1800. case AR_OBJECT_RWTEXTURE2D:
  1801. case AR_OBJECT_ROVTEXTURE2D:
  1802. *intrinsics = g_RWTexture2DMethods;
  1803. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1804. break;
  1805. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1806. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1807. *intrinsics = g_RWTexture2DArrayMethods;
  1808. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1809. break;
  1810. case AR_OBJECT_RWTEXTURE3D:
  1811. case AR_OBJECT_ROVTEXTURE3D:
  1812. *intrinsics = g_RWTexture3DMethods;
  1813. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1814. break;
  1815. case AR_OBJECT_RWBUFFER:
  1816. case AR_OBJECT_ROVBUFFER:
  1817. *intrinsics = g_RWBufferMethods;
  1818. *intrinsicCount = _countof(g_RWBufferMethods);
  1819. break;
  1820. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1821. *intrinsics = g_ByteAddressBufferMethods;
  1822. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1823. break;
  1824. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1825. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1826. *intrinsics = g_RWByteAddressBufferMethods;
  1827. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1828. break;
  1829. case AR_OBJECT_STRUCTURED_BUFFER:
  1830. *intrinsics = g_StructuredBufferMethods;
  1831. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1832. break;
  1833. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1834. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1835. *intrinsics = g_RWStructuredBufferMethods;
  1836. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1837. break;
  1838. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1839. *intrinsics = g_AppendStructuredBufferMethods;
  1840. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1841. break;
  1842. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1843. *intrinsics = g_ConsumeStructuredBufferMethods;
  1844. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1845. break;
  1846. // SPIRV change starts
  1847. #ifdef ENABLE_SPIRV_CODEGEN
  1848. case AR_OBJECT_VK_SUBPASS_INPUT:
  1849. *intrinsics = g_VkSubpassInputMethods;
  1850. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  1851. break;
  1852. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1853. *intrinsics = g_VkSubpassInputMSMethods;
  1854. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  1855. break;
  1856. #endif // ENABLE_SPIRV_CODEGEN
  1857. // SPIRV change ends
  1858. default:
  1859. *intrinsics = nullptr;
  1860. *intrinsicCount = 0;
  1861. break;
  1862. }
  1863. }
  1864. static
  1865. bool IsRowOrColumnVariable(size_t value)
  1866. {
  1867. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1868. }
  1869. static
  1870. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1871. {
  1872. return
  1873. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1874. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1875. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1876. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1877. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1878. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1879. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1880. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1881. value == LICOMPTYPE_ANY; // any time
  1882. }
  1883. static
  1884. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1885. {
  1886. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1887. }
  1888. static
  1889. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  1890. {
  1891. // Note that LITEMPLATE_OBJECT can accept different types, but it
  1892. // specifies a single 'layout'. In practice, this information is used
  1893. // together with a component type that specifies a single object.
  1894. return value == LITEMPLATE_ANY; // Any layout
  1895. }
  1896. static
  1897. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  1898. {
  1899. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  1900. }
  1901. static
  1902. bool TemplateHasDefaultType(ArBasicKind kind)
  1903. {
  1904. switch (kind) {
  1905. case AR_OBJECT_BUFFER:
  1906. case AR_OBJECT_TEXTURE1D:
  1907. case AR_OBJECT_TEXTURE2D:
  1908. case AR_OBJECT_TEXTURE3D:
  1909. case AR_OBJECT_TEXTURE1D_ARRAY:
  1910. case AR_OBJECT_TEXTURE2D_ARRAY:
  1911. case AR_OBJECT_TEXTURECUBE:
  1912. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1913. // SPIRV change starts
  1914. #ifdef ENABLE_SPIRV_CODEGEN
  1915. case AR_OBJECT_VK_SUBPASS_INPUT:
  1916. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1917. #endif // ENABLE_SPIRV_CODEGEN
  1918. // SPIRV change ends
  1919. return true;
  1920. default:
  1921. // Objects with default types return true. Everything else is false.
  1922. return false;
  1923. }
  1924. }
  1925. /// <summary>
  1926. /// Use this class to iterate over intrinsic definitions that come from an external source.
  1927. /// </summary>
  1928. class IntrinsicTableDefIter
  1929. {
  1930. private:
  1931. StringRef _typeName;
  1932. StringRef _functionName;
  1933. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  1934. const HLSL_INTRINSIC* _tableIntrinsic;
  1935. UINT64 _tableLookupCookie;
  1936. unsigned _tableIndex;
  1937. unsigned _argCount;
  1938. bool _firstChecked;
  1939. IntrinsicTableDefIter(
  1940. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1941. StringRef typeName,
  1942. StringRef functionName,
  1943. unsigned argCount) :
  1944. _typeName(typeName), _functionName(functionName), _tables(tables),
  1945. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  1946. _argCount(argCount), _firstChecked(false)
  1947. {
  1948. }
  1949. void CheckForIntrinsic() {
  1950. if (_tableIndex >= _tables.size()) {
  1951. return;
  1952. }
  1953. _firstChecked = true;
  1954. // TODO: review this - this will allocate at least once per string
  1955. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  1956. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  1957. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  1958. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  1959. _tableLookupCookie = 0;
  1960. _tableIntrinsic = nullptr;
  1961. }
  1962. }
  1963. void MoveToNext() {
  1964. for (;;) {
  1965. // If we don't have an intrinsic, try the following table.
  1966. if (_firstChecked && _tableIntrinsic == nullptr) {
  1967. _tableIndex++;
  1968. }
  1969. CheckForIntrinsic();
  1970. if (_tableIndex == _tables.size() ||
  1971. (_tableIntrinsic != nullptr &&
  1972. _tableIntrinsic->uNumArgs ==
  1973. (_argCount + 1))) // uNumArgs includes return
  1974. break;
  1975. }
  1976. }
  1977. public:
  1978. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1979. StringRef typeName,
  1980. StringRef functionName,
  1981. unsigned argCount)
  1982. {
  1983. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  1984. return result;
  1985. }
  1986. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  1987. {
  1988. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  1989. result._tableIndex = tables.size();
  1990. return result;
  1991. }
  1992. bool operator!=(const IntrinsicTableDefIter& other)
  1993. {
  1994. if (!_firstChecked) {
  1995. MoveToNext();
  1996. }
  1997. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  1998. }
  1999. const HLSL_INTRINSIC* operator*()
  2000. {
  2001. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  2002. return _tableIntrinsic;
  2003. }
  2004. LPCSTR GetTableName()
  2005. {
  2006. LPCSTR tableName = nullptr;
  2007. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  2008. return nullptr;
  2009. }
  2010. return tableName;
  2011. }
  2012. LPCSTR GetLoweringStrategy()
  2013. {
  2014. LPCSTR lowering = nullptr;
  2015. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  2016. return nullptr;
  2017. }
  2018. return lowering;
  2019. }
  2020. IntrinsicTableDefIter& operator++()
  2021. {
  2022. MoveToNext();
  2023. return *this;
  2024. }
  2025. };
  2026. /// <summary>
  2027. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2028. /// </summary>
  2029. class IntrinsicDefIter
  2030. {
  2031. const HLSL_INTRINSIC* _current;
  2032. const HLSL_INTRINSIC* _end;
  2033. IntrinsicTableDefIter _tableIter;
  2034. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2035. _current(value), _end(end), _tableIter(tableIter)
  2036. { }
  2037. public:
  2038. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2039. {
  2040. return IntrinsicDefIter(start, table + count, tableIter);
  2041. }
  2042. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2043. {
  2044. return IntrinsicDefIter(table + count, table + count, tableIter);
  2045. }
  2046. bool operator!=(const IntrinsicDefIter& other)
  2047. {
  2048. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2049. }
  2050. const HLSL_INTRINSIC* operator*()
  2051. {
  2052. return (_current != _end) ? _current : *_tableIter;
  2053. }
  2054. LPCSTR GetTableName()
  2055. {
  2056. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2057. }
  2058. LPCSTR GetLoweringStrategy()
  2059. {
  2060. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2061. }
  2062. IntrinsicDefIter& operator++()
  2063. {
  2064. if (_current != _end) {
  2065. const HLSL_INTRINSIC* next = _current + 1;
  2066. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2067. _current = next;
  2068. }
  2069. else {
  2070. _current = _end;
  2071. }
  2072. } else {
  2073. ++_tableIter;
  2074. }
  2075. return *this;
  2076. }
  2077. };
  2078. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2079. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2080. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2081. }
  2082. static void CreateSimpleField(clang::ASTContext &context, CXXRecordDecl *recordDecl, StringRef Name,
  2083. QualType Ty, AccessSpecifier access = AccessSpecifier::AS_public) {
  2084. IdentifierInfo &fieldId =
  2085. context.Idents.get(Name, tok::TokenKind::identifier);
  2086. TypeSourceInfo *filedTypeSource = context.getTrivialTypeSourceInfo(Ty, NoLoc);
  2087. const bool MutableFalse = false;
  2088. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  2089. FieldDecl *fieldDecl =
  2090. FieldDecl::Create(context, recordDecl, NoLoc, NoLoc, &fieldId, Ty,
  2091. filedTypeSource, nullptr, MutableFalse, initStyle);
  2092. fieldDecl->setAccess(access);
  2093. fieldDecl->setImplicit(true);
  2094. recordDecl->addDecl(fieldDecl);
  2095. }
  2096. // struct RayDesc
  2097. //{
  2098. // float3 Origin;
  2099. // float TMin;
  2100. // float3 Direction;
  2101. // float TMax;
  2102. //};
  2103. static CXXRecordDecl *CreateRayDescStruct(clang::ASTContext &context,
  2104. QualType float3Ty) {
  2105. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  2106. IdentifierInfo &rayDesc =
  2107. context.Idents.get(StringRef("RayDesc"), tok::TokenKind::identifier);
  2108. CXXRecordDecl *rayDescDecl = CXXRecordDecl::Create(
  2109. context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc,
  2110. &rayDesc, nullptr, DelayTypeCreationTrue);
  2111. rayDescDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2112. rayDescDecl->startDefinition();
  2113. QualType floatTy = context.FloatTy;
  2114. // float3 Origin;
  2115. CreateSimpleField(context, rayDescDecl, "Origin", float3Ty);
  2116. // float TMin;
  2117. CreateSimpleField(context, rayDescDecl, "TMin", floatTy);
  2118. // float3 Direction;
  2119. CreateSimpleField(context, rayDescDecl, "Direction", float3Ty);
  2120. // float TMax;
  2121. CreateSimpleField(context, rayDescDecl, "TMax", floatTy);
  2122. rayDescDecl->completeDefinition();
  2123. // Both declarations need to be present for correct handling.
  2124. currentDeclContext->addDecl(rayDescDecl);
  2125. rayDescDecl->setImplicit(true);
  2126. return rayDescDecl;
  2127. }
  2128. // struct BuiltInTriangleIntersectionAttributes
  2129. // {
  2130. // float2 barycentrics;
  2131. // };
  2132. static CXXRecordDecl *AddBuiltInTriangleIntersectionAttributes(ASTContext& context, QualType baryType) {
  2133. DeclContext *curDC = context.getTranslationUnitDecl();
  2134. IdentifierInfo &attributesId =
  2135. context.Idents.get(StringRef("BuiltInTriangleIntersectionAttributes"),
  2136. tok::TokenKind::identifier);
  2137. CXXRecordDecl *attributesDecl = CXXRecordDecl::Create(
  2138. context, TagTypeKind::TTK_Struct, curDC, NoLoc, NoLoc,
  2139. &attributesId, nullptr, DelayTypeCreationTrue);
  2140. attributesDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2141. attributesDecl->startDefinition();
  2142. // float2 barycentrics;
  2143. CreateSimpleField(context, attributesDecl, "barycentrics", baryType);
  2144. attributesDecl->completeDefinition();
  2145. attributesDecl->setImplicit(true);
  2146. curDC->addDecl(attributesDecl);
  2147. return attributesDecl;
  2148. }
  2149. //
  2150. // Subobjects
  2151. static CXXRecordDecl *StartSubobjectDecl(ASTContext& context, const char *name) {
  2152. IdentifierInfo &id = context.Idents.get(StringRef(name), tok::TokenKind::identifier);
  2153. CXXRecordDecl *decl = CXXRecordDecl::Create( context, TagTypeKind::TTK_Struct,
  2154. context.getTranslationUnitDecl(), NoLoc, NoLoc, &id, nullptr, DelayTypeCreationTrue);
  2155. decl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2156. decl->startDefinition();
  2157. return decl;
  2158. }
  2159. void FinishSubobjectDecl(ASTContext& context, CXXRecordDecl *decl) {
  2160. decl->completeDefinition();
  2161. context.getTranslationUnitDecl()->addDecl(decl);
  2162. decl->setImplicit(true);
  2163. }
  2164. // struct StateObjectConfig
  2165. // {
  2166. // uint32_t Flags;
  2167. // };
  2168. static CXXRecordDecl *CreateSubobjectStateObjectConfig(ASTContext& context) {
  2169. CXXRecordDecl *decl = StartSubobjectDecl(context, "StateObjectConfig");
  2170. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2171. FinishSubobjectDecl(context, decl);
  2172. return decl;
  2173. }
  2174. // struct GlobalRootSignature
  2175. // {
  2176. // string signature;
  2177. // };
  2178. static CXXRecordDecl *CreateSubobjectRootSignature(ASTContext& context, bool global) {
  2179. CXXRecordDecl *decl = StartSubobjectDecl(context, global ? "GlobalRootSignature" : "LocalRootSignature");
  2180. CreateSimpleField(context, decl, "Data", context.HLSLStringTy, AccessSpecifier::AS_private);
  2181. FinishSubobjectDecl(context, decl);
  2182. return decl;
  2183. }
  2184. // struct SubobjectToExportsAssociation
  2185. // {
  2186. // string Subobject;
  2187. // string Exports;
  2188. // };
  2189. static CXXRecordDecl *CreateSubobjectSubobjectToExportsAssoc(ASTContext& context) {
  2190. CXXRecordDecl *decl = StartSubobjectDecl(context, "SubobjectToExportsAssociation");
  2191. CreateSimpleField(context, decl, "Subobject", context.HLSLStringTy, AccessSpecifier::AS_private);
  2192. CreateSimpleField(context, decl, "Exports", context.HLSLStringTy, AccessSpecifier::AS_private);
  2193. FinishSubobjectDecl(context, decl);
  2194. return decl;
  2195. }
  2196. // struct RaytracingShaderConfig
  2197. // {
  2198. // uint32_t MaxPayloadSizeInBytes;
  2199. // uint32_t MaxAttributeSizeInBytes;
  2200. // };
  2201. static CXXRecordDecl *CreateSubobjectRaytracingShaderConfig(ASTContext& context) {
  2202. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingShaderConfig");
  2203. CreateSimpleField(context, decl, "MaxPayloadSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2204. CreateSimpleField(context, decl, "MaxAttributeSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2205. FinishSubobjectDecl(context, decl);
  2206. return decl;
  2207. }
  2208. // struct RaytracingPipelineConfig
  2209. // {
  2210. // uint32_t MaxTraceRecursionDepth;
  2211. // };
  2212. static CXXRecordDecl *CreateSubobjectRaytracingPipelineConfig(ASTContext& context) {
  2213. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingPipelineConfig");
  2214. CreateSimpleField(context, decl, "MaxTraceRecursionDepth", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2215. FinishSubobjectDecl(context, decl);
  2216. return decl;
  2217. }
  2218. // struct TriangleHitGroup
  2219. // {
  2220. // string AnyHit;
  2221. // string ClosestHit;
  2222. // };
  2223. static CXXRecordDecl *CreateSubobjectTriangleHitGroup(ASTContext& context) {
  2224. CXXRecordDecl *decl = StartSubobjectDecl(context, "TriangleHitGroup");
  2225. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2226. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2227. FinishSubobjectDecl(context, decl);
  2228. return decl;
  2229. }
  2230. // struct ProceduralPrimitiveHitGroup
  2231. // {
  2232. // string AnyHit;
  2233. // string ClosestHit;
  2234. // string Intersection;
  2235. // };
  2236. static CXXRecordDecl *CreateSubobjectProceduralPrimitiveHitGroup(ASTContext& context) {
  2237. CXXRecordDecl *decl = StartSubobjectDecl(context, "ProceduralPrimitiveHitGroup");
  2238. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2239. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2240. CreateSimpleField(context, decl, "Intersection", context.HLSLStringTy, AccessSpecifier::AS_private);
  2241. FinishSubobjectDecl(context, decl);
  2242. return decl;
  2243. }
  2244. //
  2245. // This is similar to clang/Analysis/CallGraph, but the following differences
  2246. // motivate this:
  2247. //
  2248. // - track traversed vs. observed nodes explicitly
  2249. // - fully visit all reachable functions
  2250. // - merge graph visiting with checking for recursion
  2251. // - track global variables and types used (NYI)
  2252. //
  2253. namespace hlsl {
  2254. struct CallNode {
  2255. FunctionDecl *CallerFn;
  2256. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2257. };
  2258. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2259. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2260. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2261. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2262. // Returns the definition of a function.
  2263. // This serves two purposes - ignore built-in functions, and pick
  2264. // a single Decl * to be used in maps and sets.
  2265. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2266. if (!F) return nullptr;
  2267. if (F->doesThisDeclarationHaveABody()) return F;
  2268. F = F->getFirstDecl();
  2269. for (auto &&Candidate : F->redecls()) {
  2270. if (Candidate->doesThisDeclarationHaveABody()) {
  2271. return Candidate;
  2272. }
  2273. }
  2274. return nullptr;
  2275. }
  2276. // AST visitor that maintains visited and pending collections, as well
  2277. // as recording nodes of caller/callees.
  2278. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2279. private:
  2280. CallNodes &m_callNodes;
  2281. FunctionSet &m_visitedFunctions;
  2282. PendingFunctions &m_pendingFunctions;
  2283. FunctionDecl *m_source;
  2284. CallNodes::iterator m_sourceIt;
  2285. public:
  2286. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2287. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2288. : m_callNodes(callNodes),
  2289. m_visitedFunctions(visitedFunctions),
  2290. m_pendingFunctions(pendingFunctions) {}
  2291. void setSourceFn(FunctionDecl *F) {
  2292. F = getFunctionWithBody(F);
  2293. m_source = F;
  2294. m_sourceIt = m_callNodes.find(F);
  2295. }
  2296. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2297. ValueDecl *valueDecl = ref->getDecl();
  2298. FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(valueDecl);
  2299. fnDecl = getFunctionWithBody(fnDecl);
  2300. if (fnDecl) {
  2301. if (m_sourceIt == m_callNodes.end()) {
  2302. auto result = m_callNodes.insert(
  2303. std::pair<FunctionDecl *, CallNode>(m_source, CallNode{ m_source }));
  2304. DXASSERT(result.second == true,
  2305. "else setSourceFn didn't assign m_sourceIt");
  2306. m_sourceIt = result.first;
  2307. }
  2308. m_sourceIt->second.CalleeFns.insert(fnDecl);
  2309. if (!m_visitedFunctions.count(fnDecl)) {
  2310. m_pendingFunctions.push_back(fnDecl);
  2311. }
  2312. }
  2313. return true;
  2314. }
  2315. };
  2316. // A call graph that can check for reachability and recursion efficiently.
  2317. class CallGraphWithRecurseGuard {
  2318. private:
  2319. CallNodes m_callNodes;
  2320. FunctionSet m_visitedFunctions;
  2321. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2322. FunctionDecl *D) const {
  2323. if (CallStack.insert(D).second == false)
  2324. return D;
  2325. auto node = m_callNodes.find(D);
  2326. if (node != m_callNodes.end()) {
  2327. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2328. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2329. if (pResult)
  2330. return pResult;
  2331. }
  2332. }
  2333. CallStack.erase(D);
  2334. return nullptr;
  2335. }
  2336. public:
  2337. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2338. DXASSERT_NOMSG(EntryFnDecl);
  2339. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2340. PendingFunctions pendingFunctions;
  2341. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2342. pendingFunctions.push_back(EntryFnDecl);
  2343. while (!pendingFunctions.empty()) {
  2344. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2345. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2346. visitor.setSourceFn(pendingDecl);
  2347. visitor.TraverseDecl(pendingDecl);
  2348. }
  2349. }
  2350. }
  2351. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2352. FnCallStack CallStack;
  2353. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2354. return CheckRecursion(CallStack, EntryFnDecl);
  2355. }
  2356. void dump() const {
  2357. OutputDebugStringW(L"Call Nodes:\r\n");
  2358. for (auto &node : m_callNodes) {
  2359. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), (void*)node.first);
  2360. for (auto callee : node.second.CalleeFns) {
  2361. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), (void*)callee);
  2362. }
  2363. }
  2364. }
  2365. };
  2366. }
  2367. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2368. static
  2369. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2370. {
  2371. DXASSERT_NOMSG(context != nullptr);
  2372. DXASSERT_NOMSG(ident != nullptr);
  2373. DXASSERT_NOMSG(!baseType.isNull());
  2374. DeclContext* declContext = context->getTranslationUnitDecl();
  2375. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2376. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2377. declContext->addDecl(decl);
  2378. decl->setImplicit(true);
  2379. return decl;
  2380. }
  2381. class HLSLExternalSource : public ExternalSemaSource {
  2382. private:
  2383. // Inner types.
  2384. struct FindStructBasicTypeResult {
  2385. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2386. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2387. FindStructBasicTypeResult(ArBasicKind kind,
  2388. unsigned int basicKindAsTypeIndex)
  2389. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2390. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2391. };
  2392. // Declaration for matrix and vector templates.
  2393. ClassTemplateDecl* m_matrixTemplateDecl;
  2394. ClassTemplateDecl* m_vectorTemplateDecl;
  2395. // Namespace decl for hlsl intrin functions
  2396. NamespaceDecl* m_hlslNSDecl;
  2397. // Context being processed.
  2398. _Notnull_ ASTContext* m_context;
  2399. // Semantic analyzer being processed.
  2400. Sema* m_sema;
  2401. // Intrinsic tables available externally.
  2402. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2403. // Scalar types indexed by HLSLScalarType.
  2404. QualType m_scalarTypes[HLSLScalarTypeCount];
  2405. // Scalar types already built.
  2406. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2407. // 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.
  2408. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2409. // Matrix types already built, in shorthand form.
  2410. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2411. // Vector types already built.
  2412. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2413. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2414. // BuiltinType for each scalar type.
  2415. QualType m_baseTypes[HLSLScalarTypeCount];
  2416. // String type
  2417. QualType m_hlslStringType;
  2418. TypedefDecl* m_hlslStringTypedef;
  2419. // Built-in object types declarations, indexed by basic kind constant.
  2420. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2421. // Map from object decl to the object index.
  2422. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2423. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2424. // Mask for object which not has methods created.
  2425. uint64_t m_objectTypeLazyInitMask;
  2426. UsedIntrinsicStore m_usedIntrinsics;
  2427. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2428. void AddBaseTypes();
  2429. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2430. void AddHLSLScalarTypes();
  2431. /// <summary>Adds string type QualType for HSLS string declarations</summary>
  2432. void AddHLSLStringType();
  2433. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2434. {
  2435. DXASSERT_NOMSG(recordDecl != nullptr);
  2436. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2437. NamedDecl* parameterDecl = parameterList->getParam(0);
  2438. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2439. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2440. return QualType(parmDecl->getTypeForDecl(), 0);
  2441. }
  2442. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2443. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2444. {
  2445. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2446. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2447. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2448. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2449. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2450. if (
  2451. templateRef >= 0 &&
  2452. templateArg->uTemplateId == templateRef &&
  2453. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2454. componentRef >= 0 &&
  2455. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2456. componentArg->uComponentTypeId == 0 &&
  2457. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2458. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2459. !IsRowOrColumnVariable(matrixArg->uRows))
  2460. {
  2461. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2462. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2463. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2464. }
  2465. return QualType();
  2466. }
  2467. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2468. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2469. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2470. _Inout_ size_t* templateParamNamedDeclsCount)
  2471. {
  2472. DXASSERT_NOMSG(name != nullptr);
  2473. DXASSERT_NOMSG(recordDecl != nullptr);
  2474. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2475. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2476. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2477. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2478. // Create the declaration for the template parameter.
  2479. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2480. TemplateTypeParmDecl* templateTypeParmDecl =
  2481. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2482. id, TypenameTrue, ParameterPackFalse);
  2483. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2484. // Create the type that the parameter represents.
  2485. QualType result = m_context->getTemplateTypeParmType(
  2486. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2487. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2488. // it need not concern itself with maintaining this value.
  2489. (*templateParamNamedDeclsCount)++;
  2490. return result;
  2491. }
  2492. // Adds a function specified by the given intrinsic to a record declaration.
  2493. // The template depth will be zero for records that don't have a "template<>" line
  2494. // even if conceptual; or one if it does have one.
  2495. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2496. {
  2497. DXASSERT_NOMSG(recordDecl != nullptr);
  2498. DXASSERT_NOMSG(intrinsic != nullptr);
  2499. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2500. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2501. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2502. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2503. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2504. //
  2505. // Build template parameters, parameter types, and the return type.
  2506. // Parameter declarations are built after the function is created, to use it as their scope.
  2507. //
  2508. unsigned int numParams = intrinsic->uNumArgs - 1;
  2509. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2510. size_t templateParamNamedDeclsCount = 0;
  2511. QualType argsQTs[g_MaxIntrinsicParamCount];
  2512. StringRef argNames[g_MaxIntrinsicParamCount];
  2513. QualType functionResultQT;
  2514. DXASSERT(
  2515. _countof(templateParamNamedDecls) >= numParams + 1,
  2516. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2517. // Handle the return type.
  2518. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2519. // if (functionResultQT.isNull()) {
  2520. // Workaround for template parameter argument count mismatch.
  2521. // Create template parameter for return type always
  2522. // TODO: reenable the check and skip template argument.
  2523. functionResultQT = AddTemplateParamToArray(
  2524. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2525. &templateParamNamedDeclsCount);
  2526. // }
  2527. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2528. InitParamMods(intrinsic, paramMods);
  2529. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2530. // Handle parameters.
  2531. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2532. {
  2533. //
  2534. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2535. //
  2536. // However this may produce template instantiations with equivalent template arguments
  2537. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2538. // but the current intrinsic table has rules that are hard to process in their current form
  2539. // to find all cases.
  2540. //
  2541. char name[g_MaxIntrinsicParamName + 2];
  2542. name[0] = 'T';
  2543. name[1] = '\0';
  2544. strcat_s(name, intrinsic->pArgs[i].pName);
  2545. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2546. // Change out/inout param to reference type.
  2547. if (paramMods[i-1].isAnyOut())
  2548. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2549. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2550. }
  2551. // Create the declaration.
  2552. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2553. DeclarationName declarationName = DeclarationName(ii);
  2554. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2555. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2556. declarationName, true);
  2557. functionDecl->setImplicit(true);
  2558. // If the function is a template function, create the declaration and cross-reference.
  2559. if (templateParamNamedDeclsCount > 0)
  2560. {
  2561. hlsl::CreateFunctionTemplateDecl(
  2562. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2563. }
  2564. }
  2565. // Checks whether the two specified intrinsics generate equivalent templates.
  2566. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2567. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2568. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2569. {
  2570. if (left == right)
  2571. {
  2572. return true;
  2573. }
  2574. if (left == nullptr || right == nullptr)
  2575. {
  2576. return false;
  2577. }
  2578. return (left->uNumArgs == right->uNumArgs &&
  2579. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2580. }
  2581. // Adds all the intrinsic methods that correspond to the specified type.
  2582. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2583. {
  2584. DXASSERT_NOMSG(recordDecl != nullptr);
  2585. DXASSERT_NOMSG(templateDepth >= 0);
  2586. const HLSL_INTRINSIC* intrinsics;
  2587. const HLSL_INTRINSIC* prior = nullptr;
  2588. size_t intrinsicCount;
  2589. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2590. DXASSERT(
  2591. (intrinsics == nullptr) == (intrinsicCount == 0),
  2592. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2593. while (intrinsicCount--)
  2594. {
  2595. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2596. {
  2597. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2598. prior = intrinsics;
  2599. }
  2600. intrinsics++;
  2601. }
  2602. }
  2603. void AddDoubleSubscriptSupport(
  2604. _In_ ClassTemplateDecl* typeDecl,
  2605. _In_ CXXRecordDecl* recordDecl,
  2606. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2607. _In_z_ const char* type0Name,
  2608. _In_z_ const char* type1Name,
  2609. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2610. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2611. {
  2612. DXASSERT_NOMSG(typeDecl != nullptr);
  2613. DXASSERT_NOMSG(recordDecl != nullptr);
  2614. DXASSERT_NOMSG(memberName != nullptr);
  2615. DXASSERT_NOMSG(!elementType.isNull());
  2616. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2617. DXASSERT_NOMSG(type0Name != nullptr);
  2618. DXASSERT_NOMSG(type1Name != nullptr);
  2619. DXASSERT_NOMSG(indexer0Name != nullptr);
  2620. DXASSERT_NOMSG(!indexer0Type.isNull());
  2621. DXASSERT_NOMSG(indexer1Name != nullptr);
  2622. DXASSERT_NOMSG(!indexer1Type.isNull());
  2623. //
  2624. // Add inner types to the templates to represent the following C++ code inside the class.
  2625. // public:
  2626. // class sample_slice_type
  2627. // {
  2628. // public: TElement operator[](uint3 index);
  2629. // };
  2630. // class sample_type
  2631. // {
  2632. // public: sample_slice_type operator[](uint slice);
  2633. // };
  2634. // sample_type sample;
  2635. //
  2636. // Variable names reflect this structure, but this code will also produce the types
  2637. // for .mips access.
  2638. //
  2639. const bool MutableTrue = true;
  2640. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2641. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2642. &m_context->Idents.get(StringRef(type1Name)));
  2643. sampleSliceTypeDecl->setAccess(AS_public);
  2644. sampleSliceTypeDecl->setImplicit();
  2645. recordDecl->addDecl(sampleSliceTypeDecl);
  2646. sampleSliceTypeDecl->startDefinition();
  2647. const bool MutableFalse = false;
  2648. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2649. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2650. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2651. sliceHandleDecl->setAccess(AS_private);
  2652. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2653. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2654. sampleSliceTypeDecl, elementType,
  2655. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2656. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2657. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2658. sampleSliceTypeDecl->completeDefinition();
  2659. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2660. &m_context->Idents.get(StringRef(type0Name)));
  2661. sampleTypeDecl->setAccess(AS_public);
  2662. recordDecl->addDecl(sampleTypeDecl);
  2663. sampleTypeDecl->startDefinition();
  2664. sampleTypeDecl->setImplicit();
  2665. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2666. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2667. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2668. sampleHandleDecl->setAccess(AS_private);
  2669. sampleTypeDecl->addDecl(sampleHandleDecl);
  2670. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2671. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2672. sampleTypeDecl, m_context->getRValueReferenceType(sampleSliceType), // TODO: choose LValueRef if writable.
  2673. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2674. sampleTypeDecl->completeDefinition();
  2675. // Add subscript attribute
  2676. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2677. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2678. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2679. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2680. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2681. sampleFieldDecl->setAccess(AS_public);
  2682. recordDecl->addDecl(sampleFieldDecl);
  2683. }
  2684. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2685. _In_ CXXRecordDecl *recordDecl,
  2686. SubscriptOperatorRecord op) {
  2687. DXASSERT_NOMSG(typeDecl != nullptr);
  2688. DXASSERT_NOMSG(recordDecl != nullptr);
  2689. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2690. op.SubscriptCardinality <= 3);
  2691. DXASSERT(op.SubscriptCardinality > 0 ||
  2692. (op.HasMips == false && op.HasSample == false),
  2693. "objects that have .mips or .sample member also have a plain "
  2694. "subscript defined (otherwise static table is "
  2695. "likely incorrect, and this function won't know the cardinality "
  2696. "of the position parameter");
  2697. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2698. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2699. "read/write objects don't have .mips or .sample members");
  2700. // Return early if there is no work to be done.
  2701. if (op.SubscriptCardinality == 0) {
  2702. return;
  2703. }
  2704. const unsigned int templateDepth = 1;
  2705. // Add an operator[].
  2706. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2707. typeDecl->getTemplateParameters()->getParam(0));
  2708. QualType resultType = m_context->getTemplateTypeParmType(
  2709. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2710. if (isReadWrite)
  2711. resultType = m_context->getLValueReferenceType(resultType, false);
  2712. else
  2713. resultType = m_context->getRValueReferenceType(resultType);
  2714. QualType indexType =
  2715. op.SubscriptCardinality == 1
  2716. ? m_context->UnsignedIntTy
  2717. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2718. op.SubscriptCardinality);
  2719. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2720. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2721. ArrayRef<StringRef>(StringRef("index")),
  2722. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2723. hlsl::CreateFunctionTemplateDecl(
  2724. *m_context, recordDecl, functionDecl,
  2725. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2726. // Add a .mips member if necessary.
  2727. QualType uintType = m_context->UnsignedIntTy;
  2728. if (op.HasMips) {
  2729. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2730. templateTypeParmDecl, "mips_type",
  2731. "mips_slice_type", "mipSlice", uintType, "pos",
  2732. indexType);
  2733. }
  2734. // Add a .sample member if necessary.
  2735. if (op.HasSample) {
  2736. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2737. templateTypeParmDecl, "sample_type",
  2738. "sample_slice_type", "sampleSlice", uintType,
  2739. "pos", indexType);
  2740. // TODO: support operator[][](indexType, uint).
  2741. }
  2742. }
  2743. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2744. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2745. return a.first < b.first;
  2746. };
  2747. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2748. auto begin = m_objectTypeDeclsMap.begin();
  2749. auto end = m_objectTypeDeclsMap.end();
  2750. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2751. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2752. if (low == end)
  2753. return -1;
  2754. if (recordDecl == low->first)
  2755. return low->second;
  2756. else
  2757. return -1;
  2758. }
  2759. // Adds all built-in HLSL object types.
  2760. void AddObjectTypes()
  2761. {
  2762. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2763. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2764. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2765. m_objectTypeLazyInitMask = 0;
  2766. unsigned effectKindIndex = 0;
  2767. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2768. {
  2769. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2770. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2771. continue;
  2772. }
  2773. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2774. effectKindIndex = i;
  2775. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2776. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2777. const char* typeName = g_ArBasicTypeNames[kind];
  2778. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2779. CXXRecordDecl* recordDecl = nullptr;
  2780. if (kind == AR_OBJECT_RAY_DESC) {
  2781. QualType float3Ty = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 3);
  2782. recordDecl = CreateRayDescStruct(*m_context, float3Ty);
  2783. } else if (kind == AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES) {
  2784. QualType float2Type = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 2);
  2785. recordDecl = AddBuiltInTriangleIntersectionAttributes(*m_context, float2Type);
  2786. } else if (IsSubobjectBasicKind(kind)) {
  2787. switch (kind) {
  2788. case AR_OBJECT_STATE_OBJECT_CONFIG:
  2789. recordDecl = CreateSubobjectStateObjectConfig(*m_context);
  2790. break;
  2791. case AR_OBJECT_GLOBAL_ROOT_SIGNATURE:
  2792. recordDecl = CreateSubobjectRootSignature(*m_context, true);
  2793. break;
  2794. case AR_OBJECT_LOCAL_ROOT_SIGNATURE:
  2795. recordDecl = CreateSubobjectRootSignature(*m_context, false);
  2796. break;
  2797. case AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC:
  2798. recordDecl = CreateSubobjectSubobjectToExportsAssoc(*m_context);
  2799. break;
  2800. break;
  2801. case AR_OBJECT_RAYTRACING_SHADER_CONFIG:
  2802. recordDecl = CreateSubobjectRaytracingShaderConfig(*m_context);
  2803. break;
  2804. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG:
  2805. recordDecl = CreateSubobjectRaytracingPipelineConfig(*m_context);
  2806. break;
  2807. case AR_OBJECT_TRIANGLE_HIT_GROUP:
  2808. recordDecl = CreateSubobjectTriangleHitGroup(*m_context);
  2809. break;
  2810. case AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP:
  2811. recordDecl = CreateSubobjectProceduralPrimitiveHitGroup(*m_context);
  2812. break;
  2813. }
  2814. }
  2815. else if (templateArgCount == 0)
  2816. {
  2817. AddRecordTypeWithHandle(*m_context, &recordDecl, typeName);
  2818. DXASSERT(recordDecl != nullptr, "AddRecordTypeWithHandle failed to return the object declaration");
  2819. recordDecl->setImplicit(true);
  2820. }
  2821. else
  2822. {
  2823. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2824. ClassTemplateDecl* typeDecl = nullptr;
  2825. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2826. AddTemplateTypeWithHandle(*m_context, &typeDecl, &recordDecl, typeName, templateArgCount, typeDefault);
  2827. DXASSERT(typeDecl != nullptr, "AddTemplateTypeWithHandle failed to return the object declaration");
  2828. typeDecl->setImplicit(true);
  2829. recordDecl->setImplicit(true);
  2830. }
  2831. m_objectTypeDecls[i] = recordDecl;
  2832. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2833. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2834. }
  2835. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2836. {
  2837. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2838. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2839. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2840. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2841. currentDeclContext->addDecl(samplerDecl);
  2842. samplerDecl->setImplicit(true);
  2843. // Create decls for each deprecated effect object type:
  2844. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2845. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2846. for (unsigned i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2847. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2848. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2849. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2850. currentDeclContext->addDecl(effectObjDecl);
  2851. effectObjDecl->setImplicit(true);
  2852. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2853. }
  2854. }
  2855. // Make sure it's in order.
  2856. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2857. }
  2858. FunctionDecl* AddSubscriptSpecialization(
  2859. _In_ FunctionTemplateDecl* functionTemplate,
  2860. QualType objectElement,
  2861. const FindStructBasicTypeResult& findResult);
  2862. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  2863. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2864. }
  2865. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  2866. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2867. }
  2868. static TYPE_CONVERSION_REMARKS RemarksUnused;
  2869. static ImplicitConversionKind ImplicitConversionKindUnused;
  2870. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType,
  2871. ImplicitConversionKind &convKind = ImplicitConversionKindUnused,
  2872. TYPE_CONVERSION_REMARKS &Remarks = RemarksUnused);
  2873. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  2874. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2875. rowCount <= 4 && colCount <= 4);
  2876. TypedefDecl *qts =
  2877. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  2878. if (qts == nullptr) {
  2879. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  2880. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  2881. rowCount, colCount);
  2882. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  2883. }
  2884. return qts;
  2885. }
  2886. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  2887. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2888. colCount <= 4);
  2889. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  2890. if (qts == nullptr) {
  2891. QualType type = LookupVectorType(scalarType, colCount);
  2892. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  2893. colCount);
  2894. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  2895. }
  2896. return qts;
  2897. }
  2898. public:
  2899. HLSLExternalSource() :
  2900. m_matrixTemplateDecl(nullptr),
  2901. m_vectorTemplateDecl(nullptr),
  2902. m_context(nullptr),
  2903. m_sema(nullptr),
  2904. m_hlslStringTypedef(nullptr)
  2905. {
  2906. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  2907. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  2908. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  2909. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  2910. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  2911. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  2912. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  2913. }
  2914. ~HLSLExternalSource() { }
  2915. static HLSLExternalSource* FromSema(_In_ Sema* self)
  2916. {
  2917. DXASSERT_NOMSG(self != nullptr);
  2918. ExternalSemaSource* externalSource = self->getExternalSource();
  2919. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  2920. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  2921. return hlsl;
  2922. }
  2923. void InitializeSema(Sema& S) override
  2924. {
  2925. m_sema = &S;
  2926. S.addExternalSource(this);
  2927. AddObjectTypes();
  2928. AddStdIsEqualImplementation(S.getASTContext(), S);
  2929. for (auto && intrinsic : m_intrinsicTables) {
  2930. AddIntrinsicTableMethods(intrinsic);
  2931. }
  2932. }
  2933. void ForgetSema() override
  2934. {
  2935. m_sema = nullptr;
  2936. }
  2937. Sema* getSema() {
  2938. return m_sema;
  2939. }
  2940. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  2941. // We shouldn't create Typedef for built in scalar types.
  2942. // For built in scalar types, this funciton may be called for
  2943. // TypoCorrection. In that case, we return a nullptr.
  2944. if (m_scalarTypes[scalarType].isNull()) {
  2945. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  2946. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  2947. }
  2948. return m_scalarTypeDefs[scalarType];
  2949. }
  2950. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  2951. {
  2952. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  2953. if (qt.isNull()) {
  2954. // lazy initialization of scalar types
  2955. if (m_scalarTypes[scalarType].isNull()) {
  2956. LookupScalarTypeDef(scalarType);
  2957. }
  2958. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  2959. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  2960. }
  2961. return qt;
  2962. }
  2963. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  2964. {
  2965. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  2966. if (qt.isNull()) {
  2967. if (m_scalarTypes[scalarType].isNull()) {
  2968. LookupScalarTypeDef(scalarType);
  2969. }
  2970. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  2971. m_vectorTypes[scalarType][colCount - 1] = qt;
  2972. }
  2973. return qt;
  2974. }
  2975. TypedefDecl* GetStringTypedef() {
  2976. if (m_hlslStringTypedef == nullptr) {
  2977. m_hlslStringTypedef = CreateGlobalTypedef(m_context, "string", m_hlslStringType);
  2978. m_hlslStringType = m_context->getTypeDeclType(m_hlslStringTypedef);
  2979. }
  2980. DXASSERT_NOMSG(m_hlslStringTypedef != nullptr);
  2981. return m_hlslStringTypedef;
  2982. }
  2983. static bool IsSubobjectBasicKind(ArBasicKind kind) {
  2984. return kind >= AR_OBJECT_STATE_OBJECT_CONFIG && kind <= AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP;
  2985. }
  2986. bool IsSubobjectType(QualType type) {
  2987. return IsSubobjectBasicKind(GetTypeElementKind(type));
  2988. }
  2989. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  2990. // TODO: enalbe this once we introduce precise master option
  2991. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  2992. if (type == HLSLScalarType_int_min12) {
  2993. const char *PromotedType =
  2994. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  2995. : HLSLScalarTypeNames[HLSLScalarType_int16];
  2996. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2997. << HLSLScalarTypeNames[type] << PromotedType;
  2998. } else if (type == HLSLScalarType_float_min10) {
  2999. const char *PromotedType =
  3000. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  3001. : HLSLScalarTypeNames[HLSLScalarType_float16];
  3002. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3003. << HLSLScalarTypeNames[type] << PromotedType;
  3004. }
  3005. if (!UseMinPrecision) {
  3006. if (type == HLSLScalarType_float_min16) {
  3007. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3008. << HLSLScalarTypeNames[type]
  3009. << HLSLScalarTypeNames[HLSLScalarType_float16];
  3010. } else if (type == HLSLScalarType_int_min16) {
  3011. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3012. << HLSLScalarTypeNames[type]
  3013. << HLSLScalarTypeNames[HLSLScalarType_int16];
  3014. } else if (type == HLSLScalarType_uint_min16) {
  3015. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3016. << HLSLScalarTypeNames[type]
  3017. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  3018. }
  3019. }
  3020. }
  3021. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  3022. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  3023. switch (type) {
  3024. case HLSLScalarType_float16:
  3025. case HLSLScalarType_float32:
  3026. case HLSLScalarType_float64:
  3027. case HLSLScalarType_int16:
  3028. case HLSLScalarType_int32:
  3029. case HLSLScalarType_uint16:
  3030. case HLSLScalarType_uint32:
  3031. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  3032. << HLSLScalarTypeNames[type] << "2018";
  3033. return false;
  3034. default:
  3035. break;
  3036. }
  3037. }
  3038. if (getSema()->getLangOpts().UseMinPrecision) {
  3039. switch (type) {
  3040. case HLSLScalarType_float16:
  3041. case HLSLScalarType_int16:
  3042. case HLSLScalarType_uint16:
  3043. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  3044. << HLSLScalarTypeNames[type];
  3045. return false;
  3046. default:
  3047. break;
  3048. }
  3049. }
  3050. return true;
  3051. }
  3052. bool LookupUnqualified(LookupResult &R, Scope *S) override
  3053. {
  3054. const DeclarationNameInfo declName = R.getLookupNameInfo();
  3055. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3056. if (idInfo == nullptr) {
  3057. return false;
  3058. }
  3059. // Currently template instantiation is blocked when a fatal error is
  3060. // detected. So no faulting-in types at this point, instead we simply
  3061. // back out.
  3062. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  3063. return false;
  3064. }
  3065. StringRef nameIdentifier = idInfo->getName();
  3066. HLSLScalarType parsedType;
  3067. int rowCount;
  3068. int colCount;
  3069. // Try parsing hlsl scalar types that is not initialized at AST time.
  3070. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  3071. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  3072. if (rowCount == 0 && colCount == 0) { // scalar
  3073. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  3074. if (!typeDecl) return false;
  3075. R.addDecl(typeDecl);
  3076. }
  3077. else if (rowCount == 0) { // vector
  3078. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  3079. R.addDecl(qts);
  3080. }
  3081. else { // matrix
  3082. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  3083. R.addDecl(qts);
  3084. }
  3085. return true;
  3086. }
  3087. // string
  3088. else if (TryParseString(nameIdentifier.data(), nameIdentifier.size(), getSema()->getLangOpts())) {
  3089. TypedefDecl *strDecl = GetStringTypedef();
  3090. R.addDecl(strDecl);
  3091. }
  3092. return false;
  3093. }
  3094. /// <summary>
  3095. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  3096. /// </sumary>
  3097. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  3098. {
  3099. DXASSERT_NOMSG(type != nullptr);
  3100. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3101. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3102. if (templateSpecializationDecl) {
  3103. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  3104. if (decl == m_matrixTemplateDecl)
  3105. return AR_TOBJ_MATRIX;
  3106. else if (decl == m_vectorTemplateDecl)
  3107. return AR_TOBJ_VECTOR;
  3108. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  3109. return AR_TOBJ_OBJECT;
  3110. }
  3111. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3112. if (typeRecordDecl->getDeclContext()->isFileContext()) {
  3113. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3114. if (index != -1) {
  3115. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  3116. if ( AR_OBJECT_RAY_DESC == kind || AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES == kind)
  3117. return AR_TOBJ_COMPOUND;
  3118. }
  3119. return AR_TOBJ_OBJECT;
  3120. }
  3121. else
  3122. return AR_TOBJ_INNER_OBJ;
  3123. }
  3124. return AR_TOBJ_COMPOUND;
  3125. }
  3126. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  3127. bool IsBuiltInObjectType(QualType type)
  3128. {
  3129. type = GetStructuralForm(type);
  3130. if (!type.isNull() && type->isStructureOrClassType()) {
  3131. const RecordType* recordType = type->getAs<RecordType>();
  3132. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  3133. }
  3134. return false;
  3135. }
  3136. /// <summary>
  3137. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  3138. /// possibly refering to original template record if it's a specialization; this makes the result
  3139. /// suitable for looking up in initialization tables.
  3140. /// </summary>
  3141. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  3142. {
  3143. const CXXRecordDecl* recordDecl;
  3144. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  3145. {
  3146. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  3147. }
  3148. else
  3149. {
  3150. recordDecl = dyn_cast<CXXRecordDecl>(context);
  3151. }
  3152. return recordDecl;
  3153. }
  3154. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  3155. ArTypeObjectKind GetTypeObjectKind(QualType type)
  3156. {
  3157. DXASSERT_NOMSG(!type.isNull());
  3158. type = GetStructuralForm(type);
  3159. if (type->isVoidType()) return AR_TOBJ_VOID;
  3160. if (type->isArrayType()) {
  3161. return hlsl::IsArrayConstantStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_ARRAY;
  3162. }
  3163. if (type->isPointerType()) {
  3164. return hlsl::IsPointerStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_POINTER;
  3165. }
  3166. if (type->isStructureOrClassType()) {
  3167. const RecordType* recordType = type->getAs<RecordType>();
  3168. return ClassifyRecordType(recordType);
  3169. } else if (const InjectedClassNameType *ClassNameTy =
  3170. type->getAs<InjectedClassNameType>()) {
  3171. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  3172. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  3173. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3174. if (templateSpecializationDecl) {
  3175. ClassTemplateDecl *decl =
  3176. templateSpecializationDecl->getSpecializedTemplate();
  3177. if (decl == m_matrixTemplateDecl)
  3178. return AR_TOBJ_MATRIX;
  3179. else if (decl == m_vectorTemplateDecl)
  3180. return AR_TOBJ_VECTOR;
  3181. DXASSERT(decl->isImplicit(),
  3182. "otherwise object template decl is not set to implicit");
  3183. return AR_TOBJ_OBJECT;
  3184. }
  3185. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3186. if (typeRecordDecl->getDeclContext()->isFileContext())
  3187. return AR_TOBJ_OBJECT;
  3188. else
  3189. return AR_TOBJ_INNER_OBJ;
  3190. }
  3191. return AR_TOBJ_COMPOUND;
  3192. }
  3193. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  3194. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  3195. return AR_TOBJ_INVALID;
  3196. }
  3197. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  3198. QualType GetMatrixOrVectorElementType(QualType type)
  3199. {
  3200. type = GetStructuralForm(type);
  3201. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3202. DXASSERT_NOMSG(typeRecordDecl);
  3203. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3204. DXASSERT_NOMSG(templateSpecializationDecl);
  3205. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  3206. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  3207. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  3208. }
  3209. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  3210. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  3211. QualType GetStructuralForm(QualType type)
  3212. {
  3213. if (type.isNull()) {
  3214. return type;
  3215. }
  3216. const ReferenceType *RefType = nullptr;
  3217. const AttributedType *AttrType = nullptr;
  3218. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  3219. (AttrType = dyn_cast<AttributedType>(type)))
  3220. {
  3221. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  3222. }
  3223. return type->getCanonicalTypeUnqualified();
  3224. }
  3225. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  3226. ArBasicKind GetTypeElementKind(QualType type)
  3227. {
  3228. type = GetStructuralForm(type);
  3229. ArTypeObjectKind kind = GetTypeObjectKind(type);
  3230. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  3231. QualType elementType = GetMatrixOrVectorElementType(type);
  3232. return GetTypeElementKind(elementType);
  3233. }
  3234. if (kind == AR_TOBJ_STRING) {
  3235. return type->isArrayType() ? AR_OBJECT_STRING_LITERAL : AR_OBJECT_STRING;
  3236. }
  3237. if (type->isArrayType()) {
  3238. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  3239. return GetTypeElementKind(arrayType->getElementType());
  3240. }
  3241. if (kind == AR_TOBJ_INNER_OBJ) {
  3242. return AR_OBJECT_INNER;
  3243. } else if (kind == AR_TOBJ_OBJECT) {
  3244. // Classify the object as the element type.
  3245. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  3246. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3247. // NOTE: this will likely need to be updated for specialized records
  3248. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  3249. return g_ArBasicKindsAsTypes[index];
  3250. }
  3251. CanQualType canType = type->getCanonicalTypeUnqualified();
  3252. return BasicTypeForScalarType(canType);
  3253. }
  3254. ArBasicKind BasicTypeForScalarType(CanQualType type)
  3255. {
  3256. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3257. {
  3258. switch (BT->getKind())
  3259. {
  3260. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3261. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3262. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3263. case BuiltinType::Half: return AR_BASIC_FLOAT16;
  3264. case BuiltinType::HalfFloat: return AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  3265. case BuiltinType::Int: return AR_BASIC_INT32;
  3266. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3267. case BuiltinType::Short: return AR_BASIC_INT16;
  3268. case BuiltinType::UShort: return AR_BASIC_UINT16;
  3269. case BuiltinType::Long: return AR_BASIC_INT32;
  3270. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3271. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3272. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3273. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3274. case BuiltinType::Min16Float: return AR_BASIC_MIN16FLOAT;
  3275. case BuiltinType::Min16Int: return AR_BASIC_MIN16INT;
  3276. case BuiltinType::Min16UInt: return AR_BASIC_MIN16UINT;
  3277. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3278. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3279. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3280. default:
  3281. // Only builtin types that have basickind equivalents.
  3282. break;
  3283. }
  3284. }
  3285. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3286. if (ET->getDecl()->isScopedUsingClassTag())
  3287. return AR_BASIC_ENUM_CLASS;
  3288. return AR_BASIC_ENUM;
  3289. }
  3290. return AR_BASIC_UNKNOWN;
  3291. }
  3292. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3293. DXASSERT_NOMSG(table != nullptr);
  3294. // Function intrinsics are added on-demand, objects get template methods.
  3295. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3296. // Grab information already processed by AddObjectTypes.
  3297. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3298. const char *typeName = g_ArBasicTypeNames[kind];
  3299. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3300. DXASSERT(templateArgCount <= 2, "otherwise a new case has been added");
  3301. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3302. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3303. if (recordDecl == nullptr) {
  3304. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3305. continue;
  3306. }
  3307. // This is a variation of AddObjectMethods using the new table.
  3308. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3309. const HLSL_INTRINSIC *pPrior = nullptr;
  3310. UINT64 lookupCookie = 0;
  3311. CA2W wideTypeName(typeName);
  3312. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3313. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3314. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3315. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3316. // NOTE: this only works with the current implementation because
  3317. // intrinsics are alive as long as the table is alive.
  3318. pPrior = pIntrinsic;
  3319. }
  3320. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3321. }
  3322. }
  3323. }
  3324. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3325. DXASSERT_NOMSG(table != nullptr);
  3326. m_intrinsicTables.push_back(table);
  3327. // If already initialized, add methods immediately.
  3328. if (m_sema != nullptr) {
  3329. AddIntrinsicTableMethods(table);
  3330. }
  3331. }
  3332. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3333. {
  3334. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3335. switch (kind) {
  3336. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3337. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3338. case AR_BASIC_FLOAT16: return HLSLScalarType_half;
  3339. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3340. return HLSLScalarType_float;
  3341. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3342. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3343. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3344. case AR_BASIC_INT8: return HLSLScalarType_int;
  3345. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3346. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3347. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3348. case AR_BASIC_INT32: return HLSLScalarType_int;
  3349. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3350. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3351. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3352. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3353. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3354. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3355. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3356. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3357. case AR_BASIC_ENUM: return HLSLScalarType_int;
  3358. default:
  3359. return HLSLScalarType_unknown;
  3360. }
  3361. }
  3362. QualType GetBasicKindType(ArBasicKind kind)
  3363. {
  3364. DXASSERT_VALIDBASICKIND(kind);
  3365. switch (kind) {
  3366. case AR_OBJECT_NULL: return m_context->VoidTy;
  3367. case AR_BASIC_BOOL: return m_context->BoolTy;
  3368. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3369. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3370. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->HalfFloatTy;
  3371. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3372. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3373. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3374. case AR_BASIC_INT8: return m_context->IntTy;
  3375. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3376. case AR_BASIC_INT16: return m_context->ShortTy;
  3377. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3378. case AR_BASIC_INT32: return m_context->IntTy;
  3379. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3380. case AR_BASIC_INT64: return m_context->LongLongTy;
  3381. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3382. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3383. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3384. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3385. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3386. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3387. case AR_BASIC_ENUM: return m_context->IntTy;
  3388. case AR_BASIC_ENUM_CLASS: return m_context->IntTy;
  3389. case AR_OBJECT_STRING: return m_hlslStringType;
  3390. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3391. case AR_OBJECT_TEXTURE1D:
  3392. case AR_OBJECT_TEXTURE1D_ARRAY:
  3393. case AR_OBJECT_TEXTURE2D:
  3394. case AR_OBJECT_TEXTURE2D_ARRAY:
  3395. case AR_OBJECT_TEXTURE3D:
  3396. case AR_OBJECT_TEXTURECUBE:
  3397. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3398. case AR_OBJECT_TEXTURE2DMS:
  3399. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3400. case AR_OBJECT_SAMPLER:
  3401. case AR_OBJECT_SAMPLERCOMPARISON:
  3402. case AR_OBJECT_BUFFER:
  3403. case AR_OBJECT_POINTSTREAM:
  3404. case AR_OBJECT_LINESTREAM:
  3405. case AR_OBJECT_TRIANGLESTREAM:
  3406. case AR_OBJECT_INPUTPATCH:
  3407. case AR_OBJECT_OUTPUTPATCH:
  3408. case AR_OBJECT_RWTEXTURE1D:
  3409. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3410. case AR_OBJECT_RWTEXTURE2D:
  3411. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3412. case AR_OBJECT_RWTEXTURE3D:
  3413. case AR_OBJECT_RWBUFFER:
  3414. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3415. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3416. case AR_OBJECT_STRUCTURED_BUFFER:
  3417. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3418. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3419. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3420. case AR_OBJECT_WAVE:
  3421. case AR_OBJECT_ACCELARATION_STRUCT:
  3422. case AR_OBJECT_RAY_DESC:
  3423. case AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES:
  3424. {
  3425. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3426. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3427. size_t index = match - g_ArBasicKindsAsTypes;
  3428. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3429. }
  3430. case AR_OBJECT_SAMPLER1D:
  3431. case AR_OBJECT_SAMPLER2D:
  3432. case AR_OBJECT_SAMPLER3D:
  3433. case AR_OBJECT_SAMPLERCUBE:
  3434. // Turn dimension-typed samplers into sampler states.
  3435. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3436. case AR_OBJECT_STATEBLOCK:
  3437. case AR_OBJECT_RASTERIZER:
  3438. case AR_OBJECT_DEPTHSTENCIL:
  3439. case AR_OBJECT_BLEND:
  3440. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3441. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3442. default:
  3443. return QualType();
  3444. }
  3445. }
  3446. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3447. /// <param name="E">Expression to typecast.</param>
  3448. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3449. ExprResult PromoteToIntIfBool(ExprResult& E);
  3450. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3451. {
  3452. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3453. (void)(qwUsages);
  3454. return type;
  3455. }
  3456. QualType NewSimpleAggregateType(
  3457. _In_ ArTypeObjectKind ExplicitKind,
  3458. _In_ ArBasicKind componentType,
  3459. _In_ UINT64 qwQual,
  3460. _In_ UINT uRows,
  3461. _In_ UINT uCols)
  3462. {
  3463. DXASSERT_VALIDBASICKIND(componentType);
  3464. QualType pType; // The type to return.
  3465. if (componentType < AR_BASIC_COUNT) {
  3466. // If basic numeric, call LookupScalarTypeDef to ensure on-demand
  3467. // initialization
  3468. LookupScalarTypeDef(ScalarTypeForBasic(componentType));
  3469. }
  3470. QualType pEltType = GetBasicKindType(componentType);
  3471. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3472. // TODO: handle adding qualifications like const
  3473. pType = NewQualifiedType(
  3474. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3475. pEltType);
  3476. if (uRows > 1 ||
  3477. uCols > 1 ||
  3478. ExplicitKind == AR_TOBJ_VECTOR ||
  3479. ExplicitKind == AR_TOBJ_MATRIX)
  3480. {
  3481. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3482. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3483. if ((uRows == 1 &&
  3484. ExplicitKind != AR_TOBJ_MATRIX) ||
  3485. ExplicitKind == AR_TOBJ_VECTOR)
  3486. {
  3487. pType = LookupVectorType(scalarType, uCols);
  3488. }
  3489. else
  3490. {
  3491. pType = LookupMatrixType(scalarType, uRows, uCols);
  3492. }
  3493. // TODO: handle colmajor/rowmajor
  3494. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3495. //{
  3496. // VN(pType = NewQualifiedType(pSrcLoc,
  3497. // qwQual & (AR_QUAL_COLMAJOR |
  3498. // AR_QUAL_ROWMAJOR),
  3499. // pMatrix));
  3500. //}
  3501. //else
  3502. //{
  3503. // pType = pMatrix;
  3504. //}
  3505. }
  3506. return pType;
  3507. }
  3508. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3509. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3510. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3511. /// <param name="Args">Invocation arguments to match.</param>
  3512. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3513. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  3514. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3515. bool MatchArguments(
  3516. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3517. _In_ QualType objectElement,
  3518. _In_ ArrayRef<Expr *> Args,
  3519. _Out_writes_(g_MaxIntrinsicParamCount + 1) QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  3520. _Out_range_(0, g_MaxIntrinsicParamCount + 1) size_t* argCount);
  3521. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3522. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3523. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3524. bool IsValidateObjectElement(
  3525. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3526. _In_ QualType objectElement);
  3527. // Returns the iterator with the first entry that matches the requirement
  3528. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3529. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3530. size_t tableSize,
  3531. StringRef typeName,
  3532. StringRef nameIdentifier,
  3533. size_t argumentCount)
  3534. {
  3535. // This is implemented by a linear scan for now.
  3536. // We tested binary search on tables, and there was no performance gain on
  3537. // samples probably for the following reasons.
  3538. // 1. The tables are not big enough to make noticable difference
  3539. // 2. The user of this function assumes that it returns the first entry in
  3540. // the table that matches name and argument count. So even in the binary
  3541. // search, we have to scan backwards until the entry does not match the name
  3542. // or arg count. For linear search this is not a problem
  3543. for (unsigned int i = 0; i < tableSize; i++) {
  3544. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3545. // Do some quick checks to verify size and name.
  3546. if (pIntrinsic->uNumArgs != 1 + argumentCount) {
  3547. continue;
  3548. }
  3549. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3550. continue;
  3551. }
  3552. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3553. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3554. }
  3555. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3556. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3557. }
  3558. bool AddOverloadedCallCandidates(
  3559. UnresolvedLookupExpr *ULE,
  3560. ArrayRef<Expr *> Args,
  3561. OverloadCandidateSet &CandidateSet,
  3562. bool PartialOverloading) override
  3563. {
  3564. DXASSERT_NOMSG(ULE != nullptr);
  3565. const DeclarationNameInfo declName = ULE->getNameInfo();
  3566. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3567. if (idInfo == nullptr)
  3568. {
  3569. return false;
  3570. }
  3571. StringRef nameIdentifier = idInfo->getName();
  3572. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3573. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  3574. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3575. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3576. while (cursor != end)
  3577. {
  3578. // If this is the intrinsic we're interested in, build up a representation
  3579. // of the types we need.
  3580. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3581. LPCSTR tableName = cursor.GetTableName();
  3582. LPCSTR lowering = cursor.GetLoweringStrategy();
  3583. DXASSERT(
  3584. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3585. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3586. QualType functionArgTypes[g_MaxIntrinsicParamCount + 1];
  3587. size_t functionArgTypeCount = 0;
  3588. if (!MatchArguments(pIntrinsic, QualType(), Args, functionArgTypes, &functionArgTypeCount))
  3589. {
  3590. ++cursor;
  3591. continue;
  3592. }
  3593. // Get or create the overload we're interested in.
  3594. FunctionDecl* intrinsicFuncDecl = nullptr;
  3595. std::pair<UsedIntrinsicStore::iterator, bool> insertResult = m_usedIntrinsics.insert(UsedIntrinsic(
  3596. pIntrinsic, functionArgTypes, functionArgTypeCount));
  3597. bool insertedNewValue = insertResult.second;
  3598. if (insertedNewValue)
  3599. {
  3600. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3601. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, functionArgTypes, functionArgTypeCount);
  3602. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3603. }
  3604. else
  3605. {
  3606. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3607. }
  3608. OverloadCandidate& candidate = CandidateSet.addCandidate();
  3609. candidate.Function = intrinsicFuncDecl;
  3610. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3611. candidate.Viable = true;
  3612. return true;
  3613. }
  3614. return false;
  3615. }
  3616. bool Initialize(ASTContext& context)
  3617. {
  3618. m_context = &context;
  3619. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3620. /*Inline*/ false, SourceLocation(),
  3621. SourceLocation(), &context.Idents.get("hlsl"),
  3622. /*PrevDecl*/ nullptr);
  3623. m_hlslNSDecl->setImplicit();
  3624. AddBaseTypes();
  3625. AddHLSLScalarTypes();
  3626. AddHLSLStringType();
  3627. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3628. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  3629. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  3630. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  3631. // Initializing built in integers for ray tracing
  3632. AddRayFlags(*m_context);
  3633. AddHitKinds(*m_context);
  3634. AddStateObjectFlags(*m_context);
  3635. return true;
  3636. }
  3637. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  3638. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  3639. /// <summary>Checks whether the specified type is a scalar type.</summary>
  3640. bool IsScalarType(const QualType& type) {
  3641. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  3642. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3643. }
  3644. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3645. bool IsValidVectorSize(size_t length) {
  3646. return 1 <= length && length <= 4;
  3647. }
  3648. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3649. bool IsValidMatrixColOrRowSize(size_t length) {
  3650. return 1 <= length && length <= 4;
  3651. }
  3652. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3653. if (type.isNull()) {
  3654. return false;
  3655. }
  3656. if (type.hasQualifiers()) {
  3657. return false;
  3658. }
  3659. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3660. if (type->getTypeClass() == Type::TemplateTypeParm)
  3661. return true;
  3662. QualType qt = GetStructuralForm(type);
  3663. if (requireScalar) {
  3664. if (!IsScalarType(qt)) {
  3665. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3666. return false;
  3667. }
  3668. return true;
  3669. }
  3670. else {
  3671. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3672. if (qt->isArrayType()) {
  3673. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3674. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3675. }
  3676. else if (objectKind == AR_TOBJ_VECTOR) {
  3677. bool valid = true;
  3678. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3679. valid = false;
  3680. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3681. }
  3682. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3683. valid = false;
  3684. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3685. }
  3686. return valid;
  3687. }
  3688. else if (objectKind == AR_TOBJ_MATRIX) {
  3689. bool valid = true;
  3690. UINT rowCount, colCount;
  3691. GetRowsAndCols(type, rowCount, colCount);
  3692. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3693. valid = false;
  3694. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3695. }
  3696. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3697. valid = false;
  3698. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3699. }
  3700. return valid;
  3701. }
  3702. else if (qt->isStructureType()) {
  3703. const RecordType* recordType = qt->getAsStructureType();
  3704. objectKind = ClassifyRecordType(recordType);
  3705. switch (objectKind)
  3706. {
  3707. case AR_TOBJ_OBJECT:
  3708. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3709. return false;
  3710. case AR_TOBJ_COMPOUND:
  3711. {
  3712. const RecordDecl* recordDecl = recordType->getDecl();
  3713. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3714. RecordDecl::field_iterator end = recordDecl->field_end();
  3715. bool result = true;
  3716. while (begin != end) {
  3717. const FieldDecl* fieldDecl = *begin;
  3718. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3719. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3720. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3721. result = false;
  3722. }
  3723. begin++;
  3724. }
  3725. return result;
  3726. }
  3727. default:
  3728. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3729. return false;
  3730. }
  3731. }
  3732. else if(IsScalarType(qt)) {
  3733. return true;
  3734. }
  3735. else {
  3736. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3737. return false;
  3738. }
  3739. }
  3740. }
  3741. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3742. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3743. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3744. _Inout_opt_ StandardConversionSequence* sequence);
  3745. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3746. void GetConversionForm(
  3747. QualType type,
  3748. bool explicitConversion,
  3749. ArTypeInfo* pTypeInfo);
  3750. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3751. bool suppressWarnings, bool suppressErrors,
  3752. _Inout_opt_ StandardConversionSequence* sequence);
  3753. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3754. bool ValidateTypeRequirements(
  3755. SourceLocation loc,
  3756. ArBasicKind elementKind,
  3757. ArTypeObjectKind objectKind,
  3758. bool requiresIntegrals,
  3759. bool requiresNumerics);
  3760. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3761. /// <param name="OpLoc">Source location for operator.</param>
  3762. /// <param name="Opc">Kind of binary operator.</param>
  3763. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3764. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3765. /// <param name="ResultTy">Result type for operator expression.</param>
  3766. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3767. /// <param name="CompResultTy">Type of computation result.</param>
  3768. void CheckBinOpForHLSL(
  3769. SourceLocation OpLoc,
  3770. BinaryOperatorKind Opc,
  3771. ExprResult& LHS,
  3772. ExprResult& RHS,
  3773. QualType& ResultTy,
  3774. QualType& CompLHSTy,
  3775. QualType& CompResultTy);
  3776. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3777. /// <param name="OpLoc">Source location for operator.</param>
  3778. /// <param name="Opc">Kind of operator.</param>
  3779. /// <param name="InputExpr">Input expression to the operator.</param>
  3780. /// <param name="VK">Value kind for resulting expression.</param>
  3781. /// <param name="OK">Object kind for resulting expression.</param>
  3782. /// <returns>The result type for the expression.</returns>
  3783. QualType CheckUnaryOpForHLSL(
  3784. SourceLocation OpLoc,
  3785. UnaryOperatorKind Opc,
  3786. ExprResult& InputExpr,
  3787. ExprValueKind& VK,
  3788. ExprObjectKind& OK);
  3789. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3790. /// <param name="Cond">Vector condition expression.</param>
  3791. /// <param name="LHS">Left hand side.</param>
  3792. /// <param name="RHS">Right hand side.</param>
  3793. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3794. /// <returns>Result type of vector conditional expression.</returns>
  3795. clang::QualType CheckVectorConditional(
  3796. _In_ ExprResult &Cond,
  3797. _In_ ExprResult &LHS,
  3798. _In_ ExprResult &RHS,
  3799. _In_ SourceLocation QuestionLoc);
  3800. clang::QualType ApplyTypeSpecSignToParsedType(
  3801. _In_ clang::QualType &type,
  3802. _In_ TypeSpecifierSign TSS,
  3803. _In_ SourceLocation Loc
  3804. );
  3805. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3806. {
  3807. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3808. {
  3809. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3810. return true;
  3811. }
  3812. return false;
  3813. }
  3814. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3815. bool
  3816. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3817. SourceLocation /* TemplateLoc */,
  3818. TemplateArgumentListInfo &TemplateArgList) {
  3819. DXASSERT_NOMSG(Template != nullptr);
  3820. // Determine which object type the template refers to.
  3821. StringRef templateName = Template->getName();
  3822. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3823. if (templateName.equals(StringRef("is_same"))) {
  3824. return false;
  3825. }
  3826. bool isMatrix = Template->getCanonicalDecl() ==
  3827. m_matrixTemplateDecl->getCanonicalDecl();
  3828. bool isVector = Template->getCanonicalDecl() ==
  3829. m_vectorTemplateDecl->getCanonicalDecl();
  3830. bool requireScalar = isMatrix || isVector;
  3831. // Check constraints on the type. Right now we only check that template
  3832. // types are primitive types.
  3833. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3834. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3835. SourceLocation argSrcLoc = argLoc.getLocation();
  3836. const TemplateArgument &arg = argLoc.getArgument();
  3837. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3838. QualType argType = arg.getAsType();
  3839. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3840. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3841. return true;
  3842. }
  3843. }
  3844. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  3845. if (isMatrix || isVector) {
  3846. Expr *expr = arg.getAsExpr();
  3847. llvm::APSInt constantResult;
  3848. if (expr != nullptr &&
  3849. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  3850. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  3851. return true;
  3852. }
  3853. }
  3854. }
  3855. }
  3856. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  3857. if (isMatrix || isVector) {
  3858. llvm::APSInt Val = arg.getAsIntegral();
  3859. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  3860. return true;
  3861. }
  3862. }
  3863. }
  3864. }
  3865. return false;
  3866. }
  3867. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  3868. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  3869. /// <param name="functionDeclContext">Declaration context of function.</param>
  3870. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  3871. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  3872. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  3873. void FindIntrinsicTable(
  3874. _In_ DeclContext* functionDeclContext,
  3875. _Outptr_result_z_ const char** name,
  3876. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  3877. _Out_ size_t* intrinsicCount);
  3878. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  3879. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  3880. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  3881. /// <param name="Args">Array of expressions being used as arguments.</param>
  3882. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  3883. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  3884. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  3885. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  3886. FunctionTemplateDecl *FunctionTemplate,
  3887. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3888. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  3889. clang::OverloadingResult GetBestViableFunction(
  3890. clang::SourceLocation Loc,
  3891. clang::OverloadCandidateSet& set,
  3892. clang::OverloadCandidateSet::iterator& Best);
  3893. /// <summary>
  3894. /// Initializes the specified <paramref name="initSequence" /> describing how
  3895. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  3896. /// </summary>
  3897. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  3898. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  3899. /// <param name="Args">Arguments to the initialization.</param>
  3900. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  3901. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  3902. void InitializeInitSequenceForHLSL(
  3903. const InitializedEntity& Entity,
  3904. const InitializationKind& Kind,
  3905. MultiExprArg Args,
  3906. bool TopLevelOfInitList,
  3907. _Inout_ InitializationSequence* initSequence);
  3908. /// <summary>
  3909. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3910. /// </summary>
  3911. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3912. bool IsConversionToLessOrEqualElements(
  3913. const ExprResult& sourceExpr,
  3914. const QualType& targetType,
  3915. bool explicitConversion);
  3916. /// <summary>
  3917. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3918. /// </summary>
  3919. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3920. bool IsConversionToLessOrEqualElements(
  3921. const QualType& sourceType,
  3922. const QualType& targetType,
  3923. bool explicitConversion);
  3924. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  3925. /// <param name="BaseExpr">Base expression for member access.</param>
  3926. /// <param name="MemberName">Name of member to look up.</param>
  3927. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3928. /// <param name="OpLoc">Location of access operand.</param>
  3929. /// <param name="MemberLoc">Location of member.</param>
  3930. /// <param name="result">Result of lookup operation.</param>
  3931. /// <returns>true if the base type is a matrix and the lookup has been handled.</returns>
  3932. bool LookupMatrixMemberExprForHLSL(
  3933. Expr& BaseExpr,
  3934. DeclarationName MemberName,
  3935. bool IsArrow,
  3936. SourceLocation OpLoc,
  3937. SourceLocation MemberLoc,
  3938. ExprResult* result);
  3939. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  3940. /// <param name="BaseExpr">Base expression for member access.</param>
  3941. /// <param name="MemberName">Name of member to look up.</param>
  3942. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3943. /// <param name="OpLoc">Location of access operand.</param>
  3944. /// <param name="MemberLoc">Location of member.</param>
  3945. /// <param name="result">Result of lookup operation.</param>
  3946. /// <returns>true if the base type is a vector and the lookup has been handled.</returns>
  3947. bool LookupVectorMemberExprForHLSL(
  3948. Expr& BaseExpr,
  3949. DeclarationName MemberName,
  3950. bool IsArrow,
  3951. SourceLocation OpLoc,
  3952. SourceLocation MemberLoc,
  3953. ExprResult* result);
  3954. /// <summary>Performs a member lookup on the specified BaseExpr if it's an array.</summary>
  3955. /// <param name="BaseExpr">Base expression for member access.</param>
  3956. /// <param name="MemberName">Name of member to look up.</param>
  3957. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3958. /// <param name="OpLoc">Location of access operand.</param>
  3959. /// <param name="MemberLoc">Location of member.</param>
  3960. /// <param name="result">Result of lookup operation.</param>
  3961. /// <returns>true if the base type is an array and the lookup has been handled.</returns>
  3962. bool LookupArrayMemberExprForHLSL(
  3963. Expr& BaseExpr,
  3964. DeclarationName MemberName,
  3965. bool IsArrow,
  3966. SourceLocation OpLoc,
  3967. SourceLocation MemberLoc,
  3968. ExprResult* result);
  3969. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  3970. /// <param name="E">Expression to convert.</param>
  3971. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  3972. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  3973. clang::Expr *HLSLImpCastToScalar(
  3974. _In_ clang::Sema* self,
  3975. _In_ clang::Expr* From,
  3976. ArTypeObjectKind FromShape,
  3977. ArBasicKind EltKind);
  3978. clang::ExprResult PerformHLSLConversion(
  3979. _In_ clang::Expr* From,
  3980. _In_ clang::QualType targetType,
  3981. _In_ const clang::StandardConversionSequence &SCS,
  3982. _In_ clang::Sema::CheckedConversionKind CCK);
  3983. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  3984. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  3985. /// <summary>
  3986. /// Checks if a static cast can be performed, and performs it if possible.
  3987. /// </summary>
  3988. /// <param name="SrcExpr">Expression to cast.</param>
  3989. /// <param name="DestType">Type to cast SrcExpr to.</param>
  3990. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  3991. /// <param name="OpRange">Source range for the cast operation.</param>
  3992. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  3993. /// <param name="Kind">The kind of operation required for a conversion.</param>
  3994. /// <param name="BasePath">A simple array of base specifiers.</param>
  3995. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  3996. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  3997. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  3998. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  3999. QualType DestType,
  4000. Sema::CheckedConversionKind CCK,
  4001. const SourceRange &OpRange, unsigned &msg,
  4002. CastKind &Kind, CXXCastPath &BasePath,
  4003. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  4004. _Inout_opt_ StandardConversionSequence* standard);
  4005. /// <summary>
  4006. /// Checks if a subscript index argument can be initialized from the given expression.
  4007. /// </summary>
  4008. /// <param name="SrcExpr">Source expression used as argument.</param>
  4009. /// <param name="DestType">Parameter type to initialize.</param>
  4010. /// <remarks>
  4011. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  4012. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  4013. /// </remarks>
  4014. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  4015. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  4016. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  4017. // Everything is ready.
  4018. if (m_objectTypeLazyInitMask == 0)
  4019. return;
  4020. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  4021. int idx = FindObjectBasicKindIndex(recordDecl);
  4022. // Not object type.
  4023. if (idx == -1)
  4024. return;
  4025. uint64_t bit = ((uint64_t)1)<<idx;
  4026. // Already created.
  4027. if ((m_objectTypeLazyInitMask & bit) == 0)
  4028. return;
  4029. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  4030. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  4031. int startDepth = 0;
  4032. if (templateArgCount > 0) {
  4033. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  4034. "otherwise a new case has been added");
  4035. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  4036. AddObjectSubscripts(kind, typeDecl, recordDecl,
  4037. g_ArBasicKindsSubscripts[idx]);
  4038. startDepth = 1;
  4039. }
  4040. AddObjectMethods(kind, recordDecl, startDepth);
  4041. // Clear the object.
  4042. m_objectTypeLazyInitMask &= ~bit;
  4043. }
  4044. FunctionDecl* AddHLSLIntrinsicMethod(
  4045. LPCSTR tableName,
  4046. LPCSTR lowering,
  4047. _In_ const HLSL_INTRINSIC* intrinsic,
  4048. _In_ FunctionTemplateDecl *FunctionTemplate,
  4049. ArrayRef<Expr *> Args,
  4050. _In_count_(parameterTypeCount) QualType* parameterTypes,
  4051. size_t parameterTypeCount)
  4052. {
  4053. DXASSERT_NOMSG(intrinsic != nullptr);
  4054. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  4055. DXASSERT_NOMSG(parameterTypes != nullptr);
  4056. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  4057. // Create the template arguments.
  4058. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  4059. for (size_t i = 0; i < parameterTypeCount; i++) {
  4060. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  4061. }
  4062. // Look for an existing specialization.
  4063. void *InsertPos = nullptr;
  4064. FunctionDecl *SpecFunc =
  4065. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  4066. if (SpecFunc != nullptr) {
  4067. return SpecFunc;
  4068. }
  4069. // Change return type to rvalue reference type for aggregate types
  4070. QualType retTy = parameterTypes[0];
  4071. if (retTy->isAggregateType() && !IsHLSLVecMatType(retTy))
  4072. parameterTypes[0] = m_context->getRValueReferenceType(retTy);
  4073. // Create a new specialization.
  4074. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  4075. InitParamMods(intrinsic, paramMods);
  4076. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4077. // Change out/inout parameter type to rvalue reference type.
  4078. if (paramMods[i - 1].isAnyOut()) {
  4079. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  4080. }
  4081. }
  4082. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  4083. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  4084. // Remove this when update intrinsic table not affect other things.
  4085. // Change vector<float,1> into float for bias.
  4086. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  4087. DXASSERT(parameterTypeCount > biasOperandID,
  4088. "else operation was misrecognized");
  4089. if (const ExtVectorType *VecTy =
  4090. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  4091. *m_context, parameterTypes[biasOperandID])) {
  4092. if (VecTy->getNumElements() == 1)
  4093. parameterTypes[biasOperandID] = VecTy->getElementType();
  4094. }
  4095. }
  4096. DeclContext *owner = FunctionTemplate->getDeclContext();
  4097. TemplateArgumentList templateArgumentList(
  4098. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  4099. templateArgs.size());
  4100. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4101. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  4102. mlTemplateArgumentList);
  4103. FunctionProtoType::ExtProtoInfo EmptyEPI;
  4104. QualType functionType = m_context->getFunctionType(
  4105. parameterTypes[0],
  4106. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  4107. EmptyEPI, paramMods);
  4108. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4109. FunctionProtoTypeLoc Proto =
  4110. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4111. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  4112. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4113. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  4114. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  4115. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  4116. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  4117. Params.push_back(paramDecl);
  4118. }
  4119. QualType T = TInfo->getType();
  4120. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  4121. CXXMethodDecl* method = CXXMethodDecl::Create(
  4122. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4123. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4124. // Add intrinsic attr
  4125. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  4126. // Record this function template specialization.
  4127. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  4128. *m_context, templateArgs.data(), templateArgs.size());
  4129. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  4130. // Attach the parameters
  4131. for (unsigned P = 0; P < Params.size(); ++P) {
  4132. Params[P]->setOwningFunction(method);
  4133. Proto.setParam(P, Params[P]);
  4134. }
  4135. method->setParams(Params);
  4136. // Adjust access.
  4137. method->setAccess(AccessSpecifier::AS_public);
  4138. FunctionTemplate->setAccess(method->getAccess());
  4139. return method;
  4140. }
  4141. // Overload support.
  4142. UINT64 ScoreCast(QualType leftType, QualType rightType);
  4143. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  4144. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  4145. unsigned GetNumElements(QualType anyType);
  4146. unsigned GetNumBasicElements(QualType anyType);
  4147. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  4148. QualType GetNthElementType(QualType type, unsigned index);
  4149. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  4150. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4151. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4152. };
  4153. TYPE_CONVERSION_REMARKS HLSLExternalSource::RemarksUnused = TYPE_CONVERSION_REMARKS::TYPE_CONVERSION_NONE;
  4154. ImplicitConversionKind HLSLExternalSource::ImplicitConversionKindUnused = ImplicitConversionKind::ICK_Identity;
  4155. // Use this class to flatten a type into HLSL primitives and iterate through them.
  4156. class FlattenedTypeIterator
  4157. {
  4158. private:
  4159. enum FlattenedIterKind {
  4160. FK_Simple,
  4161. FK_Fields,
  4162. FK_Expressions,
  4163. FK_IncompleteArray,
  4164. FK_Bases,
  4165. };
  4166. // Use this struct to represent a specific point in the tracked tree.
  4167. struct FlattenedTypeTracker {
  4168. QualType Type; // Type at this position in the tree.
  4169. unsigned int Count; // Count of consecutive types
  4170. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  4171. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  4172. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  4173. RecordDecl::field_iterator EndField; // STL-style end of fields.
  4174. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  4175. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  4176. FlattenedIterKind IterKind; // Kind of tracker.
  4177. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  4178. FlattenedTypeTracker(QualType type)
  4179. : Type(type), Count(0), CurrentExpr(nullptr),
  4180. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  4181. FlattenedTypeTracker(QualType type, unsigned int count,
  4182. MultiExprArg::iterator expression)
  4183. : Type(type), Count(count), CurrentExpr(expression),
  4184. IterKind(FK_Simple), IsConsidered(false) {}
  4185. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  4186. RecordDecl::field_iterator end)
  4187. : Type(type), Count(0), CurrentField(current), EndField(end),
  4188. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  4189. FlattenedTypeTracker(MultiExprArg::iterator current,
  4190. MultiExprArg::iterator end)
  4191. : Count(0), CurrentExpr(current), EndExpr(end),
  4192. IterKind(FK_Expressions), IsConsidered(false) {}
  4193. FlattenedTypeTracker(QualType type,
  4194. CXXRecordDecl::base_class_iterator current,
  4195. CXXRecordDecl::base_class_iterator end)
  4196. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  4197. IterKind(FK_Bases), IsConsidered(false) {}
  4198. /// <summary>Gets the current expression if one is available.</summary>
  4199. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  4200. /// <summary>Replaces the current expression.</summary>
  4201. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  4202. };
  4203. HLSLExternalSource& m_source; // Source driving the iteration.
  4204. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  4205. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  4206. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  4207. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  4208. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  4209. QualType m_firstType; // Name of first type found, used for diagnostics.
  4210. SourceLocation m_loc; // Location used for diagnostics.
  4211. static const size_t MaxTypeDepth = 100;
  4212. void advanceLeafTracker();
  4213. /// <summary>Consumes leaves.</summary>
  4214. void consumeLeaf();
  4215. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  4216. bool considerLeaf();
  4217. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  4218. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  4219. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  4220. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  4221. public:
  4222. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  4223. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  4224. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  4225. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  4226. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  4227. QualType getCurrentElement() const;
  4228. /// <summary>Get the number of repeated current elements.</summary>
  4229. unsigned int getCurrentElementSize() const;
  4230. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  4231. bool hasCurrentElement() const;
  4232. /// <summary>Consumes count elements on this iterator.</summary>
  4233. void advanceCurrentElement(unsigned int count);
  4234. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  4235. unsigned int countRemaining();
  4236. /// <summary>Gets the current expression if one is available.</summary>
  4237. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  4238. /// <summary>Replaces the current expression.</summary>
  4239. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  4240. struct ComparisonResult
  4241. {
  4242. unsigned int LeftCount;
  4243. unsigned int RightCount;
  4244. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  4245. bool AreElementsEqual;
  4246. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  4247. bool CanConvertElements;
  4248. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  4249. bool IsConvertibleAndEqualLength() const {
  4250. return CanConvertElements && LeftCount == RightCount;
  4251. }
  4252. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  4253. bool IsConvertibleAndLeftLonger() const {
  4254. return CanConvertElements && LeftCount > RightCount;
  4255. }
  4256. bool IsRightLonger() const {
  4257. return RightCount > LeftCount;
  4258. }
  4259. bool IsEqualLength() const {
  4260. return LeftCount == RightCount;
  4261. }
  4262. };
  4263. static ComparisonResult CompareIterators(
  4264. HLSLExternalSource& source, SourceLocation loc,
  4265. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  4266. static ComparisonResult CompareTypes(
  4267. HLSLExternalSource& source,
  4268. SourceLocation leftLoc, SourceLocation rightLoc,
  4269. QualType left, QualType right);
  4270. // Compares the arguments to initialize the left type, modifying them if necessary.
  4271. static ComparisonResult CompareTypesForInit(
  4272. HLSLExternalSource& source, QualType left, MultiExprArg args,
  4273. SourceLocation leftLoc, SourceLocation rightLoc);
  4274. };
  4275. static
  4276. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  4277. {
  4278. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  4279. if (specialization) {
  4280. const TemplateArgumentList& list = specialization->getTemplateArgs();
  4281. if (list.size()) {
  4282. return list[0].getAsType();
  4283. }
  4284. }
  4285. return QualType();
  4286. }
  4287. void HLSLExternalSource::AddBaseTypes()
  4288. {
  4289. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4290. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4291. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4292. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4293. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4294. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->HalfFloatTy : m_context->HalfTy;
  4295. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4296. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4297. m_baseTypes[HLSLScalarType_float_min10] = m_context->Min10FloatTy;
  4298. m_baseTypes[HLSLScalarType_float_min16] = m_context->Min16FloatTy;
  4299. m_baseTypes[HLSLScalarType_int_min12] = m_context->Min12IntTy;
  4300. m_baseTypes[HLSLScalarType_int_min16] = m_context->Min16IntTy;
  4301. m_baseTypes[HLSLScalarType_uint_min16] = m_context->Min16UIntTy;
  4302. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4303. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4304. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4305. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4306. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4307. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4308. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4309. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4310. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4311. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4312. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4313. }
  4314. void HLSLExternalSource::AddHLSLScalarTypes()
  4315. {
  4316. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4317. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4318. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4319. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4320. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4321. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4322. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4323. }
  4324. void HLSLExternalSource::AddHLSLStringType() {
  4325. m_hlslStringType = m_context->HLSLStringTy;
  4326. }
  4327. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4328. _In_ FunctionTemplateDecl* functionTemplate,
  4329. QualType objectElement,
  4330. const FindStructBasicTypeResult& findResult)
  4331. {
  4332. DXASSERT_NOMSG(functionTemplate != nullptr);
  4333. DXASSERT_NOMSG(!objectElement.isNull());
  4334. DXASSERT_NOMSG(findResult.Found());
  4335. DXASSERT(
  4336. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4337. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4338. // Subscript is templated only on its return type.
  4339. // Create the template argument.
  4340. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4341. QualType resultType = objectElement;
  4342. if (isReadWrite)
  4343. resultType = m_context->getLValueReferenceType(resultType, false);
  4344. else {
  4345. // Add const to avoid write.
  4346. resultType = m_context->getConstType(resultType);
  4347. resultType = m_context->getLValueReferenceType(resultType);
  4348. }
  4349. TemplateArgument templateArgument(resultType);
  4350. unsigned subscriptCardinality =
  4351. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4352. QualType subscriptIndexType =
  4353. subscriptCardinality == 1
  4354. ? m_context->UnsignedIntTy
  4355. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4356. subscriptCardinality);
  4357. // Look for an existing specialization.
  4358. void* InsertPos = nullptr;
  4359. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4360. if (SpecFunc != nullptr) {
  4361. return SpecFunc;
  4362. }
  4363. // Create a new specialization.
  4364. DeclContext* owner = functionTemplate->getDeclContext();
  4365. TemplateArgumentList templateArgumentList(
  4366. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4367. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4368. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4369. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4370. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4371. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4372. QualType functionType = m_context->getFunctionType(
  4373. resultType, subscriptIndexType, templateEPI, None);
  4374. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4375. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4376. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4377. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4378. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4379. QualType T = TInfo->getType();
  4380. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4381. CXXMethodDecl* method = CXXMethodDecl::Create(
  4382. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4383. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4384. // Add subscript attribute
  4385. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4386. // Record this function template specialization.
  4387. method->setFunctionTemplateSpecialization(functionTemplate,
  4388. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4389. // Attach the parameters
  4390. indexerParam->setOwningFunction(method);
  4391. Proto.setParam(0, indexerParam);
  4392. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4393. // Adjust access.
  4394. method->setAccess(AccessSpecifier::AS_public);
  4395. functionTemplate->setAccess(method->getAccess());
  4396. return method;
  4397. }
  4398. /// <summary>
  4399. /// This routine combines Source into Target. If you have a symmetric operation
  4400. /// and want to treat either side equally you should call it twice, swapping the
  4401. /// parameter order.
  4402. /// </summary>
  4403. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4404. _Out_opt_ ArBasicKind *pCombined) {
  4405. if (Target == Source) {
  4406. AssignOpt(Target, pCombined);
  4407. return true;
  4408. }
  4409. if (Source == AR_OBJECT_NULL) {
  4410. // NULL is valid for any object type.
  4411. AssignOpt(Target, pCombined);
  4412. return true;
  4413. }
  4414. switch (Target) {
  4415. AR_BASIC_ROBJECT_CASES:
  4416. if (Source == AR_OBJECT_STATEBLOCK) {
  4417. AssignOpt(Target, pCombined);
  4418. return true;
  4419. }
  4420. break;
  4421. AR_BASIC_TEXTURE_CASES:
  4422. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4423. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4424. AssignOpt(Target, pCombined);
  4425. return true;
  4426. }
  4427. break;
  4428. case AR_OBJECT_SAMPLERCOMPARISON:
  4429. if (Source == AR_OBJECT_STATEBLOCK) {
  4430. AssignOpt(Target, pCombined);
  4431. return true;
  4432. }
  4433. break;
  4434. default:
  4435. // Not a combinable target.
  4436. break;
  4437. }
  4438. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4439. return false;
  4440. }
  4441. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4442. HLSLExternalSource *pHLSLExternalSource) {
  4443. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4444. llvm::APInt val = intLit->getValue();
  4445. unsigned width = val.getActiveBits();
  4446. bool isNeg = val.isNegative();
  4447. if (isNeg) {
  4448. // Signed.
  4449. if (width <= 32)
  4450. return ArBasicKind::AR_BASIC_INT32;
  4451. else
  4452. return ArBasicKind::AR_BASIC_INT64;
  4453. } else {
  4454. // Unsigned.
  4455. if (width <= 32)
  4456. return ArBasicKind::AR_BASIC_UINT32;
  4457. else
  4458. return ArBasicKind::AR_BASIC_UINT64;
  4459. }
  4460. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4461. llvm::APFloat val = floatLit->getValue();
  4462. unsigned width = val.getSizeInBits(val.getSemantics());
  4463. if (width <= 16)
  4464. return ArBasicKind::AR_BASIC_FLOAT16;
  4465. else if (width <= 32)
  4466. return ArBasicKind::AR_BASIC_FLOAT32;
  4467. else
  4468. return AR_BASIC_FLOAT64;
  4469. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4470. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4471. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4472. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4473. kind = ArBasicKind::AR_BASIC_INT32;
  4474. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4475. kind = ArBasicKind::AR_BASIC_INT64;
  4476. }
  4477. return kind;
  4478. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4479. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4480. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4481. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4482. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4483. CombineBasicTypes(kind, kind1, &kind);
  4484. return kind;
  4485. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4486. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4487. return kind;
  4488. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4489. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4490. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4491. CombineBasicTypes(kind, kind1, &kind);
  4492. return kind;
  4493. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4494. // Use target Type for cast.
  4495. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4496. return kind;
  4497. } else {
  4498. // Could only be function call.
  4499. CallExpr *CE = cast<CallExpr>(litExpr);
  4500. // TODO: calculate the function call result.
  4501. if (CE->getNumArgs() == 1)
  4502. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4503. else {
  4504. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4505. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4506. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4507. CombineBasicTypes(kind, kindI, &kind);
  4508. }
  4509. return kind;
  4510. }
  4511. }
  4512. }
  4513. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4514. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4515. if (kind == *pCT)
  4516. return true;
  4517. pCT++;
  4518. }
  4519. return false;
  4520. }
  4521. static ArBasicKind
  4522. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4523. unsigned uLegalComponentTypes,
  4524. HLSLExternalSource *pHLSLExternalSource) {
  4525. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4526. ArBasicKind defaultKind = *pCT;
  4527. // Use first none literal kind as defaultKind.
  4528. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4529. ArBasicKind kind = *pCT;
  4530. pCT++;
  4531. // Skip literal type.
  4532. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4533. continue;
  4534. defaultKind = kind;
  4535. break;
  4536. }
  4537. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4538. if (kind == AR_BASIC_LITERAL_INT) {
  4539. // Search for match first.
  4540. // For literal arg which don't affect return type, the search should always success.
  4541. // Unless use literal int on a float parameter.
  4542. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4543. return litKind;
  4544. // Return the default.
  4545. return defaultKind;
  4546. }
  4547. else {
  4548. // Search for float32 first.
  4549. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4550. return AR_BASIC_FLOAT32;
  4551. // Search for float64.
  4552. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4553. return AR_BASIC_FLOAT64;
  4554. // return default.
  4555. return defaultKind;
  4556. }
  4557. }
  4558. _Use_decl_annotations_ bool
  4559. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4560. QualType objectElement) {
  4561. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4562. switch (op) {
  4563. case IntrinsicOp::MOP_Sample:
  4564. case IntrinsicOp::MOP_SampleBias:
  4565. case IntrinsicOp::MOP_SampleCmp:
  4566. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4567. case IntrinsicOp::MOP_SampleGrad:
  4568. case IntrinsicOp::MOP_SampleLevel: {
  4569. ArBasicKind kind = GetTypeElementKind(objectElement);
  4570. UINT uBits = GET_BPROP_BITS(kind);
  4571. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4572. } break;
  4573. default:
  4574. return true;
  4575. }
  4576. }
  4577. _Use_decl_annotations_
  4578. bool HLSLExternalSource::MatchArguments(
  4579. const HLSL_INTRINSIC* pIntrinsic,
  4580. QualType objectElement,
  4581. ArrayRef<Expr *> Args,
  4582. QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  4583. size_t* argCount)
  4584. {
  4585. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4586. DXASSERT_NOMSG(argCount != nullptr);
  4587. static const UINT UnusedSize = 0xFF;
  4588. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4589. #define CAB(_) { if (!(_)) return false; }
  4590. *argCount = 0;
  4591. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4592. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4593. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4594. // Reset infos
  4595. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4596. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4597. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4598. const unsigned retArgIdx = 0;
  4599. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4600. // Populate the template for each argument.
  4601. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4602. ArrayRef<Expr*>::iterator end = Args.end();
  4603. unsigned int iArg = 1;
  4604. for (; iterArg != end; ++iterArg) {
  4605. Expr* pCallArg = *iterArg;
  4606. // No vararg support.
  4607. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  4608. return false;
  4609. }
  4610. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  4611. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  4612. DXASSERT(pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS, "no vararg support");
  4613. QualType pType = pCallArg->getType();
  4614. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  4615. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  4616. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_RAYDESC) {
  4617. if (TypeInfoShapeKind == AR_TOBJ_COMPOUND) {
  4618. if (CXXRecordDecl *pDecl = pType->getAsCXXRecordDecl()) {
  4619. int index = FindObjectBasicKindIndex(pDecl);
  4620. if (index != -1 && AR_OBJECT_RAY_DESC == g_ArBasicKindsAsTypes[index]) {
  4621. ++iArg;
  4622. continue;
  4623. }
  4624. }
  4625. }
  4626. m_sema->Diag(pCallArg->getExprLoc(),
  4627. diag::err_hlsl_ray_desc_required);
  4628. return false;
  4629. }
  4630. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4631. DXASSERT(objectElement.isNull(), "");
  4632. QualType Ty = pCallArg->getType();
  4633. // Must be user define type for LICOMPTYPE_USER_DEFINED_TYPE arg.
  4634. if (TypeInfoShapeKind != AR_TOBJ_COMPOUND) {
  4635. m_sema->Diag(pCallArg->getExprLoc(),
  4636. diag::err_hlsl_no_struct_user_defined_type);
  4637. return false;
  4638. }
  4639. objectElement = Ty;
  4640. ++iArg;
  4641. continue;
  4642. }
  4643. // If we are a type and templateID requires one, this isn't a match.
  4644. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4645. ++iArg;
  4646. continue;
  4647. }
  4648. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  4649. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  4650. bool affectRetType =
  4651. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  4652. // For literal arg which don't affect return type, find concrete type.
  4653. // For literal arg affect return type,
  4654. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  4655. // where all argumentss are literal.
  4656. // CombineBasicTypes will cover the rest cases.
  4657. if (!affectRetType) {
  4658. TypeInfoEltKind = ConcreteLiteralType(
  4659. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  4660. }
  4661. }
  4662. UINT TypeInfoCols = 1;
  4663. UINT TypeInfoRows = 1;
  4664. switch (TypeInfoShapeKind) {
  4665. case AR_TOBJ_MATRIX:
  4666. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  4667. break;
  4668. case AR_TOBJ_VECTOR:
  4669. TypeInfoCols = GetHLSLVecSize(pType);
  4670. break;
  4671. case AR_TOBJ_BASIC:
  4672. case AR_TOBJ_OBJECT:
  4673. break;
  4674. default:
  4675. return false; // no struct, arrays or void
  4676. }
  4677. DXASSERT(
  4678. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  4679. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  4680. // Compare template
  4681. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  4682. ((AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  4683. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind))) {
  4684. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  4685. }
  4686. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  4687. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  4688. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  4689. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  4690. return false;
  4691. }
  4692. }
  4693. else {
  4694. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  4695. return false;
  4696. }
  4697. }
  4698. DXASSERT(
  4699. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4700. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4701. // Merge ComponentTypes
  4702. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4703. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4704. }
  4705. else {
  4706. if (!CombineBasicTypes(
  4707. ComponentType[pIntrinsicArg->uComponentTypeId],
  4708. TypeInfoEltKind,
  4709. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4710. return false;
  4711. }
  4712. }
  4713. // Rows
  4714. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4715. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4716. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4717. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4718. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4719. uSpecialSize[uSpecialId] = TypeInfoRows;
  4720. }
  4721. }
  4722. else {
  4723. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4724. return false;
  4725. }
  4726. }
  4727. }
  4728. // Columns
  4729. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4730. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4731. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4732. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4733. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4734. uSpecialSize[uSpecialId] = TypeInfoCols;
  4735. }
  4736. }
  4737. else {
  4738. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4739. return false;
  4740. }
  4741. }
  4742. }
  4743. // Usage
  4744. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4745. if (pCallArg->getType().isConstQualified()) {
  4746. // Can't use a const type in an out or inout parameter.
  4747. return false;
  4748. }
  4749. }
  4750. iArg++;
  4751. }
  4752. DXASSERT(iterArg == end, "otherwise the argument list wasn't fully processed");
  4753. // Default template and component type for return value
  4754. if (pIntrinsic->pArgs[0].qwUsage && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE) {
  4755. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4756. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4757. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4758. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4759. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4760. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4761. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4762. // half return type should map to float for min precision
  4763. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  4764. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  4765. getSema()->getLangOpts().UseMinPrecision) {
  4766. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4767. ArBasicKind::AR_BASIC_FLOAT32;
  4768. }
  4769. else {
  4770. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4771. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4772. }
  4773. }
  4774. }
  4775. }
  4776. }
  4777. // Make sure all template, component type, and texture type selections are valid.
  4778. for (size_t i = 0; i < Args.size() + 1; i++) {
  4779. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4780. // Check template.
  4781. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4782. continue; // Already verified that this is available.
  4783. }
  4784. if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4785. continue;
  4786. }
  4787. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4788. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4789. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4790. Template[i] = *pTT;
  4791. }
  4792. else {
  4793. while (AR_TOBJ_UNKNOWN != *pTT) {
  4794. if (Template[i] == *pTT)
  4795. break;
  4796. pTT++;
  4797. }
  4798. }
  4799. if (AR_TOBJ_UNKNOWN == *pTT)
  4800. return false;
  4801. }
  4802. else if (pTT) {
  4803. Template[i] = *pTT;
  4804. }
  4805. // Check component type.
  4806. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4807. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4808. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4809. if (ComponentType[i] == *pCT)
  4810. break;
  4811. pCT++;
  4812. }
  4813. // has to be a strict match
  4814. if (*pCT == AR_BASIC_NOCAST)
  4815. return false;
  4816. // If it is an object, see if it can be cast to the first thing in the
  4817. // list, otherwise move on to next intrinsic.
  4818. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4819. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4820. return false;
  4821. }
  4822. }
  4823. if (AR_BASIC_UNKNOWN == *pCT) {
  4824. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4825. }
  4826. }
  4827. else if (pCT) {
  4828. ComponentType[i] = *pCT;
  4829. }
  4830. }
  4831. // Default to a void return type.
  4832. argTypes[0] = m_context->VoidTy;
  4833. // Default specials sizes.
  4834. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  4835. if (UnusedSize == uSpecialSize[i]) {
  4836. uSpecialSize[i] = 1;
  4837. }
  4838. }
  4839. // Populate argTypes.
  4840. for (size_t i = 0; i <= Args.size(); i++) {
  4841. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4842. if (!pArgument->qwUsage)
  4843. continue;
  4844. QualType pNewType;
  4845. unsigned int quals = 0; // qualifications for this argument
  4846. // If we have no type, set it to our input type (templatized)
  4847. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4848. // Use the templated input type, but resize it if the
  4849. // intrinsic's rows/cols isn't 0
  4850. if (pArgument->uRows && pArgument->uCols) {
  4851. UINT uRows, uCols = 0;
  4852. // if type is overriden, use new type size, for
  4853. // now it only supports scalars
  4854. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4855. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4856. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4857. uRows = uSpecialSize[uSpecialId];
  4858. }
  4859. else if (pArgument->uRows > 0) {
  4860. uRows = pArgument->uRows;
  4861. }
  4862. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4863. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4864. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4865. uCols = uSpecialSize[uSpecialId];
  4866. }
  4867. else if (pArgument->uCols > 0) {
  4868. uCols = pArgument->uCols;
  4869. }
  4870. // 1x1 numeric outputs are always scalar.. since these
  4871. // are most flexible
  4872. if ((1 == uCols) && (1 == uRows)) {
  4873. pNewType = objectElement;
  4874. if (pNewType.isNull()) {
  4875. return false;
  4876. }
  4877. }
  4878. else {
  4879. // non-scalars unsupported right now since nothing
  4880. // uses it, would have to create either a type
  4881. // list for sub-structures or just resize the
  4882. // given type
  4883. // VH(E_NOTIMPL);
  4884. return false;
  4885. }
  4886. }
  4887. else {
  4888. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  4889. if (objectElement.isNull()) {
  4890. return false;
  4891. }
  4892. pNewType = objectElement;
  4893. }
  4894. } else if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4895. if (objectElement.isNull()) {
  4896. return false;
  4897. }
  4898. pNewType = objectElement;
  4899. } else {
  4900. ArBasicKind pEltType;
  4901. // ComponentType, if the Id is special then it gets the
  4902. // component type from the first component of the type, if
  4903. // we need more (for the second component, e.g.), then we
  4904. // can use more specials, etc.
  4905. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4906. if (objectElement.isNull()) {
  4907. return false;
  4908. }
  4909. pEltType = GetTypeElementKind(objectElement);
  4910. if (!IsValidBasicKind(pEltType)) {
  4911. // This can happen with Texture2D<Struct> or other invalid declarations
  4912. return false;
  4913. }
  4914. }
  4915. else {
  4916. pEltType = ComponentType[pArgument->uComponentTypeId];
  4917. DXASSERT_VALIDBASICKIND(pEltType);
  4918. }
  4919. UINT uRows, uCols;
  4920. // Rows
  4921. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4922. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4923. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4924. uRows = uSpecialSize[uSpecialId];
  4925. }
  4926. else {
  4927. uRows = pArgument->uRows;
  4928. }
  4929. // Cols
  4930. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4931. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4932. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4933. uCols = uSpecialSize[uSpecialId];
  4934. }
  4935. else {
  4936. uCols = pArgument->uCols;
  4937. }
  4938. // Verify that the final results are in bounds.
  4939. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  4940. // Const
  4941. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  4942. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  4943. qwQual |= AR_QUAL_CONST;
  4944. DXASSERT_VALIDBASICKIND(pEltType);
  4945. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  4946. }
  4947. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  4948. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  4949. // TODO: support out modifier
  4950. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  4951. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  4952. //}
  4953. }
  4954. *argCount = iArg;
  4955. DXASSERT(
  4956. *argCount == pIntrinsic->uNumArgs,
  4957. "In the absence of varargs, a successful match would indicate we have as many arguments and types as the intrinsic template");
  4958. return true;
  4959. #undef CAB
  4960. }
  4961. _Use_decl_annotations_
  4962. HLSLExternalSource::FindStructBasicTypeResult
  4963. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  4964. {
  4965. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4966. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  4967. // may be a simple class, such as RWByteAddressBuffer.
  4968. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  4969. // We save the caller from filtering out other types of context (like the translation unit itself).
  4970. if (recordDecl != nullptr)
  4971. {
  4972. int index = FindObjectBasicKindIndex(recordDecl);
  4973. if (index != -1) {
  4974. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  4975. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  4976. }
  4977. }
  4978. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  4979. }
  4980. _Use_decl_annotations_
  4981. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  4982. {
  4983. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4984. DXASSERT_NOMSG(name != nullptr);
  4985. DXASSERT_NOMSG(intrinsics != nullptr);
  4986. DXASSERT_NOMSG(intrinsicCount != nullptr);
  4987. *intrinsics = nullptr;
  4988. *intrinsicCount = 0;
  4989. *name = nullptr;
  4990. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  4991. if (lookup.Found()) {
  4992. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  4993. *name = g_ArBasicTypeNames[lookup.Kind];
  4994. }
  4995. }
  4996. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  4997. {
  4998. return
  4999. // Arithmetic operators.
  5000. Opc == BinaryOperatorKind::BO_Add ||
  5001. Opc == BinaryOperatorKind::BO_AddAssign ||
  5002. Opc == BinaryOperatorKind::BO_Sub ||
  5003. Opc == BinaryOperatorKind::BO_SubAssign ||
  5004. Opc == BinaryOperatorKind::BO_Rem ||
  5005. Opc == BinaryOperatorKind::BO_RemAssign ||
  5006. Opc == BinaryOperatorKind::BO_Div ||
  5007. Opc == BinaryOperatorKind::BO_DivAssign ||
  5008. Opc == BinaryOperatorKind::BO_Mul ||
  5009. Opc == BinaryOperatorKind::BO_MulAssign;
  5010. }
  5011. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  5012. {
  5013. return
  5014. // Arithmetic-and-assignment operators.
  5015. Opc == BinaryOperatorKind::BO_AddAssign ||
  5016. Opc == BinaryOperatorKind::BO_SubAssign ||
  5017. Opc == BinaryOperatorKind::BO_RemAssign ||
  5018. Opc == BinaryOperatorKind::BO_DivAssign ||
  5019. Opc == BinaryOperatorKind::BO_MulAssign ||
  5020. // Bitwise-and-assignment operators.
  5021. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5022. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5023. Opc == BinaryOperatorKind::BO_AndAssign ||
  5024. Opc == BinaryOperatorKind::BO_OrAssign ||
  5025. Opc == BinaryOperatorKind::BO_XorAssign;
  5026. }
  5027. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  5028. {
  5029. return
  5030. Opc == BinaryOperatorKind::BO_AndAssign ||
  5031. Opc == BinaryOperatorKind::BO_OrAssign ||
  5032. Opc == BinaryOperatorKind::BO_XorAssign;
  5033. }
  5034. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  5035. {
  5036. return
  5037. Opc == BinaryOperatorKind::BO_Shl ||
  5038. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5039. Opc == BinaryOperatorKind::BO_Shr ||
  5040. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5041. Opc == BinaryOperatorKind::BO_And ||
  5042. Opc == BinaryOperatorKind::BO_AndAssign ||
  5043. Opc == BinaryOperatorKind::BO_Or ||
  5044. Opc == BinaryOperatorKind::BO_OrAssign ||
  5045. Opc == BinaryOperatorKind::BO_Xor ||
  5046. Opc == BinaryOperatorKind::BO_XorAssign;
  5047. }
  5048. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  5049. {
  5050. return
  5051. Opc == BinaryOperatorKind::BO_Shl ||
  5052. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5053. Opc == BinaryOperatorKind::BO_Shr ||
  5054. Opc == BinaryOperatorKind::BO_ShrAssign;
  5055. }
  5056. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  5057. {
  5058. return
  5059. Opc == BinaryOperatorKind::BO_EQ ||
  5060. Opc == BinaryOperatorKind::BO_NE;
  5061. }
  5062. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  5063. {
  5064. return
  5065. Opc == BinaryOperatorKind::BO_LT ||
  5066. Opc == BinaryOperatorKind::BO_GT ||
  5067. Opc == BinaryOperatorKind::BO_LE ||
  5068. Opc == BinaryOperatorKind::BO_GE;
  5069. }
  5070. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  5071. {
  5072. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  5073. }
  5074. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  5075. {
  5076. return
  5077. Opc == BinaryOperatorKind::BO_LAnd ||
  5078. Opc == BinaryOperatorKind::BO_LOr;
  5079. }
  5080. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  5081. {
  5082. return
  5083. BinaryOperatorKindIsArithmetic(Opc) ||
  5084. BinaryOperatorKindIsOrderComparison(Opc) ||
  5085. BinaryOperatorKindIsLogical(Opc);
  5086. }
  5087. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  5088. {
  5089. return BinaryOperatorKindIsBitwise(Opc);
  5090. }
  5091. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  5092. {
  5093. return
  5094. BinaryOperatorKindIsBitwise(Opc) ||
  5095. BinaryOperatorKindIsArithmetic(Opc);
  5096. }
  5097. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  5098. {
  5099. return Opc == UnaryOperatorKind::UO_Not;
  5100. }
  5101. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  5102. {
  5103. return
  5104. Opc == UnaryOperatorKind::UO_LNot ||
  5105. Opc == UnaryOperatorKind::UO_Plus ||
  5106. Opc == UnaryOperatorKind::UO_Minus ||
  5107. // The omission in fxc caused objects and structs to accept this.
  5108. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5109. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5110. }
  5111. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  5112. {
  5113. return
  5114. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5115. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5116. }
  5117. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  5118. {
  5119. return
  5120. Opc == UnaryOperatorKind::UO_Not ||
  5121. Opc == UnaryOperatorKind::UO_Plus ||
  5122. Opc == UnaryOperatorKind::UO_Minus;
  5123. }
  5124. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  5125. {
  5126. return
  5127. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5128. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5129. }
  5130. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  5131. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  5132. }
  5133. /// <summary>
  5134. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  5135. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  5136. /// </summary>
  5137. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  5138. {
  5139. return
  5140. value == AR_TOBJ_BASIC ||
  5141. value == AR_TOBJ_MATRIX ||
  5142. value == AR_TOBJ_VECTOR;
  5143. }
  5144. static bool IsBasicKindIntegral(ArBasicKind value)
  5145. {
  5146. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  5147. }
  5148. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  5149. {
  5150. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  5151. }
  5152. static bool IsBasicKindNumeric(ArBasicKind value)
  5153. {
  5154. return GetBasicKindProps(value) & BPROP_NUMERIC;
  5155. }
  5156. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  5157. {
  5158. // An invalid expression is pass-through at this point.
  5159. if (E.isInvalid())
  5160. {
  5161. return E;
  5162. }
  5163. QualType qt = E.get()->getType();
  5164. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  5165. if (elementKind != AR_BASIC_BOOL)
  5166. {
  5167. return E;
  5168. }
  5169. // Construct a scalar/vector/matrix type with the same shape as E.
  5170. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  5171. QualType targetType;
  5172. UINT colCount, rowCount;
  5173. GetRowsAndColsForAny(qt, rowCount, colCount);
  5174. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  5175. if (E.get()->isLValue()) {
  5176. E = m_sema->DefaultLvalueConversion(E.get()).get();
  5177. }
  5178. switch (objectKind)
  5179. {
  5180. case AR_TOBJ_SCALAR:
  5181. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5182. case AR_TOBJ_ARRAY:
  5183. case AR_TOBJ_VECTOR:
  5184. case AR_TOBJ_MATRIX:
  5185. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5186. default:
  5187. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  5188. }
  5189. return E;
  5190. }
  5191. _Use_decl_annotations_
  5192. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  5193. {
  5194. DXASSERT_NOMSG(pTypeInfo != nullptr);
  5195. DXASSERT_NOMSG(!type.isNull());
  5196. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  5197. // TODO: Get* functions used here add up to a bunch of redundant code.
  5198. // Try to inline that here, making it cheaper to use this function
  5199. // when retrieving multiple properties.
  5200. pTypeInfo->ObjKind = GetTypeElementKind(type);
  5201. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  5202. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  5203. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  5204. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  5205. }
  5206. // Highest possible score (i.e., worst possible score).
  5207. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  5208. // Leave the first two score bits to handle higher-level
  5209. // variations like target type.
  5210. #define SCORE_MIN_SHIFT 2
  5211. // Space out scores to allow up to 128 parameters to
  5212. // vary between score sets spill into each other.
  5213. #define SCORE_PARAM_SHIFT 7
  5214. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  5215. if (anyType.isNull()) {
  5216. return 0;
  5217. }
  5218. anyType = GetStructuralForm(anyType);
  5219. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5220. switch (kind) {
  5221. case AR_TOBJ_BASIC:
  5222. case AR_TOBJ_OBJECT:
  5223. case AR_TOBJ_STRING:
  5224. return 1;
  5225. case AR_TOBJ_COMPOUND: {
  5226. // TODO: consider caching this value for perf
  5227. unsigned total = 0;
  5228. const RecordType *recordType = anyType->getAs<RecordType>();
  5229. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5230. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5231. while (fi != fend) {
  5232. total += GetNumElements(fi->getType());
  5233. ++fi;
  5234. }
  5235. return total;
  5236. }
  5237. case AR_TOBJ_ARRAY:
  5238. case AR_TOBJ_MATRIX:
  5239. case AR_TOBJ_VECTOR:
  5240. return GetElementCount(anyType);
  5241. default:
  5242. DXASSERT(kind == AR_TOBJ_VOID,
  5243. "otherwise the type cannot be classified or is not supported");
  5244. return 0;
  5245. }
  5246. }
  5247. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  5248. if (anyType.isNull()) {
  5249. return 0;
  5250. }
  5251. anyType = GetStructuralForm(anyType);
  5252. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5253. switch (kind) {
  5254. case AR_TOBJ_BASIC:
  5255. case AR_TOBJ_OBJECT:
  5256. case AR_TOBJ_STRING:
  5257. return 1;
  5258. case AR_TOBJ_COMPOUND: {
  5259. // TODO: consider caching this value for perf
  5260. unsigned total = 0;
  5261. const RecordType *recordType = anyType->getAs<RecordType>();
  5262. RecordDecl * RD = recordType->getDecl();
  5263. // Take care base.
  5264. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5265. if (CXXRD->getNumBases()) {
  5266. for (const auto &I : CXXRD->bases()) {
  5267. const CXXRecordDecl *BaseDecl =
  5268. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5269. if (BaseDecl->field_empty())
  5270. continue;
  5271. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5272. total += GetNumBasicElements(parentTy);
  5273. }
  5274. }
  5275. }
  5276. RecordDecl::field_iterator fi = RD->field_begin();
  5277. RecordDecl::field_iterator fend = RD->field_end();
  5278. while (fi != fend) {
  5279. total += GetNumBasicElements(fi->getType());
  5280. ++fi;
  5281. }
  5282. return total;
  5283. }
  5284. case AR_TOBJ_ARRAY: {
  5285. unsigned arraySize = GetElementCount(anyType);
  5286. unsigned eltSize = GetNumBasicElements(
  5287. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  5288. return arraySize * eltSize;
  5289. }
  5290. case AR_TOBJ_MATRIX:
  5291. case AR_TOBJ_VECTOR:
  5292. return GetElementCount(anyType);
  5293. default:
  5294. DXASSERT(kind == AR_TOBJ_VOID,
  5295. "otherwise the type cannot be classified or is not supported");
  5296. return 0;
  5297. }
  5298. }
  5299. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  5300. unsigned leftSize,
  5301. QualType rightType,
  5302. unsigned rightSize) {
  5303. // We can convert from a larger type to a smaller
  5304. // but not a smaller type to a larger so default
  5305. // to just comparing the destination size.
  5306. unsigned uElts = leftSize;
  5307. leftType = GetStructuralForm(leftType);
  5308. rightType = GetStructuralForm(rightType);
  5309. if (leftType->isArrayType() && rightType->isArrayType()) {
  5310. //
  5311. // If we're comparing arrays we don't
  5312. // need to compare every element of
  5313. // the arrays since all elements
  5314. // will have the same type.
  5315. // We only need to compare enough
  5316. // elements that we've tried every
  5317. // possible mix of dst and src elements.
  5318. //
  5319. // TODO: handle multidimensional arrays and arrays of arrays
  5320. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5321. unsigned uDstEltSize = GetNumElements(pDstElt);
  5322. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5323. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5324. if (uDstEltSize == uSrcEltSize) {
  5325. uElts = uDstEltSize;
  5326. } else if (uDstEltSize > uSrcEltSize) {
  5327. // If one size is not an even multiple of the other we need to let the
  5328. // full compare run in order to try all alignments.
  5329. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5330. uElts = uDstEltSize;
  5331. }
  5332. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5333. uElts = uSrcEltSize;
  5334. }
  5335. }
  5336. return uElts;
  5337. }
  5338. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5339. if (type.isNull()) {
  5340. return type;
  5341. }
  5342. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5343. switch (kind) {
  5344. case AR_TOBJ_BASIC:
  5345. case AR_TOBJ_OBJECT:
  5346. case AR_TOBJ_STRING:
  5347. return (index == 0) ? type : QualType();
  5348. case AR_TOBJ_COMPOUND: {
  5349. // TODO: consider caching this value for perf
  5350. const RecordType *recordType = type->getAsStructureType();
  5351. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5352. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5353. while (fi != fend) {
  5354. if (!fi->getType().isNull()) {
  5355. unsigned subElements = GetNumElements(fi->getType());
  5356. if (index < subElements) {
  5357. return GetNthElementType(fi->getType(), index);
  5358. } else {
  5359. index -= subElements;
  5360. }
  5361. }
  5362. ++fi;
  5363. }
  5364. return QualType();
  5365. }
  5366. case AR_TOBJ_ARRAY: {
  5367. unsigned arraySize;
  5368. QualType elementType;
  5369. unsigned elementCount;
  5370. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5371. elementCount = GetElementCount(elementType);
  5372. if (index < elementCount) {
  5373. return GetNthElementType(elementType, index);
  5374. }
  5375. arraySize = GetArraySize(type);
  5376. if (index >= arraySize * elementCount) {
  5377. return QualType();
  5378. }
  5379. return GetNthElementType(elementType, index % elementCount);
  5380. }
  5381. case AR_TOBJ_MATRIX:
  5382. case AR_TOBJ_VECTOR:
  5383. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5384. : QualType();
  5385. default:
  5386. DXASSERT(kind == AR_TOBJ_VOID,
  5387. "otherwise the type cannot be classified or is not supported");
  5388. return QualType();
  5389. }
  5390. }
  5391. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5392. // Eliminate exact matches first, then check for promotions.
  5393. if (leftKind == rightKind) {
  5394. return false;
  5395. }
  5396. switch (rightKind) {
  5397. case AR_BASIC_FLOAT16:
  5398. switch (leftKind) {
  5399. case AR_BASIC_FLOAT32:
  5400. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5401. case AR_BASIC_FLOAT64:
  5402. return true;
  5403. default:
  5404. return false; // No other type is a promotion.
  5405. }
  5406. break;
  5407. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5408. switch (leftKind) {
  5409. case AR_BASIC_FLOAT32:
  5410. case AR_BASIC_FLOAT64:
  5411. return true;
  5412. default:
  5413. return false; // No other type is a promotion.
  5414. }
  5415. break;
  5416. case AR_BASIC_FLOAT32:
  5417. switch (leftKind) {
  5418. case AR_BASIC_FLOAT64:
  5419. return true;
  5420. default:
  5421. return false; // No other type is a promotion.
  5422. }
  5423. break;
  5424. case AR_BASIC_MIN10FLOAT:
  5425. switch (leftKind) {
  5426. case AR_BASIC_MIN16FLOAT:
  5427. case AR_BASIC_FLOAT16:
  5428. case AR_BASIC_FLOAT32:
  5429. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5430. case AR_BASIC_FLOAT64:
  5431. return true;
  5432. default:
  5433. return false; // No other type is a promotion.
  5434. }
  5435. break;
  5436. case AR_BASIC_MIN16FLOAT:
  5437. switch (leftKind) {
  5438. case AR_BASIC_FLOAT16:
  5439. case AR_BASIC_FLOAT32:
  5440. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5441. case AR_BASIC_FLOAT64:
  5442. return true;
  5443. default:
  5444. return false; // No other type is a promotion.
  5445. }
  5446. break;
  5447. case AR_BASIC_INT8:
  5448. case AR_BASIC_UINT8:
  5449. // For backwards compat we consider signed/unsigned the same.
  5450. switch (leftKind) {
  5451. case AR_BASIC_INT16:
  5452. case AR_BASIC_INT32:
  5453. case AR_BASIC_INT64:
  5454. case AR_BASIC_UINT16:
  5455. case AR_BASIC_UINT32:
  5456. case AR_BASIC_UINT64:
  5457. return true;
  5458. default:
  5459. return false; // No other type is a promotion.
  5460. }
  5461. break;
  5462. case AR_BASIC_INT16:
  5463. case AR_BASIC_UINT16:
  5464. // For backwards compat we consider signed/unsigned the same.
  5465. switch (leftKind) {
  5466. case AR_BASIC_INT32:
  5467. case AR_BASIC_INT64:
  5468. case AR_BASIC_UINT32:
  5469. case AR_BASIC_UINT64:
  5470. return true;
  5471. default:
  5472. return false; // No other type is a promotion.
  5473. }
  5474. break;
  5475. case AR_BASIC_INT32:
  5476. case AR_BASIC_UINT32:
  5477. // For backwards compat we consider signed/unsigned the same.
  5478. switch (leftKind) {
  5479. case AR_BASIC_INT64:
  5480. case AR_BASIC_UINT64:
  5481. return true;
  5482. default:
  5483. return false; // No other type is a promotion.
  5484. }
  5485. break;
  5486. case AR_BASIC_MIN12INT:
  5487. switch (leftKind) {
  5488. case AR_BASIC_MIN16INT:
  5489. case AR_BASIC_INT32:
  5490. case AR_BASIC_INT64:
  5491. return true;
  5492. default:
  5493. return false; // No other type is a promotion.
  5494. }
  5495. break;
  5496. case AR_BASIC_MIN16INT:
  5497. switch (leftKind) {
  5498. case AR_BASIC_INT32:
  5499. case AR_BASIC_INT64:
  5500. return true;
  5501. default:
  5502. return false; // No other type is a promotion.
  5503. }
  5504. break;
  5505. case AR_BASIC_MIN16UINT:
  5506. switch (leftKind) {
  5507. case AR_BASIC_UINT32:
  5508. case AR_BASIC_UINT64:
  5509. return true;
  5510. default:
  5511. return false; // No other type is a promotion.
  5512. }
  5513. break;
  5514. }
  5515. return false;
  5516. }
  5517. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5518. // Eliminate exact matches first, then check for casts.
  5519. if (leftKind == rightKind) {
  5520. return false;
  5521. }
  5522. //
  5523. // All minimum-bits types are only considered matches of themselves
  5524. // and thus are not in this table.
  5525. //
  5526. switch (leftKind) {
  5527. case AR_BASIC_LITERAL_INT:
  5528. switch (rightKind) {
  5529. case AR_BASIC_INT8:
  5530. case AR_BASIC_INT16:
  5531. case AR_BASIC_INT32:
  5532. case AR_BASIC_INT64:
  5533. case AR_BASIC_UINT8:
  5534. case AR_BASIC_UINT16:
  5535. case AR_BASIC_UINT32:
  5536. case AR_BASIC_UINT64:
  5537. return false;
  5538. default:
  5539. break; // No other valid cast types
  5540. }
  5541. break;
  5542. case AR_BASIC_INT8:
  5543. switch (rightKind) {
  5544. // For backwards compat we consider signed/unsigned the same.
  5545. case AR_BASIC_LITERAL_INT:
  5546. case AR_BASIC_UINT8:
  5547. return false;
  5548. default:
  5549. break; // No other valid cast types
  5550. }
  5551. break;
  5552. case AR_BASIC_INT16:
  5553. switch (rightKind) {
  5554. // For backwards compat we consider signed/unsigned the same.
  5555. case AR_BASIC_LITERAL_INT:
  5556. case AR_BASIC_UINT16:
  5557. return false;
  5558. default:
  5559. break; // No other valid cast types
  5560. }
  5561. break;
  5562. case AR_BASIC_INT32:
  5563. switch (rightKind) {
  5564. // For backwards compat we consider signed/unsigned the same.
  5565. case AR_BASIC_LITERAL_INT:
  5566. case AR_BASIC_UINT32:
  5567. return false;
  5568. default:
  5569. break; // No other valid cast types.
  5570. }
  5571. break;
  5572. case AR_BASIC_INT64:
  5573. switch (rightKind) {
  5574. // For backwards compat we consider signed/unsigned the same.
  5575. case AR_BASIC_LITERAL_INT:
  5576. case AR_BASIC_UINT64:
  5577. return false;
  5578. default:
  5579. break; // No other valid cast types.
  5580. }
  5581. break;
  5582. case AR_BASIC_UINT8:
  5583. switch (rightKind) {
  5584. // For backwards compat we consider signed/unsigned the same.
  5585. case AR_BASIC_LITERAL_INT:
  5586. case AR_BASIC_INT8:
  5587. return false;
  5588. default:
  5589. break; // No other valid cast types.
  5590. }
  5591. break;
  5592. case AR_BASIC_UINT16:
  5593. switch (rightKind) {
  5594. // For backwards compat we consider signed/unsigned the same.
  5595. case AR_BASIC_LITERAL_INT:
  5596. case AR_BASIC_INT16:
  5597. return false;
  5598. default:
  5599. break; // No other valid cast types.
  5600. }
  5601. break;
  5602. case AR_BASIC_UINT32:
  5603. switch (rightKind) {
  5604. // For backwards compat we consider signed/unsigned the same.
  5605. case AR_BASIC_LITERAL_INT:
  5606. case AR_BASIC_INT32:
  5607. return false;
  5608. default:
  5609. break; // No other valid cast types.
  5610. }
  5611. break;
  5612. case AR_BASIC_UINT64:
  5613. switch (rightKind) {
  5614. // For backwards compat we consider signed/unsigned the same.
  5615. case AR_BASIC_LITERAL_INT:
  5616. case AR_BASIC_INT64:
  5617. return false;
  5618. default:
  5619. break; // No other valid cast types.
  5620. }
  5621. break;
  5622. case AR_BASIC_LITERAL_FLOAT:
  5623. switch (rightKind) {
  5624. case AR_BASIC_LITERAL_FLOAT:
  5625. case AR_BASIC_FLOAT16:
  5626. case AR_BASIC_FLOAT32:
  5627. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5628. case AR_BASIC_FLOAT64:
  5629. return false;
  5630. default:
  5631. break; // No other valid cast types.
  5632. }
  5633. break;
  5634. case AR_BASIC_FLOAT16:
  5635. switch (rightKind) {
  5636. case AR_BASIC_LITERAL_FLOAT:
  5637. return false;
  5638. default:
  5639. break; // No other valid cast types.
  5640. }
  5641. break;
  5642. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5643. switch (rightKind) {
  5644. case AR_BASIC_LITERAL_FLOAT:
  5645. return false;
  5646. default:
  5647. break; // No other valid cast types.
  5648. }
  5649. break;
  5650. case AR_BASIC_FLOAT32:
  5651. switch (rightKind) {
  5652. case AR_BASIC_LITERAL_FLOAT:
  5653. return false;
  5654. default:
  5655. break; // No other valid cast types.
  5656. }
  5657. break;
  5658. case AR_BASIC_FLOAT64:
  5659. switch (rightKind) {
  5660. case AR_BASIC_LITERAL_FLOAT:
  5661. return false;
  5662. default:
  5663. break; // No other valid cast types.
  5664. }
  5665. break;
  5666. default:
  5667. break; // No other relevant targets.
  5668. }
  5669. return true;
  5670. }
  5671. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5672. // Eliminate exact matches first, then check for casts.
  5673. if (leftKind == rightKind) {
  5674. return false;
  5675. }
  5676. //
  5677. // All minimum-bits types are only considered matches of themselves
  5678. // and thus are not in this table.
  5679. //
  5680. switch (leftKind) {
  5681. case AR_BASIC_LITERAL_INT:
  5682. switch (rightKind) {
  5683. case AR_BASIC_INT8:
  5684. case AR_BASIC_INT16:
  5685. case AR_BASIC_INT32:
  5686. case AR_BASIC_INT64:
  5687. case AR_BASIC_UINT8:
  5688. case AR_BASIC_UINT16:
  5689. case AR_BASIC_UINT32:
  5690. case AR_BASIC_UINT64:
  5691. return false;
  5692. default:
  5693. break; // No other valid conversions
  5694. }
  5695. break;
  5696. case AR_BASIC_INT8:
  5697. case AR_BASIC_INT16:
  5698. case AR_BASIC_INT32:
  5699. case AR_BASIC_INT64:
  5700. case AR_BASIC_UINT8:
  5701. case AR_BASIC_UINT16:
  5702. case AR_BASIC_UINT32:
  5703. case AR_BASIC_UINT64:
  5704. switch (rightKind) {
  5705. case AR_BASIC_LITERAL_INT:
  5706. return false;
  5707. default:
  5708. break; // No other valid conversions
  5709. }
  5710. break;
  5711. case AR_BASIC_LITERAL_FLOAT:
  5712. switch (rightKind) {
  5713. case AR_BASIC_LITERAL_FLOAT:
  5714. case AR_BASIC_FLOAT16:
  5715. case AR_BASIC_FLOAT32:
  5716. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5717. case AR_BASIC_FLOAT64:
  5718. return false;
  5719. default:
  5720. break; // No other valid conversions
  5721. }
  5722. break;
  5723. case AR_BASIC_FLOAT16:
  5724. case AR_BASIC_FLOAT32:
  5725. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5726. case AR_BASIC_FLOAT64:
  5727. switch (rightKind) {
  5728. case AR_BASIC_LITERAL_FLOAT:
  5729. return false;
  5730. default:
  5731. break; // No other valid conversions
  5732. }
  5733. break;
  5734. default:
  5735. // No other relevant targets
  5736. break;
  5737. }
  5738. return true;
  5739. }
  5740. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  5741. {
  5742. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  5743. return 0;
  5744. }
  5745. UINT64 uScore = 0;
  5746. UINT uLSize = GetNumElements(pLType);
  5747. UINT uRSize = GetNumElements(pRType);
  5748. UINT uCompareSize;
  5749. bool bLCast = false;
  5750. bool bRCast = false;
  5751. bool bLIntCast = false;
  5752. bool bRIntCast = false;
  5753. bool bLPromo = false;
  5754. bool bRPromo = false;
  5755. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  5756. if (uCompareSize > uRSize) {
  5757. uCompareSize = uRSize;
  5758. }
  5759. for (UINT i = 0; i < uCompareSize; i++) {
  5760. ArBasicKind LeftElementKind, RightElementKind;
  5761. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  5762. QualType leftSub = GetNthElementType(pLType, i);
  5763. QualType rightSub = GetNthElementType(pRType, i);
  5764. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  5765. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  5766. LeftElementKind = GetTypeElementKind(leftSub);
  5767. RightElementKind = GetTypeElementKind(rightSub);
  5768. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  5769. // information needed is the ShapeKind, EltKind and ObjKind.
  5770. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  5771. bool bCombine;
  5772. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  5773. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  5774. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  5775. ArBasicKind RightObjKind = RightElementKind;
  5776. LeftElementKind = LeftObjKind;
  5777. RightElementKind = RightObjKind;
  5778. if (leftKind != rightKind) {
  5779. bCombine = false;
  5780. }
  5781. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  5782. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  5783. }
  5784. }
  5785. else {
  5786. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  5787. }
  5788. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  5789. bLPromo = true;
  5790. }
  5791. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  5792. bLCast = true;
  5793. }
  5794. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  5795. bLIntCast = true;
  5796. }
  5797. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  5798. bRPromo = true;
  5799. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  5800. bRCast = true;
  5801. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  5802. bRIntCast = true;
  5803. }
  5804. } else {
  5805. bLCast = true;
  5806. bRCast = true;
  5807. }
  5808. }
  5809. #define SCORE_COND(shift, cond) { \
  5810. if (cond) uScore += 1ULL << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  5811. SCORE_COND(0, uRSize < uLSize);
  5812. SCORE_COND(1, bLPromo);
  5813. SCORE_COND(2, bRPromo);
  5814. SCORE_COND(3, bLIntCast);
  5815. SCORE_COND(4, bRIntCast);
  5816. SCORE_COND(5, bLCast);
  5817. SCORE_COND(6, bRCast);
  5818. SCORE_COND(7, uLSize < uRSize);
  5819. #undef SCORE_COND
  5820. // Make sure our scores fit in a UINT64.
  5821. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  5822. return uScore;
  5823. }
  5824. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  5825. DXASSERT(ics, "otherwise conversion has not been initialized");
  5826. if (!ics->isInitialized()) {
  5827. return 0;
  5828. }
  5829. if (!ics->isStandard()) {
  5830. return SCORE_MAX;
  5831. }
  5832. QualType fromType = ics->Standard.getFromType();
  5833. QualType toType = ics->Standard.getToType(2); // final type
  5834. return ScoreCast(toType, fromType);
  5835. }
  5836. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  5837. // Ignore target version mismatches.
  5838. // in/out considerations have been taken care of by viability.
  5839. // 'this' considerations don't matter without inheritance, other
  5840. // than lookup and viability.
  5841. UINT64 result = 0;
  5842. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  5843. UINT64 score;
  5844. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  5845. if (score == SCORE_MAX) {
  5846. return SCORE_MAX;
  5847. }
  5848. result += score;
  5849. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  5850. if (score == SCORE_MAX) {
  5851. return SCORE_MAX;
  5852. }
  5853. result += score;
  5854. }
  5855. return result;
  5856. }
  5857. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  5858. SourceLocation Loc,
  5859. OverloadCandidateSet& set,
  5860. OverloadCandidateSet::iterator& Best)
  5861. {
  5862. UINT64 bestScore = SCORE_MAX;
  5863. unsigned scoreMatch = 0;
  5864. Best = set.end();
  5865. if (set.size() == 1 && set.begin()->Viable) {
  5866. Best = set.begin();
  5867. return OR_Success;
  5868. }
  5869. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  5870. if (Cand->Viable) {
  5871. UINT64 score = ScoreFunction(Cand);
  5872. if (score != SCORE_MAX) {
  5873. if (score == bestScore) {
  5874. ++scoreMatch;
  5875. } else if (score < bestScore) {
  5876. Best = Cand;
  5877. scoreMatch = 1;
  5878. bestScore = score;
  5879. }
  5880. }
  5881. }
  5882. }
  5883. if (Best == set.end()) {
  5884. return OR_No_Viable_Function;
  5885. }
  5886. if (scoreMatch > 1) {
  5887. Best = set.end();
  5888. return OR_Ambiguous;
  5889. }
  5890. // No need to check for deleted functions to yield OR_Deleted.
  5891. return OR_Success;
  5892. }
  5893. /// <summary>
  5894. /// Initializes the specified <paramref name="initSequence" /> describing how
  5895. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  5896. /// </summary>
  5897. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  5898. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  5899. /// <param name="Args">Arguments to the initialization.</param>
  5900. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  5901. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  5902. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  5903. const InitializedEntity& Entity,
  5904. const InitializationKind& Kind,
  5905. MultiExprArg Args,
  5906. bool TopLevelOfInitList,
  5907. _Inout_ InitializationSequence* initSequence)
  5908. {
  5909. DXASSERT_NOMSG(initSequence != nullptr);
  5910. // In HLSL there are no default initializers, eg float4x4 m();
  5911. if (Kind.getKind() == InitializationKind::IK_Default) {
  5912. return;
  5913. }
  5914. // Value initializers occur for temporaries with empty parens or braces.
  5915. if (Kind.getKind() == InitializationKind::IK_Value) {
  5916. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  5917. SilenceSequenceDiagnostics(initSequence);
  5918. return;
  5919. }
  5920. // If we have a DirectList, we should have a single InitListExprClass argument.
  5921. DXASSERT(
  5922. Kind.getKind() != InitializationKind::IK_DirectList ||
  5923. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  5924. "otherwise caller is passing in incorrect initialization configuration");
  5925. bool isCast = Kind.isCStyleCast();
  5926. QualType destType = Entity.getType();
  5927. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  5928. // Direct initialization occurs for explicit constructor arguments.
  5929. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  5930. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  5931. !Kind.isCStyleOrFunctionalCast()) {
  5932. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  5933. SilenceSequenceDiagnostics(initSequence);
  5934. return;
  5935. }
  5936. bool flatten =
  5937. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  5938. Kind.getKind() == InitializationKind::IK_DirectList ||
  5939. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  5940. if (flatten) {
  5941. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  5942. // array types to adjust the value - we do calculate this as part of type analysis.
  5943. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  5944. FlattenedTypeIterator::ComparisonResult comparisonResult =
  5945. FlattenedTypeIterator::CompareTypesForInit(
  5946. *this, destType, Args,
  5947. Kind.getLocation(), Kind.getLocation());
  5948. if (comparisonResult.IsConvertibleAndEqualLength() ||
  5949. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  5950. {
  5951. initSequence->AddListInitializationStep(destType);
  5952. }
  5953. else
  5954. {
  5955. SourceLocation diagLocation;
  5956. if (Args.size() > 0)
  5957. {
  5958. diagLocation = Args.front()->getLocStart();
  5959. }
  5960. else
  5961. {
  5962. diagLocation = Entity.getDiagLoc();
  5963. }
  5964. if (comparisonResult.IsEqualLength()) {
  5965. m_sema->Diag(diagLocation, diag::err_hlsl_type_mismatch);
  5966. }
  5967. else {
  5968. m_sema->Diag(diagLocation,
  5969. diag::err_incorrect_num_initializers)
  5970. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  5971. << IsSubobjectType(destType)
  5972. << comparisonResult.LeftCount << comparisonResult.RightCount;
  5973. }
  5974. SilenceSequenceDiagnostics(initSequence);
  5975. }
  5976. }
  5977. else {
  5978. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  5979. Expr* firstArg = Args.front();
  5980. if (IsExpressionBinaryComma(firstArg)) {
  5981. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  5982. }
  5983. ExprResult expr = ExprResult(firstArg);
  5984. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  5985. Sema::CheckedConversionKind::CCK_CStyleCast :
  5986. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  5987. unsigned int msg = 0;
  5988. CastKind castKind;
  5989. CXXCastPath basePath;
  5990. SourceRange range = Kind.getRange();
  5991. ImplicitConversionSequence ics;
  5992. ics.setStandard();
  5993. bool castWorked = TryStaticCastForHLSL(
  5994. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  5995. if (castWorked) {
  5996. if (destType.getCanonicalType() ==
  5997. firstArg->getType().getCanonicalType() &&
  5998. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  5999. initSequence->AddCAssignmentStep(destType);
  6000. } else {
  6001. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  6002. }
  6003. }
  6004. else {
  6005. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  6006. }
  6007. }
  6008. }
  6009. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6010. const QualType& sourceType,
  6011. const QualType& targetType,
  6012. bool explicitConversion)
  6013. {
  6014. DXASSERT_NOMSG(!sourceType.isNull());
  6015. DXASSERT_NOMSG(!targetType.isNull());
  6016. ArTypeInfo sourceTypeInfo;
  6017. ArTypeInfo targetTypeInfo;
  6018. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  6019. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  6020. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  6021. {
  6022. return false;
  6023. }
  6024. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  6025. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  6026. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  6027. !isVecMatTrunc)
  6028. {
  6029. return false;
  6030. }
  6031. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  6032. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  6033. return true;
  6034. }
  6035. // Same struct is eqaul.
  6036. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  6037. sourceType.getCanonicalType().getUnqualifiedType() ==
  6038. targetType.getCanonicalType().getUnqualifiedType()) {
  6039. return true;
  6040. }
  6041. // DerivedFrom is less.
  6042. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  6043. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  6044. const RecordType *targetRT = targetType->getAsStructureType();
  6045. if (!targetRT)
  6046. targetRT = dyn_cast<RecordType>(targetType);
  6047. const RecordType *sourceRT = sourceType->getAsStructureType();
  6048. if (!sourceRT)
  6049. sourceRT = dyn_cast<RecordType>(sourceType);
  6050. if (targetRT && sourceRT) {
  6051. RecordDecl *targetRD = targetRT->getDecl();
  6052. RecordDecl *sourceRD = sourceRT->getDecl();
  6053. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6054. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6055. if (targetCXXRD && sourceCXXRD) {
  6056. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  6057. return true;
  6058. }
  6059. }
  6060. }
  6061. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  6062. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  6063. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  6064. {
  6065. return false;
  6066. }
  6067. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  6068. }
  6069. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6070. const ExprResult& sourceExpr,
  6071. const QualType& targetType,
  6072. bool explicitConversion)
  6073. {
  6074. if (sourceExpr.isInvalid() || targetType.isNull())
  6075. {
  6076. return false;
  6077. }
  6078. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  6079. }
  6080. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  6081. {
  6082. DXASSERT_NOMSG(!type.isNull());
  6083. DXASSERT_NOMSG(count != nullptr);
  6084. *count = 0;
  6085. UINT subCount = 0;
  6086. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  6087. switch (shapeKind)
  6088. {
  6089. case AR_TOBJ_ARRAY:
  6090. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  6091. {
  6092. *count = subCount * GetArraySize(type);
  6093. return true;
  6094. }
  6095. return false;
  6096. case AR_TOBJ_COMPOUND:
  6097. {
  6098. UINT maxCount = 0;
  6099. { // Determine maximum count to prevent infinite loop on incomplete array
  6100. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  6101. maxCount = itCount.countRemaining();
  6102. if (!maxCount) {
  6103. return false; // empty struct.
  6104. }
  6105. }
  6106. FlattenedTypeIterator it(SourceLocation(), type, *this);
  6107. while (it.hasCurrentElement()) {
  6108. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  6109. if (!isFieldNumeric) {
  6110. return false;
  6111. }
  6112. if (*count >= maxCount) {
  6113. // this element is an incomplete array at the end; iterator will not advance past this element.
  6114. // don't add to *count either, so *count will represent minimum size of the structure.
  6115. break;
  6116. }
  6117. *count += (subCount * it.getCurrentElementSize());
  6118. it.advanceCurrentElement(it.getCurrentElementSize());
  6119. }
  6120. return true;
  6121. }
  6122. default:
  6123. DXASSERT(false, "unreachable");
  6124. case AR_TOBJ_BASIC:
  6125. case AR_TOBJ_MATRIX:
  6126. case AR_TOBJ_VECTOR:
  6127. *count = GetElementCount(type);
  6128. return IsBasicKindNumeric(GetTypeElementKind(type));
  6129. case AR_TOBJ_OBJECT:
  6130. case AR_TOBJ_STRING:
  6131. return false;
  6132. }
  6133. }
  6134. enum MatrixMemberAccessError {
  6135. MatrixMemberAccessError_None, // No errors found.
  6136. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  6137. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  6138. MatrixMemberAccessError_Empty, // No members specified.
  6139. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  6140. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  6141. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6142. };
  6143. static
  6144. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  6145. {
  6146. DXASSERT_NOMSG(memberText != nullptr);
  6147. DXASSERT_NOMSG(value != nullptr);
  6148. if ('0' <= *memberText && *memberText <= '9')
  6149. {
  6150. *value = (*memberText) - '0';
  6151. }
  6152. else
  6153. {
  6154. return MatrixMemberAccessError_BadFormat;
  6155. }
  6156. memberText++;
  6157. return MatrixMemberAccessError_None;
  6158. }
  6159. static
  6160. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  6161. {
  6162. DXASSERT_NOMSG(memberText != nullptr);
  6163. DXASSERT_NOMSG(value != nullptr);
  6164. MatrixMemberAccessPositions result;
  6165. bool zeroBasedDecided = false;
  6166. bool zeroBased = false;
  6167. // Set the output value to invalid to allow early exits when errors are found.
  6168. value->IsValid = 0;
  6169. // Assume this is true until proven otherwise.
  6170. result.IsValid = 1;
  6171. result.Count = 0;
  6172. while (*memberText)
  6173. {
  6174. // Check for a leading underscore.
  6175. if (*memberText != '_')
  6176. {
  6177. return MatrixMemberAccessError_BadFormat;
  6178. }
  6179. ++memberText;
  6180. // Check whether we have an 'm' or a digit.
  6181. if (*memberText == 'm')
  6182. {
  6183. if (zeroBasedDecided && !zeroBased)
  6184. {
  6185. return MatrixMemberAccessError_MixingRefs;
  6186. }
  6187. zeroBased = true;
  6188. zeroBasedDecided = true;
  6189. ++memberText;
  6190. }
  6191. else if (!('0' <= *memberText && *memberText <= '9'))
  6192. {
  6193. return MatrixMemberAccessError_BadFormat;
  6194. }
  6195. else
  6196. {
  6197. if (zeroBasedDecided && zeroBased)
  6198. {
  6199. return MatrixMemberAccessError_MixingRefs;
  6200. }
  6201. zeroBased = false;
  6202. zeroBasedDecided = true;
  6203. }
  6204. // Consume two digits for the position.
  6205. uint32_t rowPosition;
  6206. uint32_t colPosition;
  6207. MatrixMemberAccessError digitError;
  6208. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  6209. {
  6210. return digitError;
  6211. }
  6212. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  6213. {
  6214. return digitError;
  6215. }
  6216. // Look for specific common errors (developer likely mixed up reference style).
  6217. if (zeroBased)
  6218. {
  6219. if (rowPosition == 4 || colPosition == 4)
  6220. {
  6221. return MatrixMemberAccessError_FourInZeroBased;
  6222. }
  6223. }
  6224. else
  6225. {
  6226. if (rowPosition == 0 || colPosition == 0)
  6227. {
  6228. return MatrixMemberAccessError_ZeroInOneBased;
  6229. }
  6230. // SetPosition will use zero-based indices.
  6231. --rowPosition;
  6232. --colPosition;
  6233. }
  6234. if (result.Count == 4)
  6235. {
  6236. return MatrixMemberAccessError_TooManyPositions;
  6237. }
  6238. result.SetPosition(result.Count, rowPosition, colPosition);
  6239. result.Count++;
  6240. }
  6241. if (result.Count == 0)
  6242. {
  6243. return MatrixMemberAccessError_Empty;
  6244. }
  6245. *value = result;
  6246. return MatrixMemberAccessError_None;
  6247. }
  6248. bool HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  6249. Expr& BaseExpr,
  6250. DeclarationName MemberName,
  6251. bool IsArrow,
  6252. SourceLocation OpLoc,
  6253. SourceLocation MemberLoc,
  6254. ExprResult* result)
  6255. {
  6256. DXASSERT_NOMSG(result != nullptr);
  6257. QualType BaseType = BaseExpr.getType();
  6258. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6259. // Assume failure.
  6260. *result = ExprError();
  6261. if (GetTypeObjectKind(BaseType) != AR_TOBJ_MATRIX)
  6262. {
  6263. return false;
  6264. }
  6265. QualType elementType;
  6266. UINT rowCount, colCount;
  6267. GetRowsAndCols(BaseType, rowCount, colCount);
  6268. elementType = GetMatrixOrVectorElementType(BaseType);
  6269. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6270. const char *memberText = member->getNameStart();
  6271. MatrixMemberAccessPositions positions;
  6272. MatrixMemberAccessError memberAccessError;
  6273. unsigned msg = 0;
  6274. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  6275. switch (memberAccessError)
  6276. {
  6277. case MatrixMemberAccessError_BadFormat:
  6278. msg = diag::err_hlsl_matrix_member_bad_format;
  6279. break;
  6280. case MatrixMemberAccessError_Empty:
  6281. msg = diag::err_hlsl_matrix_member_empty;
  6282. break;
  6283. case MatrixMemberAccessError_FourInZeroBased:
  6284. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  6285. break;
  6286. case MatrixMemberAccessError_MixingRefs:
  6287. msg = diag::err_hlsl_matrix_member_mixing_refs;
  6288. break;
  6289. case MatrixMemberAccessError_None:
  6290. msg = 0;
  6291. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6292. // Check the position with the type now.
  6293. for (unsigned int i = 0; i < positions.Count; i++)
  6294. {
  6295. uint32_t rowPos, colPos;
  6296. positions.GetPosition(i, &rowPos, &colPos);
  6297. if (rowPos >= rowCount || colPos >= colCount)
  6298. {
  6299. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  6300. break;
  6301. }
  6302. }
  6303. break;
  6304. case MatrixMemberAccessError_TooManyPositions:
  6305. msg = diag::err_hlsl_matrix_member_too_many_positions;
  6306. break;
  6307. case MatrixMemberAccessError_ZeroInOneBased:
  6308. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  6309. break;
  6310. default:
  6311. llvm_unreachable("Unknown MatrixMemberAccessError value");
  6312. }
  6313. if (msg != 0)
  6314. {
  6315. m_sema->Diag(MemberLoc, msg) << memberText;
  6316. // It's possible that it's a simple out-of-bounds condition. In this case,
  6317. // generate the member access expression with the correct arity and continue
  6318. // processing.
  6319. if (!positions.IsValid)
  6320. {
  6321. return true;
  6322. }
  6323. }
  6324. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6325. // Consume elements
  6326. QualType resultType;
  6327. if (positions.Count == 1)
  6328. resultType = elementType;
  6329. else
  6330. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6331. // Add qualifiers from BaseType.
  6332. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6333. ExprValueKind VK =
  6334. positions.ContainsDuplicateElements() ? VK_RValue :
  6335. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6336. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6337. *result = matrixExpr;
  6338. return true;
  6339. }
  6340. enum VectorMemberAccessError {
  6341. VectorMemberAccessError_None, // No errors found.
  6342. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  6343. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  6344. VectorMemberAccessError_Empty, // No members specified.
  6345. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6346. };
  6347. static
  6348. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  6349. DXASSERT_NOMSG(memberText != nullptr);
  6350. DXASSERT_NOMSG(value != nullptr);
  6351. rgbaStyle = false;
  6352. switch (*memberText) {
  6353. case 'r':
  6354. rgbaStyle = true;
  6355. case 'x':
  6356. *value = 0;
  6357. break;
  6358. case 'g':
  6359. rgbaStyle = true;
  6360. case 'y':
  6361. *value = 1;
  6362. break;
  6363. case 'b':
  6364. rgbaStyle = true;
  6365. case 'z':
  6366. *value = 2;
  6367. break;
  6368. case 'a':
  6369. rgbaStyle = true;
  6370. case 'w':
  6371. *value = 3;
  6372. break;
  6373. default:
  6374. return VectorMemberAccessError_BadFormat;
  6375. }
  6376. memberText++;
  6377. return VectorMemberAccessError_None;
  6378. }
  6379. static
  6380. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  6381. DXASSERT_NOMSG(memberText != nullptr);
  6382. DXASSERT_NOMSG(value != nullptr);
  6383. VectorMemberAccessPositions result;
  6384. bool rgbaStyleDecided = false;
  6385. bool rgbaStyle = false;
  6386. // Set the output value to invalid to allow early exits when errors are found.
  6387. value->IsValid = 0;
  6388. // Assume this is true until proven otherwise.
  6389. result.IsValid = 1;
  6390. result.Count = 0;
  6391. while (*memberText) {
  6392. // Consume one character for the swizzle.
  6393. uint32_t colPosition;
  6394. VectorMemberAccessError digitError;
  6395. bool rgbaStyleTmp = false;
  6396. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6397. return digitError;
  6398. }
  6399. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6400. return VectorMemberAccessError_MixingStyles;
  6401. }
  6402. else {
  6403. rgbaStyleDecided = true;
  6404. rgbaStyle = rgbaStyleTmp;
  6405. }
  6406. if (result.Count == 4) {
  6407. return VectorMemberAccessError_TooManyPositions;
  6408. }
  6409. result.SetPosition(result.Count, colPosition);
  6410. result.Count++;
  6411. }
  6412. if (result.Count == 0) {
  6413. return VectorMemberAccessError_Empty;
  6414. }
  6415. *value = result;
  6416. return VectorMemberAccessError_None;
  6417. }
  6418. bool HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6419. Expr& BaseExpr,
  6420. DeclarationName MemberName,
  6421. bool IsArrow,
  6422. SourceLocation OpLoc,
  6423. SourceLocation MemberLoc,
  6424. ExprResult* result) {
  6425. DXASSERT_NOMSG(result != nullptr);
  6426. QualType BaseType = BaseExpr.getType();
  6427. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6428. // Assume failure.
  6429. *result = ExprError();
  6430. if (GetTypeObjectKind(BaseType) != AR_TOBJ_VECTOR) {
  6431. return false;
  6432. }
  6433. QualType elementType;
  6434. UINT colCount = GetHLSLVecSize(BaseType);
  6435. elementType = GetMatrixOrVectorElementType(BaseType);
  6436. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6437. const char *memberText = member->getNameStart();
  6438. VectorMemberAccessPositions positions;
  6439. VectorMemberAccessError memberAccessError;
  6440. unsigned msg = 0;
  6441. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6442. switch (memberAccessError) {
  6443. case VectorMemberAccessError_BadFormat:
  6444. msg = diag::err_hlsl_vector_member_bad_format;
  6445. break;
  6446. case VectorMemberAccessError_Empty:
  6447. msg = diag::err_hlsl_vector_member_empty;
  6448. break;
  6449. case VectorMemberAccessError_MixingStyles:
  6450. msg = diag::err_ext_vector_component_name_mixedsets;
  6451. break;
  6452. case VectorMemberAccessError_None:
  6453. msg = 0;
  6454. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6455. // Check the position with the type now.
  6456. for (unsigned int i = 0; i < positions.Count; i++) {
  6457. uint32_t colPos;
  6458. positions.GetPosition(i, &colPos);
  6459. if (colPos >= colCount) {
  6460. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6461. break;
  6462. }
  6463. }
  6464. break;
  6465. case VectorMemberAccessError_TooManyPositions:
  6466. msg = diag::err_hlsl_vector_member_too_many_positions;
  6467. break;
  6468. default:
  6469. llvm_unreachable("Unknown VectorMemberAccessError value");
  6470. }
  6471. if (msg != 0) {
  6472. m_sema->Diag(MemberLoc, msg) << memberText;
  6473. // It's possible that it's a simple out-of-bounds condition. In this case,
  6474. // generate the member access expression with the correct arity and continue
  6475. // processing.
  6476. if (!positions.IsValid) {
  6477. return true;
  6478. }
  6479. }
  6480. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6481. // Consume elements
  6482. QualType resultType;
  6483. if (positions.Count == 1)
  6484. resultType = elementType;
  6485. else
  6486. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6487. // Add qualifiers from BaseType.
  6488. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6489. ExprValueKind VK =
  6490. positions.ContainsDuplicateElements() ? VK_RValue :
  6491. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6492. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6493. *result = vectorExpr;
  6494. return true;
  6495. }
  6496. bool HLSLExternalSource::LookupArrayMemberExprForHLSL(
  6497. Expr& BaseExpr,
  6498. DeclarationName MemberName,
  6499. bool IsArrow,
  6500. SourceLocation OpLoc,
  6501. SourceLocation MemberLoc,
  6502. ExprResult* result) {
  6503. DXASSERT_NOMSG(result != nullptr);
  6504. QualType BaseType = BaseExpr.getType();
  6505. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6506. // Assume failure.
  6507. *result = ExprError();
  6508. if (GetTypeObjectKind(BaseType) != AR_TOBJ_ARRAY) {
  6509. return false;
  6510. }
  6511. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6512. const char *memberText = member->getNameStart();
  6513. // The only property available on arrays is Length; it is deprecated and available only on HLSL version <=2018
  6514. if (member->getLength() == 6 && 0 == strcmp(memberText, "Length")) {
  6515. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(BaseType)) {
  6516. // check version support
  6517. unsigned hlslVer = getSema()->getLangOpts().HLSLVersion;
  6518. if (hlslVer > 2016) {
  6519. m_sema->Diag(MemberLoc, diag::err_hlsl_unsupported_for_version_lower) << "Length" << "2016";
  6520. return false;
  6521. }
  6522. if (hlslVer == 2016) {
  6523. m_sema->Diag(MemberLoc, diag::warn_deprecated) << "Length";
  6524. }
  6525. UnaryExprOrTypeTraitExpr *arrayLenExpr = new (m_context) UnaryExprOrTypeTraitExpr(
  6526. UETT_ArrayLength, &BaseExpr, m_context->getSizeType(), MemberLoc, BaseExpr.getSourceRange().getEnd());
  6527. *result = arrayLenExpr;
  6528. return true;
  6529. }
  6530. }
  6531. return false;
  6532. }
  6533. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  6534. DXASSERT_NOMSG(E != nullptr);
  6535. ArBasicKind basic = GetTypeElementKind(E->getType());
  6536. if (!IS_BASIC_PRIMITIVE(basic)) {
  6537. return E;
  6538. }
  6539. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  6540. if (kind != AR_TOBJ_SCALAR) {
  6541. return E;
  6542. }
  6543. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  6544. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  6545. }
  6546. static clang::CastKind ImplicitConversionKindToCastKind(
  6547. clang::ImplicitConversionKind ICK,
  6548. ArBasicKind FromKind,
  6549. ArBasicKind ToKind) {
  6550. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  6551. // based on from/to kinds in order to determine CastKind?
  6552. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  6553. // problem.
  6554. switch (ICK) {
  6555. case ICK_Integral_Promotion:
  6556. case ICK_Integral_Conversion:
  6557. return CK_IntegralCast;
  6558. case ICK_Floating_Promotion:
  6559. case ICK_Floating_Conversion:
  6560. return CK_FloatingCast;
  6561. case ICK_Floating_Integral:
  6562. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  6563. return CK_FloatingToIntegral;
  6564. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  6565. return CK_IntegralToFloating;
  6566. break;
  6567. case ICK_Boolean_Conversion:
  6568. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  6569. return CK_FloatingToBoolean;
  6570. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  6571. return CK_IntegralToBoolean;
  6572. break;
  6573. default:
  6574. // Only covers implicit conversions with cast kind equivalents.
  6575. return CK_Invalid;
  6576. }
  6577. return CK_Invalid;
  6578. }
  6579. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  6580. switch (CK) {
  6581. case CK_IntegralCast:
  6582. return CK_HLSLCC_IntegralCast;
  6583. case CK_FloatingCast:
  6584. return CK_HLSLCC_FloatingCast;
  6585. case CK_FloatingToIntegral:
  6586. return CK_HLSLCC_FloatingToIntegral;
  6587. case CK_IntegralToFloating:
  6588. return CK_HLSLCC_IntegralToFloating;
  6589. case CK_FloatingToBoolean:
  6590. return CK_HLSLCC_FloatingToBoolean;
  6591. case CK_IntegralToBoolean:
  6592. return CK_HLSLCC_IntegralToBoolean;
  6593. default:
  6594. // Only HLSLCC castkinds are relevant. Ignore the rest.
  6595. return CK_Invalid;
  6596. }
  6597. return CK_Invalid;
  6598. }
  6599. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  6600. _In_ clang::Sema* self,
  6601. _In_ clang::Expr* From,
  6602. ArTypeObjectKind FromShape,
  6603. ArBasicKind EltKind)
  6604. {
  6605. clang::CastKind CK = CK_Invalid;
  6606. if (AR_TOBJ_MATRIX == FromShape)
  6607. CK = CK_HLSLMatrixToScalarCast;
  6608. if (AR_TOBJ_VECTOR == FromShape)
  6609. CK = CK_HLSLVectorToScalarCast;
  6610. if (CK_Invalid != CK) {
  6611. return self->ImpCastExprToType(From,
  6612. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  6613. }
  6614. return From;
  6615. }
  6616. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  6617. _In_ clang::Expr* From,
  6618. _In_ clang::QualType targetType,
  6619. _In_ const clang::StandardConversionSequence &SCS,
  6620. _In_ clang::Sema::CheckedConversionKind CCK)
  6621. {
  6622. QualType sourceType = From->getType();
  6623. sourceType = GetStructuralForm(sourceType);
  6624. targetType = GetStructuralForm(targetType);
  6625. ArTypeInfo SourceInfo, TargetInfo;
  6626. CollectInfo(sourceType, &SourceInfo);
  6627. CollectInfo(targetType, &TargetInfo);
  6628. clang::CastKind CK = CK_Invalid;
  6629. QualType intermediateTarget;
  6630. // TODO: construct vector/matrix and component cast expressions
  6631. switch (SCS.Second) {
  6632. case ICK_Flat_Conversion: {
  6633. // TODO: determine how to handle individual component conversions:
  6634. // - have an array of conversions for ComponentConversion in SCS?
  6635. // convert that to an array of casts under a special kind of flat
  6636. // flat conversion node? What do component conversion casts cast
  6637. // from? We don't have a From expression for individiual components.
  6638. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6639. break;
  6640. }
  6641. case ICK_HLSL_Derived_To_Base: {
  6642. CXXCastPath BasePath;
  6643. if (m_sema->CheckDerivedToBaseConversion(
  6644. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  6645. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  6646. return ExprError();
  6647. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  6648. break;
  6649. }
  6650. case ICK_HLSLVector_Splat: {
  6651. // 1. optionally convert from vec1 or mat1x1 to scalar
  6652. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6653. // 2. optionally convert component type
  6654. if (ICK_Identity != SCS.ComponentConversion) {
  6655. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6656. if (CK_Invalid != CK) {
  6657. From = m_sema->ImpCastExprToType(From,
  6658. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6659. }
  6660. }
  6661. // 3. splat scalar to final vector or matrix
  6662. CK = CK_Invalid;
  6663. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  6664. CK = CK_HLSLVectorSplat;
  6665. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  6666. CK = CK_HLSLMatrixSplat;
  6667. if (CK_Invalid != CK) {
  6668. From = m_sema->ImpCastExprToType(From,
  6669. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6670. }
  6671. break;
  6672. }
  6673. case ICK_HLSLVector_Scalar: {
  6674. // 1. select vector or matrix component
  6675. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6676. // 2. optionally convert component type
  6677. if (ICK_Identity != SCS.ComponentConversion) {
  6678. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6679. if (CK_Invalid != CK) {
  6680. From = m_sema->ImpCastExprToType(From,
  6681. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6682. }
  6683. }
  6684. break;
  6685. }
  6686. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  6687. // can be done with case fall-through, since this is the order in which we want to
  6688. // do the conversion operations.
  6689. case ICK_HLSLVector_Truncation: {
  6690. // 1. dimension truncation
  6691. // vector truncation or matrix truncation?
  6692. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  6693. From = m_sema->ImpCastExprToType(From,
  6694. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  6695. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6696. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  6697. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  6698. // Handle the column to vector case
  6699. From = m_sema->ImpCastExprToType(From,
  6700. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  6701. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6702. } else {
  6703. From = m_sema->ImpCastExprToType(From,
  6704. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6705. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6706. }
  6707. } else {
  6708. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  6709. }
  6710. }
  6711. __fallthrough;
  6712. case ICK_HLSLVector_Conversion: {
  6713. // 2. Do ShapeKind conversion if necessary
  6714. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  6715. switch (TargetInfo.ShapeKind) {
  6716. case AR_TOBJ_VECTOR:
  6717. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6718. From = m_sema->ImpCastExprToType(From,
  6719. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6720. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6721. break;
  6722. case AR_TOBJ_MATRIX:
  6723. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6724. From = m_sema->ImpCastExprToType(From,
  6725. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6726. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6727. break;
  6728. case AR_TOBJ_BASIC:
  6729. // Truncation may be followed by cast to scalar
  6730. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6731. break;
  6732. default:
  6733. DXASSERT(false, "otherwise, invalid casting sequence");
  6734. break;
  6735. }
  6736. }
  6737. // 3. Do component type conversion
  6738. if (ICK_Identity != SCS.ComponentConversion) {
  6739. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6740. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  6741. CK = ConvertToComponentCastKind(CK);
  6742. if (CK_Invalid != CK) {
  6743. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6744. }
  6745. }
  6746. break;
  6747. }
  6748. case ICK_Identity:
  6749. // Nothing to do.
  6750. break;
  6751. default:
  6752. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  6753. }
  6754. return From;
  6755. }
  6756. void HLSLExternalSource::GetConversionForm(
  6757. QualType type,
  6758. bool explicitConversion,
  6759. ArTypeInfo* pTypeInfo)
  6760. {
  6761. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  6762. CollectInfo(type, pTypeInfo);
  6763. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  6764. // but that value is only used for pointer conversions.
  6765. // When explicitly converting types complex aggregates can be treated
  6766. // as vectors if they are entirely numeric.
  6767. switch (pTypeInfo->ShapeKind)
  6768. {
  6769. case AR_TOBJ_COMPOUND:
  6770. case AR_TOBJ_ARRAY:
  6771. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  6772. {
  6773. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  6774. }
  6775. else
  6776. {
  6777. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  6778. }
  6779. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  6780. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  6781. break;
  6782. case AR_TOBJ_VECTOR:
  6783. case AR_TOBJ_MATRIX:
  6784. // Convert 1x1 types to scalars.
  6785. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  6786. {
  6787. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  6788. }
  6789. break;
  6790. default:
  6791. // Only convertable shapekinds are relevant.
  6792. break;
  6793. }
  6794. }
  6795. static
  6796. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  6797. {
  6798. DXASSERT_NOMSG(allowed != nullptr);
  6799. bool applicable = true;
  6800. *allowed = true;
  6801. if (explicitConversion) {
  6802. // (void) non-void
  6803. if (target->isVoidType()) {
  6804. DXASSERT_NOMSG(*allowed);
  6805. }
  6806. // (non-void) void
  6807. else if (source->isVoidType()) {
  6808. *allowed = false;
  6809. }
  6810. else {
  6811. applicable = false;
  6812. }
  6813. }
  6814. else {
  6815. // (void) void
  6816. if (source->isVoidType() && target->isVoidType()) {
  6817. DXASSERT_NOMSG(*allowed);
  6818. }
  6819. // (void) non-void, (non-void) void
  6820. else if (source->isVoidType() || target->isVoidType()) {
  6821. *allowed = false;
  6822. }
  6823. else {
  6824. applicable = false;
  6825. }
  6826. }
  6827. return applicable;
  6828. }
  6829. static bool ConvertDimensions(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  6830. ImplicitConversionKind &Second,
  6831. TYPE_CONVERSION_REMARKS &Remarks) {
  6832. // The rules for aggregate conversions are:
  6833. // 1. A scalar can be replicated to any layout.
  6834. // 2. Any type may be truncated to anything else with one component.
  6835. // 3. A vector may be truncated to a smaller vector.
  6836. // 4. A matrix may be truncated to a smaller matrix.
  6837. // 5. The result of a vector and a matrix is:
  6838. // a. If the matrix has one row it's a vector-sized
  6839. // piece of the row.
  6840. // b. If the matrix has one column it's a vector-sized
  6841. // piece of the column.
  6842. // c. Otherwise the number of elements in the vector
  6843. // and matrix must match and the result is the vector.
  6844. // 6. The result of a matrix and a vector is similar to #5.
  6845. switch (TargetInfo.ShapeKind) {
  6846. case AR_TOBJ_BASIC:
  6847. switch (SourceInfo.ShapeKind)
  6848. {
  6849. case AR_TOBJ_BASIC:
  6850. Second = ICK_Identity;
  6851. break;
  6852. case AR_TOBJ_VECTOR:
  6853. if (1 < SourceInfo.uCols)
  6854. Second = ICK_HLSLVector_Truncation;
  6855. else
  6856. Second = ICK_HLSLVector_Scalar;
  6857. break;
  6858. case AR_TOBJ_MATRIX:
  6859. if (1 < SourceInfo.uRows * SourceInfo.uCols)
  6860. Second = ICK_HLSLVector_Truncation;
  6861. else
  6862. Second = ICK_HLSLVector_Scalar;
  6863. break;
  6864. default:
  6865. return false;
  6866. }
  6867. break;
  6868. case AR_TOBJ_VECTOR:
  6869. switch (SourceInfo.ShapeKind)
  6870. {
  6871. case AR_TOBJ_BASIC:
  6872. // Conversions between scalars and aggregates are always supported.
  6873. Second = ICK_HLSLVector_Splat;
  6874. break;
  6875. case AR_TOBJ_VECTOR:
  6876. if (TargetInfo.uCols > SourceInfo.uCols) {
  6877. if (SourceInfo.uCols == 1) {
  6878. Second = ICK_HLSLVector_Splat;
  6879. }
  6880. else {
  6881. return false;
  6882. }
  6883. }
  6884. else if (TargetInfo.uCols < SourceInfo.uCols) {
  6885. Second = ICK_HLSLVector_Truncation;
  6886. }
  6887. else {
  6888. Second = ICK_Identity;
  6889. }
  6890. break;
  6891. case AR_TOBJ_MATRIX: {
  6892. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6893. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  6894. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  6895. Second = ICK_HLSLVector_Splat;
  6896. }
  6897. else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  6898. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  6899. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  6900. return false;
  6901. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  6902. Second = ICK_HLSLVector_Truncation;
  6903. else // equalivalent: O == N*M
  6904. Second = ICK_HLSLVector_Conversion;
  6905. }
  6906. else if (TargetInfo.uCols == 1 && SourceComponents > 1) {
  6907. Second = ICK_HLSLVector_Truncation;
  6908. }
  6909. else if (TargetInfo.uCols != SourceComponents) {
  6910. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  6911. return false;
  6912. }
  6913. else {
  6914. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  6915. Second = ICK_HLSLVector_Conversion;
  6916. }
  6917. break;
  6918. }
  6919. default:
  6920. return false;
  6921. }
  6922. break;
  6923. case AR_TOBJ_MATRIX: {
  6924. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  6925. switch (SourceInfo.ShapeKind)
  6926. {
  6927. case AR_TOBJ_BASIC:
  6928. // Conversions between scalars and aggregates are always supported.
  6929. Second = ICK_HLSLVector_Splat;
  6930. break;
  6931. case AR_TOBJ_VECTOR: {
  6932. // We can only convert vector to matrix in following cases:
  6933. // - splat from vector<...,1>
  6934. // - same number of components
  6935. // - one target component (truncate to scalar)
  6936. // - matrix has one row or one column, and fewer components (truncation)
  6937. // Other cases disallowed even if implicitly convertable in two steps (truncation+conversion).
  6938. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  6939. // splat: vector<[..], 1> -> matrix<[..], M, N>
  6940. Second = ICK_HLSLVector_Splat;
  6941. }
  6942. else if (TargetComponents == SourceInfo.uCols) {
  6943. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  6944. Second = ICK_HLSLVector_Conversion;
  6945. }
  6946. else if (1 == TargetComponents) {
  6947. // truncate to scalar: matrix<[..], 1, 1>
  6948. Second = ICK_HLSLVector_Truncation;
  6949. }
  6950. else if ((1 == TargetInfo.uRows || 1 == TargetInfo.uCols) &&
  6951. TargetComponents < SourceInfo.uCols) {
  6952. Second = ICK_HLSLVector_Truncation;
  6953. }
  6954. else {
  6955. // illegal: change in components without going to or from scalar equivalent
  6956. return false;
  6957. }
  6958. break;
  6959. }
  6960. case AR_TOBJ_MATRIX: {
  6961. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6962. if (1 == SourceComponents && TargetComponents != 1) {
  6963. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  6964. Second = ICK_HLSLVector_Splat;
  6965. }
  6966. else if (TargetComponents == 1) {
  6967. Second = ICK_HLSLVector_Truncation;
  6968. }
  6969. else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  6970. return false;
  6971. }
  6972. else if (TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  6973. Second = ICK_HLSLVector_Truncation;
  6974. }
  6975. else {
  6976. Second = ICK_Identity;
  6977. }
  6978. break;
  6979. }
  6980. default:
  6981. return false;
  6982. }
  6983. break;
  6984. }
  6985. case AR_TOBJ_STRING:
  6986. if (SourceInfo.ShapeKind == AR_TOBJ_STRING) {
  6987. Second = ICK_Identity;
  6988. break;
  6989. }
  6990. else {
  6991. return false;
  6992. }
  6993. default:
  6994. return false;
  6995. }
  6996. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  6997. {
  6998. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  6999. }
  7000. return true;
  7001. }
  7002. static bool ConvertComponent(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7003. ImplicitConversionKind &ComponentConversion,
  7004. TYPE_CONVERSION_REMARKS &Remarks) {
  7005. // Conversion to/from unknown types not supported.
  7006. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  7007. SourceInfo.EltKind == AR_BASIC_UNKNOWN) {
  7008. return false;
  7009. }
  7010. bool precisionLoss = false;
  7011. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  7012. GET_BASIC_BITS(TargetInfo.EltKind) <
  7013. GET_BASIC_BITS(SourceInfo.EltKind))
  7014. {
  7015. precisionLoss = true;
  7016. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  7017. }
  7018. // enum -> enum not allowed
  7019. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  7020. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  7021. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  7022. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  7023. return false;
  7024. }
  7025. if (SourceInfo.EltKind != TargetInfo.EltKind)
  7026. {
  7027. if (IS_BASIC_BOOL(TargetInfo.EltKind))
  7028. {
  7029. ComponentConversion = ICK_Boolean_Conversion;
  7030. }
  7031. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  7032. {
  7033. // conversion to enum type not allowed
  7034. return false;
  7035. }
  7036. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  7037. {
  7038. // enum -> int/float
  7039. ComponentConversion = ICK_Integral_Conversion;
  7040. }
  7041. else if (TargetInfo.EltKind == AR_OBJECT_STRING)
  7042. {
  7043. if (SourceInfo.EltKind == AR_OBJECT_STRING_LITERAL) {
  7044. ComponentConversion = ICK_Array_To_Pointer;
  7045. }
  7046. else
  7047. {
  7048. return false;
  7049. }
  7050. }
  7051. else
  7052. {
  7053. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  7054. if (IS_BASIC_AINT(SourceInfo.EltKind))
  7055. {
  7056. if (targetIsInt)
  7057. {
  7058. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  7059. }
  7060. else
  7061. {
  7062. ComponentConversion = ICK_Floating_Integral;
  7063. }
  7064. }
  7065. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  7066. {
  7067. if (targetIsInt)
  7068. {
  7069. ComponentConversion = ICK_Floating_Integral;
  7070. }
  7071. else
  7072. {
  7073. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  7074. }
  7075. }
  7076. else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  7077. if (targetIsInt)
  7078. ComponentConversion = ICK_Integral_Conversion;
  7079. else
  7080. ComponentConversion = ICK_Floating_Integral;
  7081. }
  7082. }
  7083. }
  7084. return true;
  7085. }
  7086. _Use_decl_annotations_
  7087. bool HLSLExternalSource::CanConvert(
  7088. SourceLocation loc,
  7089. Expr* sourceExpr,
  7090. QualType target,
  7091. bool explicitConversion,
  7092. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  7093. _Inout_opt_ StandardConversionSequence* standard)
  7094. {
  7095. UINT uTSize, uSSize;
  7096. DXASSERT_NOMSG(sourceExpr != nullptr);
  7097. DXASSERT_NOMSG(!target.isNull());
  7098. // Implements the semantics of ArType::CanConvertTo.
  7099. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  7100. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  7101. QualType source = sourceExpr->getType();
  7102. // Cannot cast function type.
  7103. if (source->isFunctionType())
  7104. return false;
  7105. // Convert to an r-value to begin with.
  7106. bool needsLValueToRValue = sourceExpr->isLValue() &&
  7107. !target->isLValueReferenceType() &&
  7108. IsConversionToLessOrEqualElements(source, target, explicitConversion);
  7109. bool targetRef = target->isReferenceType();
  7110. // Initialize the output standard sequence if available.
  7111. if (standard != nullptr) {
  7112. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  7113. standard->setAsIdentityConversion();
  7114. if (needsLValueToRValue) {
  7115. standard->First = ICK_Lvalue_To_Rvalue;
  7116. }
  7117. standard->setFromType(source);
  7118. standard->setAllToTypes(target);
  7119. }
  7120. source = GetStructuralForm(source);
  7121. target = GetStructuralForm(target);
  7122. // Temporary conversion kind tracking which will be used/fixed up at the end
  7123. ImplicitConversionKind Second = ICK_Identity;
  7124. ImplicitConversionKind ComponentConversion = ICK_Identity;
  7125. // Identical types require no conversion.
  7126. if (source == target) {
  7127. Remarks = TYPE_CONVERSION_IDENTICAL;
  7128. goto lSuccess;
  7129. }
  7130. // Trivial cases for void.
  7131. bool allowed;
  7132. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  7133. if (allowed) {
  7134. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  7135. goto lSuccess;
  7136. }
  7137. else {
  7138. return false;
  7139. }
  7140. }
  7141. ArTypeInfo TargetInfo, SourceInfo;
  7142. CollectInfo(target, &TargetInfo);
  7143. CollectInfo(source, &SourceInfo);
  7144. uTSize = TargetInfo.uTotalElts;
  7145. uSSize = SourceInfo.uTotalElts;
  7146. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  7147. // are we missing cases?
  7148. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  7149. return false;
  7150. }
  7151. // Structure cast.
  7152. if (TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY ||
  7153. SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY) {
  7154. if (!explicitConversion && TargetInfo.ShapeKind != SourceInfo.ShapeKind)
  7155. {
  7156. return false;
  7157. }
  7158. const RecordType *targetRT = target->getAsStructureType();
  7159. if (!targetRT)
  7160. targetRT = dyn_cast<RecordType>(target);
  7161. const RecordType *sourceRT = source->getAsStructureType();
  7162. if (!sourceRT)
  7163. sourceRT = dyn_cast<RecordType>(source);
  7164. if (targetRT && sourceRT) {
  7165. RecordDecl *targetRD = targetRT->getDecl();
  7166. RecordDecl *sourceRD = sourceRT->getDecl();
  7167. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  7168. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  7169. if (targetCXXRD && sourceCXXRD) {
  7170. if (targetRD == sourceRD) {
  7171. Second = ICK_Flat_Conversion;
  7172. goto lSuccess;
  7173. }
  7174. if (sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  7175. Second = ICK_HLSL_Derived_To_Base;
  7176. goto lSuccess;
  7177. }
  7178. } else {
  7179. if (targetRD == sourceRD) {
  7180. Second = ICK_Flat_Conversion;
  7181. goto lSuccess;
  7182. }
  7183. }
  7184. }
  7185. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  7186. BuiltinType::Kind kind = BT->getKind();
  7187. switch (kind) {
  7188. case BuiltinType::Kind::UInt:
  7189. case BuiltinType::Kind::Int:
  7190. case BuiltinType::Kind::Float:
  7191. case BuiltinType::Kind::LitFloat:
  7192. case BuiltinType::Kind::LitInt:
  7193. if (explicitConversion) {
  7194. Second = ICK_Flat_Conversion;
  7195. goto lSuccess;
  7196. }
  7197. break;
  7198. default:
  7199. // Only flat conversion kinds are relevant.
  7200. break;
  7201. }
  7202. }
  7203. FlattenedTypeIterator::ComparisonResult result =
  7204. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  7205. if (!result.CanConvertElements) {
  7206. return false;
  7207. }
  7208. // Only allow scalar to compound or array with explicit cast
  7209. if (result.IsConvertibleAndLeftLonger()) {
  7210. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  7211. return false;
  7212. }
  7213. }
  7214. // Assignment is valid if elements are exactly the same in type and size; if
  7215. // an explicit conversion is being done, we accept converted elements and a
  7216. // longer right-hand sequence.
  7217. if (!explicitConversion &&
  7218. (!result.AreElementsEqual || result.IsRightLonger()))
  7219. {
  7220. return false;
  7221. }
  7222. Second = ICK_Flat_Conversion;
  7223. goto lSuccess;
  7224. }
  7225. // Convert scalar/vector/matrix dimensions
  7226. if (!ConvertDimensions(TargetInfo, SourceInfo, Second, Remarks))
  7227. return false;
  7228. // Convert component type
  7229. if (!ConvertComponent(TargetInfo, SourceInfo, ComponentConversion, Remarks))
  7230. return false;
  7231. lSuccess:
  7232. if (standard)
  7233. {
  7234. if (sourceExpr->isLValue())
  7235. {
  7236. if (needsLValueToRValue) {
  7237. // We don't need LValueToRValue cast before casting a derived object
  7238. // to its base.
  7239. if (Second == ICK_HLSL_Derived_To_Base) {
  7240. standard->First = ICK_Identity;
  7241. } else {
  7242. standard->First = ICK_Lvalue_To_Rvalue;
  7243. }
  7244. } else {
  7245. switch (Second)
  7246. {
  7247. case ICK_NoReturn_Adjustment:
  7248. case ICK_Vector_Conversion:
  7249. case ICK_Vector_Splat:
  7250. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  7251. case ICK_Flat_Conversion:
  7252. case ICK_HLSLVector_Splat:
  7253. standard->First = ICK_Lvalue_To_Rvalue;
  7254. break;
  7255. default:
  7256. // Only flat and splat conversions handled.
  7257. break;
  7258. }
  7259. switch (ComponentConversion)
  7260. {
  7261. case ICK_Integral_Promotion:
  7262. case ICK_Integral_Conversion:
  7263. case ICK_Floating_Promotion:
  7264. case ICK_Floating_Conversion:
  7265. case ICK_Floating_Integral:
  7266. case ICK_Boolean_Conversion:
  7267. standard->First = ICK_Lvalue_To_Rvalue;
  7268. break;
  7269. case ICK_Array_To_Pointer:
  7270. standard->First = ICK_Array_To_Pointer;
  7271. break;
  7272. default:
  7273. // Only potential assignments above covered.
  7274. break;
  7275. }
  7276. }
  7277. }
  7278. // Finally fix up the cases for scalar->scalar component conversion, and
  7279. // identity vector/matrix component conversion
  7280. if (ICK_Identity != ComponentConversion) {
  7281. if (Second == ICK_Identity) {
  7282. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  7283. // Scalar to scalar type conversion, use normal mechanism (Second)
  7284. Second = ComponentConversion;
  7285. ComponentConversion = ICK_Identity;
  7286. }
  7287. else if (TargetInfo.ShapeKind != AR_TOBJ_STRING) {
  7288. // vector or matrix dimensions are not being changed, but component type
  7289. // is being converted, so change Second to signal the conversion
  7290. Second = ICK_HLSLVector_Conversion;
  7291. }
  7292. }
  7293. }
  7294. standard->Second = Second;
  7295. standard->ComponentConversion = ComponentConversion;
  7296. // For conversion which change to RValue but targeting reference type
  7297. // Hold the conversion to codeGen
  7298. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  7299. standard->First = ICK_Identity;
  7300. standard->Second = ICK_Identity;
  7301. }
  7302. }
  7303. AssignOpt(Remarks, remarks);
  7304. return true;
  7305. }
  7306. bool HLSLExternalSource::ValidateTypeRequirements(
  7307. SourceLocation loc,
  7308. ArBasicKind elementKind,
  7309. ArTypeObjectKind objectKind,
  7310. bool requiresIntegrals,
  7311. bool requiresNumerics)
  7312. {
  7313. if (requiresIntegrals || requiresNumerics)
  7314. {
  7315. if (!IsObjectKindPrimitiveAggregate(objectKind))
  7316. {
  7317. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  7318. return false;
  7319. }
  7320. }
  7321. if (requiresIntegrals)
  7322. {
  7323. if (!IsBasicKindIntegral(elementKind))
  7324. {
  7325. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  7326. return false;
  7327. }
  7328. }
  7329. else if (requiresNumerics)
  7330. {
  7331. if (!IsBasicKindNumeric(elementKind))
  7332. {
  7333. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  7334. return false;
  7335. }
  7336. }
  7337. return true;
  7338. }
  7339. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  7340. {
  7341. bool isValid = true;
  7342. if (IsBuiltInObjectType(type)) {
  7343. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  7344. isValid = false;
  7345. }
  7346. if (kind == AR_TOBJ_COMPOUND) {
  7347. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  7348. isValid = false;
  7349. }
  7350. return isValid;
  7351. }
  7352. HRESULT HLSLExternalSource::CombineDimensions(
  7353. QualType leftType, QualType rightType, QualType *resultType,
  7354. ImplicitConversionKind &convKind, TYPE_CONVERSION_REMARKS &Remarks)
  7355. {
  7356. ArTypeInfo leftInfo, rightInfo;
  7357. CollectInfo(leftType, &leftInfo);
  7358. CollectInfo(rightType, &rightInfo);
  7359. // Prefer larger, or left if same.
  7360. if (leftInfo.uTotalElts >= rightInfo.uTotalElts) {
  7361. if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7362. *resultType = leftType;
  7363. else if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7364. *resultType = rightType;
  7365. else
  7366. return E_FAIL;
  7367. } else {
  7368. if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7369. *resultType = rightType;
  7370. else if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7371. *resultType = leftType;
  7372. else
  7373. return E_FAIL;
  7374. }
  7375. return S_OK;
  7376. }
  7377. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  7378. /// <param name="OpLoc">Source location for operator.</param>
  7379. /// <param name="Opc">Kind of binary operator.</param>
  7380. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  7381. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  7382. /// <param name="ResultTy">Result type for operator expression.</param>
  7383. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  7384. /// <param name="CompResultTy">Type of computation result.</param>
  7385. void HLSLExternalSource::CheckBinOpForHLSL(
  7386. SourceLocation OpLoc,
  7387. BinaryOperatorKind Opc,
  7388. ExprResult& LHS,
  7389. ExprResult& RHS,
  7390. QualType& ResultTy,
  7391. QualType& CompLHSTy,
  7392. QualType& CompResultTy)
  7393. {
  7394. // At the start, none of the output types should be valid.
  7395. DXASSERT_NOMSG(ResultTy.isNull());
  7396. DXASSERT_NOMSG(CompLHSTy.isNull());
  7397. DXASSERT_NOMSG(CompResultTy.isNull());
  7398. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7399. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7400. // If either expression is invalid to begin with, propagate that.
  7401. if (LHS.isInvalid() || RHS.isInvalid()) {
  7402. return;
  7403. }
  7404. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  7405. // Handle Assign and Comma operators and return
  7406. switch (Opc)
  7407. {
  7408. case BO_AddAssign:
  7409. case BO_AndAssign:
  7410. case BO_DivAssign:
  7411. case BO_MulAssign:
  7412. case BO_RemAssign:
  7413. case BO_ShlAssign:
  7414. case BO_ShrAssign:
  7415. case BO_SubAssign:
  7416. case BO_OrAssign:
  7417. case BO_XorAssign: {
  7418. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  7419. Sema & S);
  7420. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7421. return;
  7422. }
  7423. } break;
  7424. case BO_Assign: {
  7425. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7426. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7427. return;
  7428. }
  7429. bool complained = false;
  7430. ResultTy = LHS.get()->getType();
  7431. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  7432. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  7433. Sema::AssignmentAction::AA_Assigning, &complained)) {
  7434. return;
  7435. }
  7436. StandardConversionSequence standard;
  7437. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  7438. ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7439. return;
  7440. }
  7441. if (RHS.get()->isLValue()) {
  7442. standard.First = ICK_Lvalue_To_Rvalue;
  7443. }
  7444. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  7445. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  7446. return;
  7447. }
  7448. break;
  7449. case BO_Comma:
  7450. // C performs conversions, C++ doesn't but still checks for type completeness.
  7451. // There are also diagnostics for improper comma use.
  7452. // In the HLSL case these cases don't apply or simply aren't surfaced.
  7453. ResultTy = RHS.get()->getType();
  7454. return;
  7455. default:
  7456. // Only assign and comma operations handled.
  7457. break;
  7458. }
  7459. // Leave this diagnostic for last to emulate fxc behavior.
  7460. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  7461. bool unsupportedBoolLvalue = isCompoundAssignment &&
  7462. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7463. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7464. // Turn operand inputs into r-values.
  7465. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7466. if (!isCompoundAssignment) {
  7467. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7468. }
  7469. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7470. if (LHS.isInvalid() || RHS.isInvalid()) {
  7471. return;
  7472. }
  7473. // Gather type info
  7474. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7475. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7476. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7477. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7478. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7479. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7480. // Validate type requirements
  7481. {
  7482. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  7483. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  7484. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  7485. return;
  7486. }
  7487. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  7488. return;
  7489. }
  7490. }
  7491. if (unsupportedBoolLvalue) {
  7492. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7493. return;
  7494. }
  7495. // We don't support binary operators on built-in object types other than assignment or commas.
  7496. {
  7497. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  7498. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  7499. bool isValid;
  7500. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  7501. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  7502. isValid = false;
  7503. }
  7504. if (!isValid) {
  7505. return;
  7506. }
  7507. }
  7508. // We don't support equality comparisons on arrays.
  7509. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  7510. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  7511. return;
  7512. }
  7513. // Combine element types for computation.
  7514. ArBasicKind resultElementKind = leftElementKind;
  7515. {
  7516. if (BinaryOperatorKindIsLogical(Opc)) {
  7517. resultElementKind = AR_BASIC_BOOL;
  7518. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  7519. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  7520. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7521. return;
  7522. }
  7523. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  7524. (resultElementKind == AR_BASIC_LITERAL_INT ||
  7525. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  7526. rightElementKind != AR_BASIC_LITERAL_INT &&
  7527. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  7528. // For case like 1<<x.
  7529. resultElementKind = AR_BASIC_UINT32;
  7530. } else if (resultElementKind == AR_BASIC_BOOL &&
  7531. BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7532. resultElementKind = AR_BASIC_INT32;
  7533. }
  7534. // The following combines the selected/combined element kind above with
  7535. // the dimensions that are legal to implicitly cast. This means that
  7536. // element kind may be taken from one side and the dimensions from the
  7537. // other.
  7538. if (!isCompoundAssignment) {
  7539. // Legal dimension combinations are identical, splat, and truncation.
  7540. // ResultTy will be set to whichever type can be converted to, if legal,
  7541. // with preference for leftType if both are possible.
  7542. if (FAILED(CombineDimensions(LHS.get()->getType(), RHS.get()->getType(), &ResultTy))) {
  7543. // Just choose leftType, and allow ValidateCast to catch this later
  7544. ResultTy = LHS.get()->getType();
  7545. }
  7546. } else {
  7547. ResultTy = LHS.get()->getType();
  7548. }
  7549. // Here, element kind is combined with dimensions for computation type, if different.
  7550. if (resultElementKind != GetTypeElementKind(ResultTy)) {
  7551. UINT rowCount, colCount;
  7552. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7553. ResultTy = NewSimpleAggregateType(GetTypeObjectKind(ResultTy), resultElementKind, 0, rowCount, colCount);
  7554. }
  7555. }
  7556. bool bFailedFirstRHSCast = false;
  7557. // Perform necessary conversion sequences for LHS and RHS
  7558. if (RHS.get()->getType() != ResultTy) {
  7559. StandardConversionSequence standard;
  7560. // Suppress type narrowing or truncation warnings for RHS on bitwise shift, since we only care about the LHS type.
  7561. bool bSuppressWarnings = BinaryOperatorKindIsBitwiseShift(Opc);
  7562. // Suppress errors on compound assignment, since we will vaildate the cast to the final type later.
  7563. bool bSuppressErrors = isCompoundAssignment;
  7564. // If compound assignment, suppress errors until later, but report warning (vector truncation/type narrowing) here.
  7565. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, bSuppressWarnings, bSuppressErrors, &standard)) {
  7566. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7567. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7568. } else if (!isCompoundAssignment) {
  7569. // If compound assignment, validate cast from RHS directly to LHS later, otherwise, fail here.
  7570. ResultTy = QualType();
  7571. return;
  7572. } else {
  7573. bFailedFirstRHSCast = true;
  7574. }
  7575. }
  7576. if (isCompoundAssignment) {
  7577. CompResultTy = ResultTy;
  7578. CompLHSTy = CompResultTy;
  7579. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  7580. // then converts to the result type and then assigns.
  7581. //
  7582. // So int + float promotes the int to float, does a floating-point addition,
  7583. // then the result becomes and int and is assigned.
  7584. ResultTy = LHSTypeAsPossibleLValue;
  7585. // Validate remainder of cast from computation type to final result type
  7586. StandardConversionSequence standard;
  7587. if (!ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7588. ResultTy = QualType();
  7589. return;
  7590. }
  7591. DXASSERT_LOCALVAR(bFailedFirstRHSCast, !bFailedFirstRHSCast,
  7592. "otherwise, hit compound assign case that failed RHS -> CompResultTy cast, but succeeded RHS -> LHS cast.");
  7593. } else if (LHS.get()->getType() != ResultTy) {
  7594. StandardConversionSequence standard;
  7595. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7596. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7597. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7598. } else {
  7599. ResultTy = QualType();
  7600. return;
  7601. }
  7602. }
  7603. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  7604. {
  7605. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  7606. // Return bool vector for vector types.
  7607. if (IsVectorType(m_sema, ResultTy)) {
  7608. UINT rowCount, colCount;
  7609. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7610. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  7611. } else if (IsMatrixType(m_sema, ResultTy)) {
  7612. UINT rowCount, colCount;
  7613. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7614. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  7615. } else
  7616. ResultTy = m_context->BoolTy.withConst();
  7617. }
  7618. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  7619. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  7620. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  7621. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  7622. return;
  7623. }
  7624. }
  7625. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  7626. if (resultElementKind == AR_BASIC_FLOAT64) {
  7627. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  7628. return;
  7629. }
  7630. }
  7631. }
  7632. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  7633. /// <param name="OpLoc">Source location for operator.</param>
  7634. /// <param name="Opc">Kind of operator.</param>
  7635. /// <param name="InputExpr">Input expression to the operator.</param>
  7636. /// <param name="VK">Value kind for resulting expression.</param>
  7637. /// <param name="OK">Object kind for resulting expression.</param>
  7638. /// <returns>The result type for the expression.</returns>
  7639. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  7640. SourceLocation OpLoc,
  7641. UnaryOperatorKind Opc,
  7642. ExprResult& InputExpr,
  7643. ExprValueKind& VK,
  7644. ExprObjectKind& OK)
  7645. {
  7646. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  7647. if (InputExpr.isInvalid())
  7648. return QualType();
  7649. // Reject unsupported operators * and &
  7650. switch (Opc) {
  7651. case UO_AddrOf:
  7652. case UO_Deref:
  7653. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  7654. return QualType();
  7655. default:
  7656. // Only * and & covered.
  7657. break;
  7658. }
  7659. Expr* expr = InputExpr.get();
  7660. if (expr->isTypeDependent())
  7661. return m_context->DependentTy;
  7662. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  7663. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  7664. if (elementKind == AR_BASIC_ENUM) {
  7665. bool isInc = IsIncrementOp(Opc);
  7666. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  7667. return QualType();
  7668. }
  7669. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7670. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  7671. return QualType();
  7672. } else {
  7673. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  7674. if (InputExpr.isInvalid()) return QualType();
  7675. }
  7676. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  7677. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7678. return QualType();
  7679. }
  7680. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7681. InputExpr = PromoteToIntIfBool(InputExpr);
  7682. expr = InputExpr.get();
  7683. elementKind = GetTypeElementKind(expr->getType());
  7684. }
  7685. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  7686. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  7687. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  7688. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  7689. return QualType();
  7690. }
  7691. if (Opc == UnaryOperatorKind::UO_Minus) {
  7692. if (IS_BASIC_UINT(Opc)) {
  7693. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  7694. }
  7695. }
  7696. // By default, the result type is the operand type.
  7697. // Logical not however should cast to a bool.
  7698. QualType resultType = expr->getType();
  7699. if (Opc == UnaryOperatorKind::UO_LNot) {
  7700. UINT rowCount, colCount;
  7701. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  7702. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  7703. StandardConversionSequence standard;
  7704. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  7705. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  7706. return QualType();
  7707. }
  7708. // Cast argument.
  7709. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7710. if (result.isUsable()) {
  7711. InputExpr = result.get();
  7712. }
  7713. }
  7714. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  7715. if (isPrefix) {
  7716. VK = VK_LValue;
  7717. return resultType;
  7718. }
  7719. else {
  7720. VK = VK_RValue;
  7721. return resultType.getUnqualifiedType();
  7722. }
  7723. }
  7724. clang::QualType HLSLExternalSource::CheckVectorConditional(
  7725. _In_ ExprResult &Cond,
  7726. _In_ ExprResult &LHS,
  7727. _In_ ExprResult &RHS,
  7728. _In_ SourceLocation QuestionLoc)
  7729. {
  7730. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  7731. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7732. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7733. // If either expression is invalid to begin with, propagate that.
  7734. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  7735. return QualType();
  7736. }
  7737. // Gather type info
  7738. QualType condType = GetStructuralForm(Cond.get()->getType());
  7739. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7740. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7741. ArBasicKind condElementKind = GetTypeElementKind(condType);
  7742. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7743. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7744. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  7745. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7746. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7747. QualType ResultTy = leftType;
  7748. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  7749. if (!condIsSimple) {
  7750. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  7751. return QualType();
  7752. }
  7753. UINT rowCountCond, colCountCond;
  7754. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  7755. bool leftIsSimple =
  7756. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  7757. leftObjectKind == AR_TOBJ_MATRIX;
  7758. bool rightIsSimple =
  7759. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  7760. rightObjectKind == AR_TOBJ_MATRIX;
  7761. if (!leftIsSimple || !rightIsSimple) {
  7762. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  7763. if (leftType == rightType) {
  7764. return leftType;
  7765. }
  7766. }
  7767. // NOTE: Limiting this operator to working only on basic numeric types.
  7768. // This is due to extremely limited (and even broken) support for any other case.
  7769. // In the future we may decide to support more cases.
  7770. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  7771. return QualType();
  7772. }
  7773. // Types should be only scalar, vector, or matrix after this point.
  7774. ArBasicKind resultElementKind = leftElementKind;
  7775. // Combine LHS and RHS element types for computation.
  7776. if (leftElementKind != rightElementKind) {
  7777. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  7778. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  7779. return QualType();
  7780. }
  7781. }
  7782. // Restore left/right type to original to avoid stripping attributed type or typedef type
  7783. leftType = LHS.get()->getType();
  7784. rightType = RHS.get()->getType();
  7785. // Combine LHS and RHS dimensions
  7786. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  7787. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  7788. return QualType();
  7789. }
  7790. UINT rowCount, colCount;
  7791. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7792. // If result is scalar, use condition dimensions.
  7793. // Otherwise, condition must either match or is scalar, then use result dimensions
  7794. if (rowCount * colCount == 1) {
  7795. rowCount = rowCountCond;
  7796. colCount = colCountCond;
  7797. }
  7798. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  7799. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  7800. return QualType();
  7801. }
  7802. // Here, element kind is combined with dimensions for result type.
  7803. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7804. // Cast condition to RValue
  7805. if (Cond.get()->isLValue())
  7806. Cond.set(CreateLValueToRValueCast(Cond.get()));
  7807. // Convert condition component type to bool, using result component dimensions
  7808. if (condElementKind != AR_BASIC_BOOL) {
  7809. QualType boolType = NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7810. StandardConversionSequence standard;
  7811. if (ValidateCast(SourceLocation(), Cond.get(), boolType, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7812. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7813. Cond = m_sema->PerformImplicitConversion(Cond.get(), boolType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7814. }
  7815. else {
  7816. return QualType();
  7817. }
  7818. }
  7819. // TODO: Is this correct? Does fxc support lvalue return here?
  7820. // Cast LHS/RHS to RValue
  7821. if (LHS.get()->isLValue())
  7822. LHS.set(CreateLValueToRValueCast(LHS.get()));
  7823. if (RHS.get()->isLValue())
  7824. RHS.set(CreateLValueToRValueCast(RHS.get()));
  7825. if (leftType != ResultTy) {
  7826. StandardConversionSequence standard;
  7827. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7828. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7829. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7830. }
  7831. else {
  7832. return QualType();
  7833. }
  7834. }
  7835. if (rightType != ResultTy) {
  7836. StandardConversionSequence standard;
  7837. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7838. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7839. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7840. }
  7841. else {
  7842. return QualType();
  7843. }
  7844. }
  7845. return ResultTy;
  7846. }
  7847. // Apply type specifier sign to the given QualType.
  7848. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  7849. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  7850. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  7851. _In_ clang::SourceLocation Loc) {
  7852. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  7853. return type;
  7854. }
  7855. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  7856. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  7857. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  7858. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  7859. return type;
  7860. }
  7861. // check if element type is unsigned and check if such vector exists
  7862. // If not create a new one, Make a QualType of the new kind
  7863. ArBasicKind elementKind = GetTypeElementKind(type);
  7864. // Only ints can have signed/unsigend ty
  7865. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  7866. return type;
  7867. }
  7868. else {
  7869. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  7870. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  7871. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  7872. // Get new vector types for a given TypeSpecifierSign.
  7873. if (objKind == AR_TOBJ_VECTOR) {
  7874. UINT colCount = GetHLSLVecSize(type);
  7875. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  7876. return m_context->getTypeDeclType(qts);
  7877. } else if (objKind == AR_TOBJ_MATRIX) {
  7878. UINT rowCount, colCount;
  7879. GetRowsAndCols(type, rowCount, colCount);
  7880. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  7881. return m_context->getTypeDeclType(qts);
  7882. } else {
  7883. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  7884. return m_scalarTypes[newScalarType];
  7885. }
  7886. }
  7887. }
  7888. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  7889. FunctionTemplateDecl *FunctionTemplate,
  7890. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7891. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7892. {
  7893. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  7894. // Get information about the function we have.
  7895. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  7896. DXASSERT(functionMethod != nullptr,
  7897. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  7898. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  7899. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  7900. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  7901. // Handle subscript overloads.
  7902. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  7903. {
  7904. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  7905. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  7906. if (!findResult.Found())
  7907. {
  7908. // This might be a nested type. Do a lookup on the parent.
  7909. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  7910. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  7911. {
  7912. return Sema::TemplateDeductionResult::TDK_Invalid;
  7913. }
  7914. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  7915. if (!findResult.Found())
  7916. {
  7917. return Sema::TemplateDeductionResult::TDK_Invalid;
  7918. }
  7919. DXASSERT(
  7920. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  7921. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  7922. "otherwise FindStructBasicType should have failed - no other types are allowed");
  7923. objectElement = GetFirstElementTypeFromDecl(
  7924. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  7925. }
  7926. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  7927. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7928. FunctionTemplate->getCanonicalDecl());
  7929. return Sema::TemplateDeductionResult::TDK_Success;
  7930. }
  7931. // Reject overload lookups that aren't identifier-based.
  7932. if (!FunctionTemplate->getDeclName().isIdentifier())
  7933. {
  7934. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7935. }
  7936. // Find the table of intrinsics based on the object type.
  7937. const HLSL_INTRINSIC* intrinsics;
  7938. size_t intrinsicCount;
  7939. const char* objectName;
  7940. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  7941. DXASSERT(intrinsics != nullptr,
  7942. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  7943. "or the parser let a user-defined template object through");
  7944. // Look for an intrinsic for which we can match arguments.
  7945. size_t argCount;
  7946. QualType argTypes[g_MaxIntrinsicParamCount + 1];
  7947. StringRef nameIdentifier = FunctionTemplate->getName();
  7948. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  7949. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  7950. while (cursor != end)
  7951. {
  7952. if (!MatchArguments(*cursor, objectElement, Args, argTypes, &argCount))
  7953. {
  7954. ++cursor;
  7955. continue;
  7956. }
  7957. // Currently only intrinsic we allow for explicit template arguments are
  7958. // for Load return types for ByteAddressBuffer/RWByteAddressBuffer
  7959. // TODO: handle template arguments for future intrinsics in a more natural way
  7960. // Check Explicit template arguments
  7961. UINT intrinsicOp = (*cursor)->Op;
  7962. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  7963. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  7964. bool IsBAB =
  7965. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  7966. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  7967. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  7968. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  7969. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  7970. bool isLegalTemplate = false;
  7971. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  7972. auto TemplateDiag =
  7973. !IsBABLoad
  7974. ? diag::err_hlsl_intrinsic_template_arg_unsupported
  7975. : !Is2018 ? diag::err_hlsl_intrinsic_template_arg_requires_2018
  7976. : diag::err_hlsl_intrinsic_template_arg_scalar_vector;
  7977. if (IsBABLoad && Is2018 && ExplicitTemplateArgs->size() == 1) {
  7978. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  7979. QualType explicitType = (*ExplicitTemplateArgs)[0].getArgument().getAsType();
  7980. ArTypeObjectKind explicitKind = GetTypeObjectKind(explicitType);
  7981. if (explicitKind == AR_TOBJ_BASIC || explicitKind == AR_TOBJ_VECTOR) {
  7982. isLegalTemplate = true;
  7983. argTypes[0] = explicitType;
  7984. }
  7985. }
  7986. if (!isLegalTemplate) {
  7987. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  7988. return Sema::TemplateDeductionResult::TDK_Invalid;
  7989. }
  7990. } else if (IsBABStore) {
  7991. // Prior to HLSL 2018, Store operation only stored scalar uint.
  7992. if (!Is2018) {
  7993. if (GetNumElements(argTypes[2]) != 1) {
  7994. getSema()->Diag(Args[1]->getLocStart(),
  7995. diag::err_ovl_no_viable_member_function_in_call)
  7996. << intrinsicName;
  7997. return Sema::TemplateDeductionResult::TDK_Invalid;
  7998. }
  7999. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  8000. 32, /*signed*/ false);
  8001. }
  8002. }
  8003. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes, argCount);
  8004. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8005. FunctionTemplate->getCanonicalDecl());
  8006. if (!IsValidateObjectElement(*cursor, objectElement)) {
  8007. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  8008. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  8009. }
  8010. return Sema::TemplateDeductionResult::TDK_Success;
  8011. }
  8012. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8013. }
  8014. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  8015. {
  8016. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  8017. }
  8018. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  8019. QualType DestType,
  8020. Sema::CheckedConversionKind CCK,
  8021. const SourceRange &OpRange, unsigned &msg,
  8022. CastKind &Kind, CXXCastPath &BasePath,
  8023. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  8024. _Inout_opt_ StandardConversionSequence* standard)
  8025. {
  8026. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  8027. bool explicitConversion
  8028. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  8029. bool suppressWarnings = explicitConversion || SuppressWarnings;
  8030. SourceLocation loc = OpRange.getBegin();
  8031. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  8032. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  8033. // so do this here until we figure out why this is needed.
  8034. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  8035. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  8036. }
  8037. return true;
  8038. }
  8039. // ValidateCast includes its own error messages.
  8040. msg = 0;
  8041. return false;
  8042. }
  8043. /// <summary>
  8044. /// Checks if a subscript index argument can be initialized from the given expression.
  8045. /// </summary>
  8046. /// <param name="SrcExpr">Source expression used as argument.</param>
  8047. /// <param name="DestType">Parameter type to initialize.</param>
  8048. /// <remarks>
  8049. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  8050. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  8051. /// </remarks>
  8052. ImplicitConversionSequence
  8053. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  8054. clang::QualType DestType) {
  8055. DXASSERT_NOMSG(SrcExpr != nullptr);
  8056. DXASSERT_NOMSG(!DestType.isNull());
  8057. unsigned int msg = 0;
  8058. CastKind kind;
  8059. CXXCastPath path;
  8060. ImplicitConversionSequence sequence;
  8061. sequence.setStandard();
  8062. ExprResult sourceExpr(SrcExpr);
  8063. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  8064. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8065. SrcExpr->getType(), DestType);
  8066. } else if (!TryStaticCastForHLSL(
  8067. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  8068. msg, kind, path, ListInitializationFalse,
  8069. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  8070. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8071. SrcExpr->getType(), DestType);
  8072. }
  8073. return sequence;
  8074. }
  8075. template <typename T>
  8076. static
  8077. bool IsValueInRange(T value, T minValue, T maxValue) {
  8078. return minValue <= value && value <= maxValue;
  8079. }
  8080. #define D3DX_16F_MAX 6.550400e+004 // max value
  8081. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  8082. static
  8083. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  8084. {
  8085. DXASSERT_NOMSG(minValue != nullptr);
  8086. DXASSERT_NOMSG(maxValue != nullptr);
  8087. switch (basicKind) {
  8088. case AR_BASIC_MIN10FLOAT:
  8089. case AR_BASIC_MIN16FLOAT:
  8090. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  8091. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8092. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  8093. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  8094. default:
  8095. // No other float types.
  8096. break;
  8097. }
  8098. DXASSERT(false, "unreachable");
  8099. *minValue = 0; *maxValue = 0;
  8100. return;
  8101. }
  8102. static
  8103. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  8104. {
  8105. DXASSERT_NOMSG(maxValue != nullptr);
  8106. switch (basicKind) {
  8107. case AR_BASIC_BOOL: *maxValue = 1; return;
  8108. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  8109. case AR_BASIC_MIN16UINT:
  8110. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  8111. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  8112. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  8113. default:
  8114. // No other unsigned int types.
  8115. break;
  8116. }
  8117. DXASSERT(false, "unreachable");
  8118. *maxValue = 0;
  8119. return;
  8120. }
  8121. static
  8122. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  8123. {
  8124. DXASSERT_NOMSG(minValue != nullptr);
  8125. DXASSERT_NOMSG(maxValue != nullptr);
  8126. switch (basicKind) {
  8127. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  8128. case AR_BASIC_MIN12INT:
  8129. case AR_BASIC_MIN16INT:
  8130. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  8131. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  8132. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  8133. default:
  8134. // No other signed int types.
  8135. break;
  8136. }
  8137. DXASSERT(false, "unreachable");
  8138. *minValue = 0; *maxValue = 0;
  8139. return;
  8140. }
  8141. static
  8142. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  8143. {
  8144. if (IS_BASIC_FLOAT(basicKind)) {
  8145. double val;
  8146. if (value.isInt()) {
  8147. val = value.getInt().getLimitedValue();
  8148. } else if (value.isFloat()) {
  8149. llvm::APFloat floatValue = value.getFloat();
  8150. if (!floatValue.isFinite()) {
  8151. return false;
  8152. }
  8153. llvm::APFloat valueFloat = value.getFloat();
  8154. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  8155. val = value.getFloat().convertToFloat();
  8156. }
  8157. else {
  8158. val = value.getFloat().convertToDouble();
  8159. }
  8160. } else {
  8161. return false;
  8162. }
  8163. double minValue, maxValue;
  8164. GetFloatLimits(basicKind, &minValue, &maxValue);
  8165. return IsValueInRange(val, minValue, maxValue);
  8166. }
  8167. else if (IS_BASIC_SINT(basicKind)) {
  8168. if (!value.isInt()) {
  8169. return false;
  8170. }
  8171. int64_t val = value.getInt().getSExtValue();
  8172. int64_t minValue, maxValue;
  8173. GetSignedLimits(basicKind, &minValue, &maxValue);
  8174. return IsValueInRange(val, minValue, maxValue);
  8175. }
  8176. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  8177. if (!value.isInt()) {
  8178. return false;
  8179. }
  8180. uint64_t val = value.getInt().getLimitedValue();
  8181. uint64_t maxValue;
  8182. GetUnsignedLimit(basicKind, &maxValue);
  8183. return IsValueInRange(val, (uint64_t)0, maxValue);
  8184. }
  8185. else {
  8186. return false;
  8187. }
  8188. }
  8189. static
  8190. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  8191. {
  8192. DXASSERT_NOMSG(!targetType.isNull());
  8193. DXASSERT_NOMSG(sourceExpr != nullptr);
  8194. Expr::EvalResult evalResult;
  8195. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  8196. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  8197. return IsValueInBasicRange(targetKind, evalResult.Val);
  8198. }
  8199. }
  8200. return false;
  8201. }
  8202. bool HLSLExternalSource::ValidateCast(
  8203. SourceLocation OpLoc,
  8204. _In_ Expr* sourceExpr,
  8205. QualType target,
  8206. bool explicitConversion,
  8207. bool suppressWarnings,
  8208. bool suppressErrors,
  8209. _Inout_opt_ StandardConversionSequence* standard)
  8210. {
  8211. DXASSERT_NOMSG(sourceExpr != nullptr);
  8212. if (OpLoc.isInvalid())
  8213. OpLoc = sourceExpr->getExprLoc();
  8214. QualType source = sourceExpr->getType();
  8215. TYPE_CONVERSION_REMARKS remarks;
  8216. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  8217. {
  8218. const bool IsOutputParameter = false;
  8219. //
  8220. // Check whether the lack of explicit-ness matters.
  8221. //
  8222. // Setting explicitForDiagnostics to true in that case will avoid the message
  8223. // saying anything about the implicit nature of the cast, when adding the
  8224. // explicit cast won't make a difference.
  8225. //
  8226. bool explicitForDiagnostics = explicitConversion;
  8227. if (explicitConversion == false)
  8228. {
  8229. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  8230. {
  8231. // Can't convert either way - implicit/explicit doesn't matter.
  8232. explicitForDiagnostics = true;
  8233. }
  8234. }
  8235. if (!suppressErrors)
  8236. {
  8237. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  8238. << explicitForDiagnostics << IsOutputParameter << source << target;
  8239. }
  8240. return false;
  8241. }
  8242. if (!suppressWarnings)
  8243. {
  8244. if (!explicitConversion)
  8245. {
  8246. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  8247. {
  8248. // This is a much more restricted version of the analysis does
  8249. // StandardConversionSequence::getNarrowingKind
  8250. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  8251. {
  8252. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  8253. }
  8254. }
  8255. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  8256. {
  8257. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  8258. }
  8259. }
  8260. }
  8261. return true;
  8262. }
  8263. ////////////////////////////////////////////////////////////////////////////////
  8264. // Functions exported from this translation unit. //
  8265. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  8266. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  8267. SourceLocation OpLoc,
  8268. UnaryOperatorKind Opc,
  8269. ExprResult& InputExpr,
  8270. ExprValueKind& VK,
  8271. ExprObjectKind& OK)
  8272. {
  8273. ExternalSemaSource* externalSource = self.getExternalSource();
  8274. if (externalSource == nullptr) {
  8275. return QualType();
  8276. }
  8277. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8278. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  8279. }
  8280. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  8281. void hlsl::CheckBinOpForHLSL(Sema& self,
  8282. SourceLocation OpLoc,
  8283. BinaryOperatorKind Opc,
  8284. ExprResult& LHS,
  8285. ExprResult& RHS,
  8286. QualType& ResultTy,
  8287. QualType& CompLHSTy,
  8288. QualType& CompResultTy)
  8289. {
  8290. ExternalSemaSource* externalSource = self.getExternalSource();
  8291. if (externalSource == nullptr) {
  8292. return;
  8293. }
  8294. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8295. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  8296. }
  8297. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  8298. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  8299. {
  8300. DXASSERT_NOMSG(Template != nullptr);
  8301. ExternalSemaSource* externalSource = self.getExternalSource();
  8302. if (externalSource == nullptr) {
  8303. return false;
  8304. }
  8305. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8306. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  8307. }
  8308. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  8309. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  8310. FunctionTemplateDecl *FunctionTemplate,
  8311. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8312. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8313. {
  8314. return HLSLExternalSource::FromSema(self)
  8315. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  8316. }
  8317. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  8318. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  8319. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  8320. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  8321. self->Diag(condExpr->getLocStart(),
  8322. diag::err_hlsl_control_flow_cond_not_scalar)
  8323. << StmtName;
  8324. return;
  8325. }
  8326. condExpr = IC->getSubExpr();
  8327. }
  8328. }
  8329. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  8330. {
  8331. // TODO: handle shorthand cases.
  8332. return left.size() == 0 || right.size() == 0 || left.equals(right);
  8333. }
  8334. void hlsl::DiagnosePackingOffset(
  8335. clang::Sema* self,
  8336. SourceLocation loc,
  8337. clang::QualType type,
  8338. int componentOffset)
  8339. {
  8340. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  8341. if (componentOffset > 0) {
  8342. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8343. ArBasicKind element = source->GetTypeElementKind(type);
  8344. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  8345. // Only perform some simple validation for now.
  8346. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  8347. int count = GetElementCount(type);
  8348. if (count > (4 - componentOffset)) {
  8349. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  8350. }
  8351. }
  8352. }
  8353. }
  8354. void hlsl::DiagnoseRegisterType(
  8355. clang::Sema* self,
  8356. clang::SourceLocation loc,
  8357. clang::QualType type,
  8358. char registerType)
  8359. {
  8360. // SPIRV Change Starts - skip the check if space-only for SPIR-V
  8361. if (self->getLangOpts().SPIRV && registerType == 'x')
  8362. return;
  8363. // SPIRV Change Ends
  8364. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8365. ArBasicKind element = source->GetTypeElementKind(type);
  8366. StringRef expected("none");
  8367. bool isValid = true;
  8368. bool isWarning = false;
  8369. switch (element)
  8370. {
  8371. case AR_BASIC_BOOL:
  8372. case AR_BASIC_LITERAL_FLOAT:
  8373. case AR_BASIC_FLOAT16:
  8374. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8375. case AR_BASIC_FLOAT32:
  8376. case AR_BASIC_FLOAT64:
  8377. case AR_BASIC_LITERAL_INT:
  8378. case AR_BASIC_INT8:
  8379. case AR_BASIC_UINT8:
  8380. case AR_BASIC_INT16:
  8381. case AR_BASIC_UINT16:
  8382. case AR_BASIC_INT32:
  8383. case AR_BASIC_UINT32:
  8384. case AR_BASIC_INT64:
  8385. case AR_BASIC_UINT64:
  8386. case AR_BASIC_MIN10FLOAT:
  8387. case AR_BASIC_MIN16FLOAT:
  8388. case AR_BASIC_MIN12INT:
  8389. case AR_BASIC_MIN16INT:
  8390. case AR_BASIC_MIN16UINT:
  8391. expected = "'b', 'c', or 'i'";
  8392. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i' ||
  8393. registerType == 'B' || registerType == 'C' || registerType == 'I';
  8394. break;
  8395. case AR_OBJECT_TEXTURE1D:
  8396. case AR_OBJECT_TEXTURE1D_ARRAY:
  8397. case AR_OBJECT_TEXTURE2D:
  8398. case AR_OBJECT_TEXTURE2D_ARRAY:
  8399. case AR_OBJECT_TEXTURE3D:
  8400. case AR_OBJECT_TEXTURECUBE:
  8401. case AR_OBJECT_TEXTURECUBE_ARRAY:
  8402. case AR_OBJECT_TEXTURE2DMS:
  8403. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  8404. expected = "'t' or 's'";
  8405. isValid = registerType == 't' || registerType == 's' ||
  8406. registerType == 'T' || registerType == 'S';
  8407. break;
  8408. case AR_OBJECT_SAMPLER:
  8409. case AR_OBJECT_SAMPLER1D:
  8410. case AR_OBJECT_SAMPLER2D:
  8411. case AR_OBJECT_SAMPLER3D:
  8412. case AR_OBJECT_SAMPLERCUBE:
  8413. case AR_OBJECT_SAMPLERCOMPARISON:
  8414. expected = "'s' or 't'";
  8415. isValid = registerType == 's' || registerType == 't' ||
  8416. registerType == 'S' || registerType == 'T';
  8417. break;
  8418. case AR_OBJECT_BUFFER:
  8419. expected = "'t'";
  8420. isValid = registerType == 't' || registerType == 'T';
  8421. break;
  8422. case AR_OBJECT_POINTSTREAM:
  8423. case AR_OBJECT_LINESTREAM:
  8424. case AR_OBJECT_TRIANGLESTREAM:
  8425. isValid = false;
  8426. isWarning = true;
  8427. break;
  8428. case AR_OBJECT_INPUTPATCH:
  8429. case AR_OBJECT_OUTPUTPATCH:
  8430. isValid = false;
  8431. isWarning = true;
  8432. break;
  8433. case AR_OBJECT_RWTEXTURE1D:
  8434. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  8435. case AR_OBJECT_RWTEXTURE2D:
  8436. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  8437. case AR_OBJECT_RWTEXTURE3D:
  8438. case AR_OBJECT_RWBUFFER:
  8439. expected = "'u'";
  8440. isValid = registerType == 'u' || registerType == 'U';
  8441. break;
  8442. case AR_OBJECT_BYTEADDRESS_BUFFER:
  8443. case AR_OBJECT_STRUCTURED_BUFFER:
  8444. expected = "'t'";
  8445. isValid = registerType == 't' || registerType == 'T';
  8446. break;
  8447. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  8448. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  8449. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  8450. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8451. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8452. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8453. expected = "'u'";
  8454. isValid = registerType == 'u' || registerType == 'U';
  8455. break;
  8456. case AR_OBJECT_CONSTANT_BUFFER:
  8457. expected = "'b'";
  8458. isValid = registerType == 'b' || registerType == 'B';
  8459. break;
  8460. case AR_OBJECT_TEXTURE_BUFFER:
  8461. expected = "'t'";
  8462. isValid = registerType == 't' || registerType == 'T';
  8463. break;
  8464. case AR_OBJECT_ROVBUFFER:
  8465. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  8466. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  8467. case AR_OBJECT_ROVTEXTURE1D:
  8468. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  8469. case AR_OBJECT_ROVTEXTURE2D:
  8470. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  8471. case AR_OBJECT_ROVTEXTURE3D:
  8472. expected = "'u'";
  8473. isValid = registerType == 'u' || registerType == 'U';
  8474. break;
  8475. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  8476. isWarning = true;
  8477. break; // So we don't care what you tried to bind it to
  8478. default: // Other types have no associated registers.
  8479. break;
  8480. }
  8481. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  8482. // a warning instead.
  8483. if (!isValid)
  8484. {
  8485. if (isWarning)
  8486. self->Diag(loc, diag::warn_hlsl_incorrect_bind_semantic) << expected;
  8487. else
  8488. self->Diag(loc, diag::err_hlsl_incorrect_bind_semantic) << expected;
  8489. }
  8490. }
  8491. struct NameLookup {
  8492. FunctionDecl *Found;
  8493. FunctionDecl *Other;
  8494. };
  8495. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  8496. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  8497. FunctionDecl *pFoundDecl = nullptr;
  8498. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  8499. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  8500. if (!pFnDecl) continue;
  8501. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  8502. if (pFoundDecl) {
  8503. return NameLookup{ pFoundDecl, pFnDecl };
  8504. }
  8505. pFoundDecl = pFnDecl;
  8506. }
  8507. return NameLookup{ pFoundDecl, nullptr };
  8508. }
  8509. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  8510. DXASSERT_NOMSG(self != nullptr);
  8511. // Don't bother with global validation if compilation has already failed.
  8512. if (self->getDiagnostics().hasErrorOccurred()) {
  8513. return;
  8514. }
  8515. // Don't check entry function for library.
  8516. if (self->getLangOpts().IsHLSLLibrary) {
  8517. // TODO: validate no recursion start from every function.
  8518. return;
  8519. }
  8520. // TODO: make these error 'real' errors rather than on-the-fly things
  8521. // Validate that the entry point is available.
  8522. DiagnosticsEngine &Diags = self->getDiagnostics();
  8523. FunctionDecl *pEntryPointDecl = nullptr;
  8524. FunctionDecl *pPatchFnDecl = nullptr;
  8525. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  8526. if (!EntryPointName.empty()) {
  8527. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  8528. if (NL.Found && NL.Other) {
  8529. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  8530. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  8531. // string, and so ambiguous points will produce an error earlier on.
  8532. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8533. "ambiguous entry point function");
  8534. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  8535. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  8536. return;
  8537. }
  8538. pEntryPointDecl = NL.Found;
  8539. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  8540. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8541. "missing entry point definition");
  8542. Diags.Report(id);
  8543. return;
  8544. }
  8545. }
  8546. // Validate that there is no recursion; start with the entry function.
  8547. // NOTE: the information gathered here could be used to bypass code generation
  8548. // on functions that are unreachable (as an early form of dead code elimination).
  8549. if (pEntryPointDecl) {
  8550. const auto *shaderModel =
  8551. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  8552. if (shaderModel->IsGS()) {
  8553. // Validate that GS has the maxvertexcount attribute
  8554. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  8555. self->Diag(pEntryPointDecl->getLocation(),
  8556. diag::err_hlsl_missing_maxvertexcount_attr);
  8557. return;
  8558. }
  8559. } else if (shaderModel->IsHS()) {
  8560. if (const HLSLPatchConstantFuncAttr *Attr =
  8561. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8562. NameLookup NL = GetSingleFunctionDeclByName(
  8563. self, Attr->getFunctionName(), /*checkPatch*/ true);
  8564. if (!NL.Found || !NL.Found->hasBody()) {
  8565. unsigned id =
  8566. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8567. "missing patch function definition");
  8568. Diags.Report(id);
  8569. return;
  8570. }
  8571. pPatchFnDecl = NL.Found;
  8572. } else {
  8573. self->Diag(pEntryPointDecl->getLocation(),
  8574. diag::err_hlsl_missing_patchconstantfunc_attr);
  8575. return;
  8576. }
  8577. }
  8578. hlsl::CallGraphWithRecurseGuard CG;
  8579. CG.BuildForEntry(pEntryPointDecl);
  8580. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  8581. if (pResult) {
  8582. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8583. "recursive functions not allowed");
  8584. Diags.Report(pResult->getSourceRange().getBegin(), id);
  8585. }
  8586. if (pPatchFnDecl) {
  8587. CG.BuildForEntry(pPatchFnDecl);
  8588. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  8589. if (pPatchFnDecl) {
  8590. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8591. "recursive functions not allowed (via patch function)");
  8592. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  8593. }
  8594. }
  8595. }
  8596. }
  8597. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  8598. Sema& S,
  8599. std::vector<hlsl::UnusualAnnotation *>& annotations)
  8600. {
  8601. bool packoffsetOverriddenReported = false;
  8602. auto && iter = annotations.begin();
  8603. auto && end = annotations.end();
  8604. for (; iter != end; ++iter) {
  8605. switch ((*iter)->getKind()) {
  8606. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8607. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  8608. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  8609. if (!packoffsetOverriddenReported) {
  8610. auto newIter = iter;
  8611. ++newIter;
  8612. while (newIter != end) {
  8613. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  8614. if (other != nullptr &&
  8615. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  8616. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  8617. packoffsetOverriddenReported = true;
  8618. break;
  8619. }
  8620. ++newIter;
  8621. }
  8622. }
  8623. break;
  8624. }
  8625. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8626. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  8627. // Check whether this will conflict with other register assignments of the same type.
  8628. auto newIter = iter;
  8629. ++newIter;
  8630. while (newIter != end) {
  8631. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  8632. // Same register bank and profile, but different number.
  8633. if (other != nullptr &&
  8634. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  8635. other->RegisterType == registerAssignment->RegisterType &&
  8636. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  8637. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  8638. // Obvious conflict - report it up front.
  8639. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  8640. }
  8641. ++newIter;
  8642. }
  8643. break;
  8644. }
  8645. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8646. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  8647. // No common validation to be performed.
  8648. break;
  8649. }
  8650. }
  8651. }
  8652. }
  8653. clang::OverloadingResult
  8654. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  8655. clang::OverloadCandidateSet &set,
  8656. clang::OverloadCandidateSet::iterator &Best) {
  8657. return HLSLExternalSource::FromSema(&S)
  8658. ->GetBestViableFunction(Loc, set, Best);
  8659. }
  8660. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  8661. const InitializedEntity &Entity,
  8662. const InitializationKind &Kind,
  8663. MultiExprArg Args,
  8664. bool TopLevelOfInitList,
  8665. InitializationSequence *initSequence) {
  8666. return HLSLExternalSource::FromSema(self)
  8667. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  8668. }
  8669. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  8670. const clang::InitListExpr *InitList) {
  8671. unsigned totalSize = 0;
  8672. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  8673. const clang::Expr *EltInit = InitList->getInit(i);
  8674. QualType EltInitTy = EltInit->getType();
  8675. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  8676. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  8677. } else {
  8678. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  8679. }
  8680. }
  8681. return totalSize;
  8682. }
  8683. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  8684. _In_ clang::Sema* sema,
  8685. _In_ const clang::InitListExpr *InitList,
  8686. _In_ const clang::QualType EltTy) {
  8687. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  8688. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  8689. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  8690. if (totalSize > 0 && (totalSize % eltSize)==0) {
  8691. return totalSize / eltSize;
  8692. } else {
  8693. return 0;
  8694. }
  8695. }
  8696. bool hlsl::IsConversionToLessOrEqualElements(
  8697. _In_ clang::Sema* self,
  8698. const clang::ExprResult& sourceExpr,
  8699. const clang::QualType& targetType,
  8700. bool explicitConversion)
  8701. {
  8702. return HLSLExternalSource::FromSema(self)
  8703. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  8704. }
  8705. bool hlsl::LookupMatrixMemberExprForHLSL(
  8706. Sema* self,
  8707. Expr& BaseExpr,
  8708. DeclarationName MemberName,
  8709. bool IsArrow,
  8710. SourceLocation OpLoc,
  8711. SourceLocation MemberLoc,
  8712. ExprResult* result)
  8713. {
  8714. return HLSLExternalSource::FromSema(self)
  8715. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8716. }
  8717. bool hlsl::LookupVectorMemberExprForHLSL(
  8718. Sema* self,
  8719. Expr& BaseExpr,
  8720. DeclarationName MemberName,
  8721. bool IsArrow,
  8722. SourceLocation OpLoc,
  8723. SourceLocation MemberLoc,
  8724. ExprResult* result)
  8725. {
  8726. return HLSLExternalSource::FromSema(self)
  8727. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8728. }
  8729. bool hlsl::LookupArrayMemberExprForHLSL(
  8730. Sema* self,
  8731. Expr& BaseExpr,
  8732. DeclarationName MemberName,
  8733. bool IsArrow,
  8734. SourceLocation OpLoc,
  8735. SourceLocation MemberLoc,
  8736. ExprResult* result)
  8737. {
  8738. return HLSLExternalSource::FromSema(self)
  8739. ->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8740. }
  8741. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  8742. _In_ clang::Sema* self,
  8743. _In_ clang::Expr* E)
  8744. {
  8745. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  8746. }
  8747. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  8748. QualType DestType,
  8749. Sema::CheckedConversionKind CCK,
  8750. const SourceRange &OpRange, unsigned &msg,
  8751. CastKind &Kind, CXXCastPath &BasePath,
  8752. bool ListInitialization,
  8753. bool SuppressDiagnostics,
  8754. _Inout_opt_ StandardConversionSequence* standard)
  8755. {
  8756. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  8757. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  8758. SuppressDiagnostics, SuppressDiagnostics, standard);
  8759. }
  8760. clang::ExprResult hlsl::PerformHLSLConversion(
  8761. _In_ clang::Sema* self,
  8762. _In_ clang::Expr* From,
  8763. _In_ clang::QualType targetType,
  8764. _In_ const clang::StandardConversionSequence &SCS,
  8765. _In_ clang::Sema::CheckedConversionKind CCK)
  8766. {
  8767. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  8768. }
  8769. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  8770. _In_ clang::Sema* self,
  8771. _In_ clang::Expr* SrcExpr,
  8772. clang::QualType DestType)
  8773. {
  8774. return HLSLExternalSource::FromSema(self)
  8775. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  8776. }
  8777. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  8778. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  8779. {
  8780. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  8781. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  8782. if (hlslSource->Initialize(context)) {
  8783. context.setExternalSource(externalSource);
  8784. }
  8785. }
  8786. ////////////////////////////////////////////////////////////////////////////////
  8787. // FlattenedTypeIterator implementation //
  8788. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  8789. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  8790. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8791. {
  8792. if (pushTrackerForType(type, nullptr)) {
  8793. considerLeaf();
  8794. }
  8795. }
  8796. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  8797. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  8798. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8799. {
  8800. if (!args.empty()) {
  8801. MultiExprArg::iterator ii = args.begin();
  8802. MultiExprArg::iterator ie = args.end();
  8803. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  8804. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8805. if (!considerLeaf()) {
  8806. m_typeTrackers.clear();
  8807. }
  8808. }
  8809. }
  8810. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  8811. QualType FlattenedTypeIterator::getCurrentElement() const
  8812. {
  8813. return m_typeTrackers.back().Type;
  8814. }
  8815. /// <summary>Get the number of repeated current elements.</summary>
  8816. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  8817. {
  8818. const FlattenedTypeTracker& back = m_typeTrackers.back();
  8819. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  8820. }
  8821. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  8822. bool FlattenedTypeIterator::hasCurrentElement() const
  8823. {
  8824. return m_typeTrackers.size() > 0;
  8825. }
  8826. /// <summary>Consumes count elements on this iterator.</summary>
  8827. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  8828. {
  8829. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8830. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  8831. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8832. if (tracker.IterKind == FK_IncompleteArray)
  8833. {
  8834. tracker.Count += count;
  8835. m_springLoaded = true;
  8836. }
  8837. else
  8838. {
  8839. tracker.Count -= count;
  8840. m_springLoaded = false;
  8841. if (m_typeTrackers.back().Count == 0)
  8842. {
  8843. advanceLeafTracker();
  8844. }
  8845. }
  8846. }
  8847. unsigned int FlattenedTypeIterator::countRemaining()
  8848. {
  8849. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  8850. size_t result = 0;
  8851. while (hasCurrentElement() && !m_springLoaded)
  8852. {
  8853. size_t pending = getCurrentElementSize();
  8854. result += pending;
  8855. advanceCurrentElement(pending);
  8856. }
  8857. return result;
  8858. }
  8859. void FlattenedTypeIterator::advanceLeafTracker()
  8860. {
  8861. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8862. for (;;)
  8863. {
  8864. consumeLeaf();
  8865. if (m_typeTrackers.empty()) {
  8866. return;
  8867. }
  8868. if (considerLeaf()) {
  8869. return;
  8870. }
  8871. }
  8872. }
  8873. bool FlattenedTypeIterator::considerLeaf()
  8874. {
  8875. if (m_typeTrackers.empty()) {
  8876. return false;
  8877. }
  8878. m_typeDepth++;
  8879. if (m_typeDepth > MaxTypeDepth) {
  8880. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  8881. m_typeTrackers.clear();
  8882. m_typeDepth--;
  8883. return false;
  8884. }
  8885. bool result = false;
  8886. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8887. tracker.IsConsidered = true;
  8888. switch (tracker.IterKind) {
  8889. case FlattenedIterKind::FK_Expressions:
  8890. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  8891. result = considerLeaf();
  8892. }
  8893. break;
  8894. case FlattenedIterKind::FK_Fields:
  8895. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  8896. result = considerLeaf();
  8897. } else {
  8898. // Pop empty struct.
  8899. m_typeTrackers.pop_back();
  8900. }
  8901. break;
  8902. case FlattenedIterKind::FK_Bases:
  8903. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  8904. result = considerLeaf();
  8905. } else {
  8906. // Pop empty base.
  8907. m_typeTrackers.pop_back();
  8908. }
  8909. break;
  8910. case FlattenedIterKind::FK_IncompleteArray:
  8911. m_springLoaded = true; // fall through.
  8912. default:
  8913. case FlattenedIterKind::FK_Simple: {
  8914. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  8915. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  8916. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT &&
  8917. objectKind != ArTypeObjectKind::AR_TOBJ_STRING) {
  8918. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  8919. result = considerLeaf();
  8920. }
  8921. } else {
  8922. result = true;
  8923. }
  8924. }
  8925. }
  8926. m_typeDepth--;
  8927. return result;
  8928. }
  8929. void FlattenedTypeIterator::consumeLeaf()
  8930. {
  8931. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  8932. for (;;) {
  8933. if (m_typeTrackers.empty()) {
  8934. return;
  8935. }
  8936. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8937. // Reach a leaf which is not considered before.
  8938. // Stop here.
  8939. if (!tracker.IsConsidered) {
  8940. break;
  8941. }
  8942. switch (tracker.IterKind) {
  8943. case FlattenedIterKind::FK_Expressions:
  8944. ++tracker.CurrentExpr;
  8945. if (tracker.CurrentExpr == tracker.EndExpr) {
  8946. m_typeTrackers.pop_back();
  8947. topConsumed = false;
  8948. } else {
  8949. return;
  8950. }
  8951. break;
  8952. case FlattenedIterKind::FK_Fields:
  8953. ++tracker.CurrentField;
  8954. if (tracker.CurrentField == tracker.EndField) {
  8955. m_typeTrackers.pop_back();
  8956. topConsumed = false;
  8957. } else {
  8958. return;
  8959. }
  8960. break;
  8961. case FlattenedIterKind::FK_Bases:
  8962. ++tracker.CurrentBase;
  8963. if (tracker.CurrentBase == tracker.EndBase) {
  8964. m_typeTrackers.pop_back();
  8965. topConsumed = false;
  8966. } else {
  8967. return;
  8968. }
  8969. break;
  8970. case FlattenedIterKind::FK_IncompleteArray:
  8971. if (m_draining) {
  8972. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  8973. m_incompleteCount = tracker.Count;
  8974. m_typeTrackers.pop_back();
  8975. }
  8976. return;
  8977. default:
  8978. case FlattenedIterKind::FK_Simple: {
  8979. m_springLoaded = false;
  8980. if (!topConsumed) {
  8981. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  8982. --tracker.Count;
  8983. }
  8984. else {
  8985. topConsumed = false;
  8986. }
  8987. if (tracker.Count == 0) {
  8988. m_typeTrackers.pop_back();
  8989. } else {
  8990. return;
  8991. }
  8992. }
  8993. }
  8994. }
  8995. }
  8996. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  8997. {
  8998. Expr* e = *expression;
  8999. Stmt::StmtClass expressionClass = e->getStmtClass();
  9000. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  9001. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  9002. if (initExpr->getNumInits() == 0) {
  9003. return false;
  9004. }
  9005. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  9006. MultiExprArg::iterator ii = inits.begin();
  9007. MultiExprArg::iterator ie = inits.end();
  9008. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  9009. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9010. return true;
  9011. }
  9012. return pushTrackerForType(e->getType(), expression);
  9013. }
  9014. // TODO: improve this to provide a 'peek' at intermediate types,
  9015. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  9016. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  9017. {
  9018. if (type->isVoidType()) {
  9019. return false;
  9020. }
  9021. if (type->isFunctionType()) {
  9022. return false;
  9023. }
  9024. if (m_firstType.isNull()) {
  9025. m_firstType = type;
  9026. }
  9027. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  9028. QualType elementType;
  9029. unsigned int elementCount;
  9030. const RecordType* recordType;
  9031. RecordDecl::field_iterator fi, fe;
  9032. switch (objectKind)
  9033. {
  9034. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  9035. // TODO: handle multi-dimensional arrays
  9036. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  9037. elementCount = GetArraySize(type);
  9038. if (elementCount == 0) {
  9039. if (type->isIncompleteArrayType()) {
  9040. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  9041. return true;
  9042. }
  9043. return false;
  9044. }
  9045. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9046. elementType, elementCount, nullptr));
  9047. return true;
  9048. case ArTypeObjectKind::AR_TOBJ_BASIC:
  9049. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  9050. return true;
  9051. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  9052. recordType = type->getAsStructureType();
  9053. if (recordType == nullptr)
  9054. recordType = dyn_cast<RecordType>(type.getTypePtr());
  9055. fi = recordType->getDecl()->field_begin();
  9056. fe = recordType->getDecl()->field_end();
  9057. bool bAddTracker = false;
  9058. // Skip empty struct.
  9059. if (fi != fe) {
  9060. m_typeTrackers.push_back(
  9061. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9062. type = (*fi)->getType();
  9063. bAddTracker = true;
  9064. }
  9065. if (CXXRecordDecl *cxxRecordDecl =
  9066. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  9067. CXXRecordDecl::base_class_iterator bi, be;
  9068. bi = cxxRecordDecl->bases_begin();
  9069. be = cxxRecordDecl->bases_end();
  9070. if (bi != be) {
  9071. // Add type tracker for base.
  9072. // Add base after child to make sure base considered first.
  9073. m_typeTrackers.push_back(
  9074. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  9075. bAddTracker = true;
  9076. }
  9077. }
  9078. return bAddTracker;
  9079. }
  9080. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  9081. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9082. m_source.GetMatrixOrVectorElementType(type),
  9083. GetElementCount(type), nullptr));
  9084. return true;
  9085. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  9086. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9087. m_source.GetMatrixOrVectorElementType(type),
  9088. GetHLSLVecSize(type), nullptr));
  9089. return true;
  9090. case ArTypeObjectKind::AR_TOBJ_OBJECT: {
  9091. if (m_source.IsSubobjectType(type)) {
  9092. // subobjects are initialized with initialization lists
  9093. recordType = type->getAsStructureType();
  9094. fi = recordType->getDecl()->field_begin();
  9095. fe = recordType->getDecl()->field_end();
  9096. m_typeTrackers.push_back(
  9097. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9098. return true;
  9099. }
  9100. else {
  9101. // Object have no sub-types.
  9102. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9103. type.getCanonicalType(), 1, expression));
  9104. return true;
  9105. }
  9106. }
  9107. case ArTypeObjectKind::AR_TOBJ_STRING: {
  9108. // Strings have no sub-types.
  9109. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9110. type.getCanonicalType(), 1, expression));
  9111. return true;
  9112. }
  9113. default:
  9114. DXASSERT(false, "unreachable");
  9115. return false;
  9116. }
  9117. }
  9118. FlattenedTypeIterator::ComparisonResult
  9119. FlattenedTypeIterator::CompareIterators(
  9120. HLSLExternalSource& source,
  9121. SourceLocation loc,
  9122. FlattenedTypeIterator& leftIter,
  9123. FlattenedTypeIterator& rightIter)
  9124. {
  9125. FlattenedTypeIterator::ComparisonResult result;
  9126. result.LeftCount = 0;
  9127. result.RightCount = 0;
  9128. result.AreElementsEqual = true; // Until proven otherwise.
  9129. result.CanConvertElements = true; // Until proven otherwise.
  9130. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  9131. {
  9132. Expr* actualExpr = rightIter.getExprOrNull();
  9133. bool hasExpr = actualExpr != nullptr;
  9134. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  9135. StandardConversionSequence standard;
  9136. ExprResult convertedExpr;
  9137. if (!source.CanConvert(loc,
  9138. hasExpr ? actualExpr : &scratchExpr,
  9139. leftIter.getCurrentElement(),
  9140. ExplicitConversionFalse,
  9141. nullptr,
  9142. &standard)) {
  9143. result.AreElementsEqual = false;
  9144. result.CanConvertElements = false;
  9145. break;
  9146. }
  9147. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  9148. {
  9149. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  9150. leftIter.getCurrentElement(),
  9151. standard,
  9152. Sema::AA_Casting,
  9153. Sema::CCK_ImplicitConversion);
  9154. }
  9155. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  9156. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  9157. {
  9158. result.AreElementsEqual = false;
  9159. }
  9160. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  9161. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  9162. // If we need to apply conversions to the expressions, then advance a single element.
  9163. if (hasExpr && convertedExpr.isUsable()) {
  9164. rightIter.replaceExpr(convertedExpr.get());
  9165. advance = 1;
  9166. }
  9167. leftIter.advanceCurrentElement(advance);
  9168. rightIter.advanceCurrentElement(advance);
  9169. result.LeftCount += advance;
  9170. result.RightCount += advance;
  9171. }
  9172. result.LeftCount += leftIter.countRemaining();
  9173. result.RightCount += rightIter.countRemaining();
  9174. return result;
  9175. }
  9176. FlattenedTypeIterator::ComparisonResult
  9177. FlattenedTypeIterator::CompareTypes(
  9178. HLSLExternalSource& source,
  9179. SourceLocation leftLoc, SourceLocation rightLoc,
  9180. QualType left, QualType right)
  9181. {
  9182. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9183. FlattenedTypeIterator rightIter(rightLoc, right, source);
  9184. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9185. }
  9186. FlattenedTypeIterator::ComparisonResult
  9187. FlattenedTypeIterator::CompareTypesForInit(
  9188. HLSLExternalSource& source, QualType left, MultiExprArg args,
  9189. SourceLocation leftLoc, SourceLocation rightLoc)
  9190. {
  9191. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9192. FlattenedTypeIterator rightIter(rightLoc, args, source);
  9193. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9194. }
  9195. ////////////////////////////////////////////////////////////////////////////////
  9196. // Attribute processing support. //
  9197. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  9198. {
  9199. int64_t value = 0;
  9200. if (Attr.getNumArgs() > index)
  9201. {
  9202. Expr *E = nullptr;
  9203. if (!Attr.isArgExpr(index)) {
  9204. // For case arg is constant variable.
  9205. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  9206. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  9207. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  9208. Sema::LookupNameKind::LookupOrdinaryName));
  9209. if (!decl) {
  9210. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9211. return value;
  9212. }
  9213. Expr *init = decl->getInit();
  9214. if (!init) {
  9215. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9216. return value;
  9217. }
  9218. E = init;
  9219. } else
  9220. E = Attr.getArgAsExpr(index);
  9221. clang::APValue ArgNum;
  9222. bool displayError = false;
  9223. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  9224. {
  9225. displayError = true;
  9226. }
  9227. else
  9228. {
  9229. if (ArgNum.isInt())
  9230. {
  9231. value = ArgNum.getInt().getSExtValue();
  9232. }
  9233. else if (ArgNum.isFloat())
  9234. {
  9235. llvm::APSInt floatInt;
  9236. bool isPrecise;
  9237. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  9238. {
  9239. value = floatInt.getSExtValue();
  9240. }
  9241. else
  9242. {
  9243. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9244. }
  9245. }
  9246. else
  9247. {
  9248. displayError = true;
  9249. }
  9250. if (value < 0)
  9251. {
  9252. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9253. }
  9254. }
  9255. if (displayError)
  9256. {
  9257. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  9258. << Attr.getName() << AANT_ArgumentIntegerConstant
  9259. << E->getSourceRange();
  9260. }
  9261. }
  9262. return (int)value;
  9263. }
  9264. // TODO: support float arg directly.
  9265. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  9266. unsigned index = 0) {
  9267. int value = 0;
  9268. if (Attr.getNumArgs() > index) {
  9269. Expr *E = Attr.getArgAsExpr(index);
  9270. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  9271. llvm::APFloat flV = FL->getValue();
  9272. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  9273. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  9274. value = intV.getLimitedValue();
  9275. } else {
  9276. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  9277. value = intV.getLimitedValue();
  9278. }
  9279. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  9280. llvm::APInt intV =
  9281. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  9282. value = intV.getLimitedValue();
  9283. } else {
  9284. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  9285. << Attr.getName();
  9286. }
  9287. }
  9288. return value;
  9289. }
  9290. static Stmt* IgnoreParensAndDecay(Stmt* S)
  9291. {
  9292. for (;;)
  9293. {
  9294. switch (S->getStmtClass())
  9295. {
  9296. case Stmt::ParenExprClass:
  9297. S = cast<ParenExpr>(S)->getSubExpr();
  9298. break;
  9299. case Stmt::ImplicitCastExprClass:
  9300. {
  9301. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  9302. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  9303. castExpr->getCastKind() != CK_NoOp &&
  9304. castExpr->getCastKind() != CK_LValueToRValue)
  9305. {
  9306. return S;
  9307. }
  9308. S = castExpr->getSubExpr();
  9309. }
  9310. break;
  9311. default:
  9312. return S;
  9313. }
  9314. }
  9315. }
  9316. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  9317. {
  9318. DXASSERT_NOMSG(E != nullptr);
  9319. Expr* subscriptExpr = E->getIdx();
  9320. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  9321. if (subscriptExpr == nullptr ||
  9322. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  9323. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  9324. {
  9325. S.Diag(
  9326. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  9327. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  9328. return nullptr;
  9329. }
  9330. return E->getBase();
  9331. }
  9332. static bool IsValidClipPlaneDecl(Decl* D)
  9333. {
  9334. Decl::Kind kind = D->getKind();
  9335. if (kind == Decl::Var)
  9336. {
  9337. VarDecl* varDecl = cast<VarDecl>(D);
  9338. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  9339. varDecl->getType().isConstQualified())
  9340. {
  9341. return false;
  9342. }
  9343. return true;
  9344. }
  9345. else if (kind == Decl::Field)
  9346. {
  9347. return true;
  9348. }
  9349. return false;
  9350. }
  9351. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  9352. {
  9353. Stmt* cursor = E;
  9354. // clip plane expressions are a linear path, so no need to traverse the tree here.
  9355. while (cursor != nullptr)
  9356. {
  9357. bool supported = true;
  9358. cursor = IgnoreParensAndDecay(cursor);
  9359. switch (cursor->getStmtClass())
  9360. {
  9361. case Stmt::ArraySubscriptExprClass:
  9362. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  9363. if (cursor == nullptr)
  9364. {
  9365. // nullptr indicates failure, and the error message has already been printed out
  9366. return nullptr;
  9367. }
  9368. break;
  9369. case Stmt::DeclRefExprClass:
  9370. {
  9371. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  9372. Decl* decl = declRef->getDecl();
  9373. supported = IsValidClipPlaneDecl(decl);
  9374. cursor = supported ? nullptr : cursor;
  9375. }
  9376. break;
  9377. case Stmt::MemberExprClass:
  9378. {
  9379. MemberExpr* member = cast<MemberExpr>(cursor);
  9380. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  9381. cursor = supported ? member->getBase() : cursor;
  9382. }
  9383. break;
  9384. default:
  9385. supported = false;
  9386. break;
  9387. }
  9388. if (!supported)
  9389. {
  9390. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  9391. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  9392. return nullptr;
  9393. }
  9394. }
  9395. // Validate that the type is a float4.
  9396. QualType expressionType = E->getType();
  9397. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  9398. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  9399. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  9400. {
  9401. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  9402. return nullptr;
  9403. }
  9404. return E;
  9405. }
  9406. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  9407. {
  9408. Expr* clipExprs[6];
  9409. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  9410. {
  9411. if (A.getNumArgs() <= index)
  9412. {
  9413. clipExprs[index] = nullptr;
  9414. continue;
  9415. }
  9416. Expr *E = A.getArgAsExpr(index);
  9417. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  9418. }
  9419. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  9420. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  9421. A.getAttributeSpellingListIndex());
  9422. }
  9423. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  9424. {
  9425. int argValue = ValidateAttributeIntArg(S, Attr);
  9426. // Default value is 0 (full unroll).
  9427. if (Attr.getNumArgs() == 0) argValue = 0;
  9428. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  9429. argValue, Attr.getAttributeSpellingListIndex());
  9430. }
  9431. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  9432. {
  9433. Stmt::StmtClass stClass = St->getStmtClass();
  9434. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  9435. {
  9436. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9437. << Attr.getName();
  9438. }
  9439. }
  9440. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  9441. {
  9442. Stmt::StmtClass stClass = St->getStmtClass();
  9443. if (stClass != Stmt::SwitchStmtClass)
  9444. {
  9445. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9446. << Attr.getName();
  9447. }
  9448. }
  9449. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  9450. {
  9451. Stmt::StmtClass stClass = St->getStmtClass();
  9452. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  9453. {
  9454. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9455. << Attr.getName();
  9456. }
  9457. }
  9458. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  9459. {
  9460. // values is an optional comma-separated list of potential values.
  9461. if (A.getNumArgs() <= index)
  9462. return StringRef();
  9463. Expr* E = A.getArgAsExpr(index);
  9464. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  9465. {
  9466. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  9467. << A.getName();
  9468. return StringRef();
  9469. }
  9470. StringLiteral* sl = cast<StringLiteral>(E);
  9471. StringRef result = sl->getString();
  9472. // Return result with no additional validation.
  9473. if (values == nullptr)
  9474. {
  9475. return result;
  9476. }
  9477. const char* value = values;
  9478. while (*value != '\0')
  9479. {
  9480. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  9481. // Look for a match.
  9482. const char* argData = result.data();
  9483. size_t argDataLen = result.size();
  9484. while (argDataLen != 0 && *argData == *value && *value)
  9485. {
  9486. ++argData;
  9487. ++value;
  9488. --argDataLen;
  9489. }
  9490. // Match found if every input character matched.
  9491. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  9492. {
  9493. return result;
  9494. }
  9495. // Move to next separator.
  9496. while (*value != '\0' && *value != ',')
  9497. {
  9498. ++value;
  9499. }
  9500. // Move to the start of the next item if any.
  9501. if (*value == ',') value++;
  9502. }
  9503. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  9504. // No match found.
  9505. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  9506. << A.getName() << values;
  9507. return StringRef();
  9508. }
  9509. static
  9510. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  9511. {
  9512. if (D->isFunctionOrFunctionTemplate())
  9513. {
  9514. return true;
  9515. }
  9516. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  9517. return false;
  9518. }
  9519. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  9520. {
  9521. DXASSERT_NOMSG(D != nullptr);
  9522. DXASSERT_NOMSG(!A.isInvalid());
  9523. Attr* declAttr = nullptr;
  9524. Handled = true;
  9525. switch (A.getKind())
  9526. {
  9527. case AttributeList::AT_HLSLIn:
  9528. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  9529. A.getAttributeSpellingListIndex());
  9530. break;
  9531. case AttributeList::AT_HLSLOut:
  9532. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  9533. A.getAttributeSpellingListIndex());
  9534. break;
  9535. case AttributeList::AT_HLSLInOut:
  9536. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  9537. A.getAttributeSpellingListIndex());
  9538. break;
  9539. case AttributeList::AT_HLSLNoInterpolation:
  9540. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  9541. A.getAttributeSpellingListIndex());
  9542. break;
  9543. case AttributeList::AT_HLSLLinear:
  9544. case AttributeList::AT_HLSLCenter:
  9545. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  9546. A.getAttributeSpellingListIndex());
  9547. break;
  9548. case AttributeList::AT_HLSLNoPerspective:
  9549. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  9550. A.getAttributeSpellingListIndex());
  9551. break;
  9552. case AttributeList::AT_HLSLSample:
  9553. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  9554. A.getAttributeSpellingListIndex());
  9555. break;
  9556. case AttributeList::AT_HLSLCentroid:
  9557. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  9558. A.getAttributeSpellingListIndex());
  9559. break;
  9560. case AttributeList::AT_HLSLPrecise:
  9561. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  9562. A.getAttributeSpellingListIndex());
  9563. break;
  9564. case AttributeList::AT_HLSLShared:
  9565. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  9566. A.getAttributeSpellingListIndex());
  9567. break;
  9568. case AttributeList::AT_HLSLGroupShared:
  9569. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  9570. A.getAttributeSpellingListIndex());
  9571. break;
  9572. case AttributeList::AT_HLSLUniform:
  9573. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  9574. A.getAttributeSpellingListIndex());
  9575. break;
  9576. case AttributeList::AT_HLSLColumnMajor:
  9577. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  9578. A.getAttributeSpellingListIndex());
  9579. break;
  9580. case AttributeList::AT_HLSLRowMajor:
  9581. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  9582. A.getAttributeSpellingListIndex());
  9583. break;
  9584. case AttributeList::AT_HLSLUnorm:
  9585. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  9586. A.getAttributeSpellingListIndex());
  9587. break;
  9588. case AttributeList::AT_HLSLSnorm:
  9589. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  9590. A.getAttributeSpellingListIndex());
  9591. break;
  9592. case AttributeList::AT_HLSLPoint:
  9593. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  9594. A.getAttributeSpellingListIndex());
  9595. break;
  9596. case AttributeList::AT_HLSLLine:
  9597. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  9598. A.getAttributeSpellingListIndex());
  9599. break;
  9600. case AttributeList::AT_HLSLLineAdj:
  9601. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  9602. A.getAttributeSpellingListIndex());
  9603. break;
  9604. case AttributeList::AT_HLSLTriangle:
  9605. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  9606. A.getAttributeSpellingListIndex());
  9607. break;
  9608. case AttributeList::AT_HLSLTriangleAdj:
  9609. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  9610. A.getAttributeSpellingListIndex());
  9611. break;
  9612. case AttributeList::AT_HLSLGloballyCoherent:
  9613. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  9614. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9615. break;
  9616. default:
  9617. Handled = false;
  9618. break;
  9619. }
  9620. if (declAttr != nullptr)
  9621. {
  9622. DXASSERT_NOMSG(Handled);
  9623. D->addAttr(declAttr);
  9624. return;
  9625. }
  9626. Handled = true;
  9627. switch (A.getKind())
  9628. {
  9629. // These apply to statements, not declarations. The warning messages clarify this properly.
  9630. case AttributeList::AT_HLSLUnroll:
  9631. case AttributeList::AT_HLSLAllowUAVCondition:
  9632. case AttributeList::AT_HLSLLoop:
  9633. case AttributeList::AT_HLSLFastOpt:
  9634. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9635. << A.getName();
  9636. return;
  9637. case AttributeList::AT_HLSLBranch:
  9638. case AttributeList::AT_HLSLFlatten:
  9639. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9640. << A.getName();
  9641. return;
  9642. case AttributeList::AT_HLSLForceCase:
  9643. case AttributeList::AT_HLSLCall:
  9644. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9645. << A.getName();
  9646. return;
  9647. // These are the cases that actually apply to declarations.
  9648. case AttributeList::AT_HLSLClipPlanes:
  9649. declAttr = HandleClipPlanes(S, A);
  9650. break;
  9651. case AttributeList::AT_HLSLDomain:
  9652. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  9653. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  9654. break;
  9655. case AttributeList::AT_HLSLEarlyDepthStencil:
  9656. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9657. break;
  9658. case AttributeList::AT_HLSLInstance:
  9659. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  9660. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9661. break;
  9662. case AttributeList::AT_HLSLMaxTessFactor:
  9663. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  9664. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  9665. break;
  9666. case AttributeList::AT_HLSLNumThreads:
  9667. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  9668. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  9669. A.getAttributeSpellingListIndex());
  9670. break;
  9671. case AttributeList::AT_HLSLRootSignature:
  9672. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  9673. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  9674. A.getAttributeSpellingListIndex());
  9675. break;
  9676. case AttributeList::AT_HLSLOutputControlPoints:
  9677. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  9678. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9679. break;
  9680. case AttributeList::AT_HLSLOutputTopology:
  9681. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  9682. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  9683. break;
  9684. case AttributeList::AT_HLSLPartitioning:
  9685. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  9686. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  9687. break;
  9688. case AttributeList::AT_HLSLPatchConstantFunc:
  9689. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  9690. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  9691. break;
  9692. case AttributeList::AT_HLSLShader:
  9693. declAttr = ::new (S.Context) HLSLShaderAttr(
  9694. A.getRange(), S.Context,
  9695. ValidateAttributeStringArg(S, A,
  9696. "compute,vertex,pixel,hull,domain,geometry,raygeneration,intersection,anyhit,closesthit,miss,callable"),
  9697. A.getAttributeSpellingListIndex());
  9698. break;
  9699. case AttributeList::AT_HLSLMaxVertexCount:
  9700. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  9701. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9702. break;
  9703. case AttributeList::AT_HLSLExperimental:
  9704. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  9705. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  9706. A.getAttributeSpellingListIndex());
  9707. break;
  9708. case AttributeList::AT_NoInline:
  9709. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9710. break;
  9711. case AttributeList::AT_HLSLExport:
  9712. declAttr = ::new (S.Context) HLSLExportAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9713. break;
  9714. default:
  9715. Handled = false;
  9716. break; // SPIRV Change: was return;
  9717. }
  9718. if (declAttr != nullptr)
  9719. {
  9720. DXASSERT_NOMSG(Handled);
  9721. D->addAttr(declAttr);
  9722. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  9723. // and prevent code generation.
  9724. ValidateAttributeTargetIsFunction(S, D, A);
  9725. return; // SPIRV Change
  9726. }
  9727. // SPIRV Change Starts
  9728. Handled = true;
  9729. switch (A.getKind())
  9730. {
  9731. case AttributeList::AT_VKBuiltIn:
  9732. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  9733. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation,BaseVertex,BaseInstance,DrawIndex,DeviceIndex"),
  9734. A.getAttributeSpellingListIndex());
  9735. break;
  9736. case AttributeList::AT_VKLocation:
  9737. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  9738. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9739. break;
  9740. case AttributeList::AT_VKIndex:
  9741. declAttr = ::new (S.Context) VKIndexAttr(A.getRange(), S.Context,
  9742. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9743. break;
  9744. case AttributeList::AT_VKBinding:
  9745. declAttr = ::new (S.Context) VKBindingAttr(A.getRange(), S.Context,
  9746. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1),
  9747. A.getAttributeSpellingListIndex());
  9748. break;
  9749. case AttributeList::AT_VKCounterBinding:
  9750. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  9751. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9752. break;
  9753. case AttributeList::AT_VKPushConstant:
  9754. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  9755. A.getAttributeSpellingListIndex());
  9756. break;
  9757. case AttributeList::AT_VKOffset:
  9758. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  9759. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9760. break;
  9761. case AttributeList::AT_VKInputAttachmentIndex:
  9762. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  9763. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  9764. A.getAttributeSpellingListIndex());
  9765. break;
  9766. case AttributeList::AT_VKConstantId:
  9767. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  9768. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9769. break;
  9770. case AttributeList::AT_VKPostDepthCoverage:
  9771. declAttr = ::new (S.Context) VKPostDepthCoverageAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9772. break;
  9773. default:
  9774. Handled = false;
  9775. return;
  9776. }
  9777. if (declAttr != nullptr)
  9778. {
  9779. DXASSERT_NOMSG(Handled);
  9780. D->addAttr(declAttr);
  9781. }
  9782. // SPIRV Change Ends
  9783. }
  9784. /// <summary>Processes an attribute for a statement.</summary>
  9785. /// <param name="S">Sema with context.</param>
  9786. /// <param name="St">Statement annotated.</param>
  9787. /// <param name="A">Single parsed attribute to process.</param>
  9788. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  9789. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  9790. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  9791. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  9792. {
  9793. // | Construct | Allowed Attributes |
  9794. // +------------------+--------------------------------------------+
  9795. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  9796. // | if | branch, flatten |
  9797. // | switch | branch, flatten, forcecase, call |
  9798. Attr * result = nullptr;
  9799. Handled = true;
  9800. switch (A.getKind())
  9801. {
  9802. case AttributeList::AT_HLSLUnroll:
  9803. ValidateAttributeOnLoop(S, St, A);
  9804. result = HandleUnrollAttribute(S, A);
  9805. break;
  9806. case AttributeList::AT_HLSLAllowUAVCondition:
  9807. ValidateAttributeOnLoop(S, St, A);
  9808. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  9809. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9810. break;
  9811. case AttributeList::AT_HLSLLoop:
  9812. ValidateAttributeOnLoop(S, St, A);
  9813. result = ::new (S.Context) HLSLLoopAttr(
  9814. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9815. break;
  9816. case AttributeList::AT_HLSLFastOpt:
  9817. ValidateAttributeOnLoop(S, St, A);
  9818. result = ::new (S.Context) HLSLFastOptAttr(
  9819. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9820. break;
  9821. case AttributeList::AT_HLSLBranch:
  9822. ValidateAttributeOnSwitchOrIf(S, St, A);
  9823. result = ::new (S.Context) HLSLBranchAttr(
  9824. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9825. break;
  9826. case AttributeList::AT_HLSLFlatten:
  9827. ValidateAttributeOnSwitchOrIf(S, St, A);
  9828. result = ::new (S.Context) HLSLFlattenAttr(
  9829. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9830. break;
  9831. case AttributeList::AT_HLSLForceCase:
  9832. ValidateAttributeOnSwitch(S, St, A);
  9833. result = ::new (S.Context) HLSLForceCaseAttr(
  9834. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9835. break;
  9836. case AttributeList::AT_HLSLCall:
  9837. ValidateAttributeOnSwitch(S, St, A);
  9838. result = ::new (S.Context) HLSLCallAttr(
  9839. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9840. break;
  9841. default:
  9842. Handled = false;
  9843. break;
  9844. }
  9845. return result;
  9846. }
  9847. ////////////////////////////////////////////////////////////////////////////////
  9848. // Implementation of Sema members. //
  9849. Decl* Sema::ActOnStartHLSLBuffer(
  9850. Scope* bufferScope,
  9851. bool cbuffer, SourceLocation KwLoc,
  9852. IdentifierInfo *Ident, SourceLocation IdentLoc,
  9853. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  9854. SourceLocation LBrace)
  9855. {
  9856. // For anonymous namespace, take the location of the left brace.
  9857. DeclContext* lexicalParent = getCurLexicalContext();
  9858. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9859. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  9860. Ident, IdentLoc, BufferAttributes, LBrace);
  9861. // Keep track of the currently active buffer.
  9862. HLSLBuffers.push_back(result);
  9863. // Validate unusual annotations and emit diagnostics.
  9864. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  9865. auto && unusualIter = BufferAttributes.begin();
  9866. auto && unusualEnd = BufferAttributes.end();
  9867. char expectedRegisterType = cbuffer ? 'b' : 't';
  9868. for (; unusualIter != unusualEnd; ++unusualIter) {
  9869. switch ((*unusualIter)->getKind()) {
  9870. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9871. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  9872. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  9873. break;
  9874. }
  9875. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9876. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  9877. // SPIRV Change Starts - skip the check if space-only for SPIR-V
  9878. if (getLangOpts().SPIRV && registerAssignment->isSpaceOnly())
  9879. continue;
  9880. // SPIRV Change Ends
  9881. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  9882. Diag(registerAssignment->Loc, cbuffer ? diag::err_hlsl_unsupported_cbuffer_register :
  9883. diag::err_hlsl_unsupported_tbuffer_register);
  9884. } else if (registerAssignment->ShaderProfile.size() > 0) {
  9885. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  9886. }
  9887. break;
  9888. }
  9889. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9890. // Ignore semantic declarations.
  9891. break;
  9892. }
  9893. }
  9894. }
  9895. PushOnScopeChains(result, bufferScope);
  9896. PushDeclContext(bufferScope, result);
  9897. ActOnDocumentableDecl(result);
  9898. return result;
  9899. }
  9900. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  9901. {
  9902. DXASSERT_NOMSG(Dcl != nullptr);
  9903. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9904. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  9905. HLSLBuffers.pop_back();
  9906. PopDeclContext();
  9907. }
  9908. Decl* Sema::getActiveHLSLBuffer() const
  9909. {
  9910. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  9911. }
  9912. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  9913. DeclGroupPtrTy &dcl, bool iscbuf) {
  9914. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9915. HLSLBuffers.pop_back();
  9916. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9917. Decl *decl = dcl.get().getSingleDecl();
  9918. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  9919. IdentifierInfo *Ident = namedDecl->getIdentifier();
  9920. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  9921. SourceLocation Loc = decl->getLocation();
  9922. // Prevent array type in template. The only way to specify an array in the template type
  9923. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  9924. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  9925. QualType declType = cast<VarDecl>(namedDecl)->getType();
  9926. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  9927. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  9928. declType = arrayType->getElementType();
  9929. }
  9930. // Check to make that sure only structs are allowed as parameter types for
  9931. // ConstantBuffer and TextureBuffer.
  9932. if (!declType->isStructureType()) {
  9933. Diag(decl->getLocStart(),
  9934. diag::err_hlsl_typeintemplateargument_requires_struct)
  9935. << declType;
  9936. return nullptr;
  9937. }
  9938. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  9939. DeclContext *lexicalParent = getCurLexicalContext();
  9940. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9941. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  9942. KwLoc, Ident, Loc, hlslAttrs, Loc);
  9943. // set relation
  9944. namedDecl->setDeclContext(result);
  9945. result->addDecl(namedDecl);
  9946. // move attribute from constant to constant buffer
  9947. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  9948. namedDecl->setUnusualAnnotations(hlslAttrs);
  9949. return result;
  9950. }
  9951. bool Sema::IsOnHLSLBufferView() {
  9952. // nullptr will not pushed for cbuffer.
  9953. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  9954. }
  9955. void Sema::ActOnStartHLSLBufferView() {
  9956. // Push nullptr to mark HLSLBufferView.
  9957. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9958. HLSLBuffers.emplace_back(nullptr);
  9959. }
  9960. HLSLBufferDecl::HLSLBufferDecl(
  9961. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  9962. IdentifierInfo *Id, SourceLocation IdLoc,
  9963. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9964. SourceLocation LBrace)
  9965. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  9966. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  9967. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  9968. if (!BufferAttributes.empty()) {
  9969. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9970. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  9971. }
  9972. }
  9973. HLSLBufferDecl *
  9974. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  9975. bool constantbuffer, SourceLocation KwLoc,
  9976. IdentifierInfo *Id, SourceLocation IdLoc,
  9977. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9978. SourceLocation LBrace) {
  9979. DeclContext *DC = C.getTranslationUnitDecl();
  9980. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  9981. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  9982. if (DC != lexicalParent) {
  9983. result->setLexicalDeclContext(lexicalParent);
  9984. }
  9985. return result;
  9986. }
  9987. const char *HLSLBufferDecl::getDeclKindName() const {
  9988. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  9989. "ConstantBuffer"};
  9990. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  9991. return HLSLBufferNames[index];
  9992. }
  9993. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  9994. assert(NewDecl != nullptr);
  9995. if (!getLangOpts().HLSL) {
  9996. return;
  9997. }
  9998. if (!D.UnusualAnnotations.empty()) {
  9999. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10000. getASTContext(), D.UnusualAnnotations.data(),
  10001. D.UnusualAnnotations.size()));
  10002. D.UnusualAnnotations.clear();
  10003. }
  10004. // pragma pack_matrix.
  10005. // Do this for struct member also.
  10006. if (ValueDecl *VD = dyn_cast<ValueDecl>(NewDecl)) {
  10007. QualType Ty = VD->getType();
  10008. QualType EltTy = Ty;
  10009. while (EltTy->isArrayType()) {
  10010. EltTy = EltTy->getAsArrayTypeUnsafe()->getElementType();
  10011. }
  10012. if (hlsl::IsHLSLMatType(EltTy)) {
  10013. bool bRowMajor = false;
  10014. if (!hlsl::HasHLSLMatOrientation(EltTy, &bRowMajor)) {
  10015. if (PackMatrixColMajorPragmaOn || PackMatrixRowMajorPragmaOn) {
  10016. // Add major.
  10017. QualType NewEltTy = Context.getAttributedType(
  10018. PackMatrixRowMajorPragmaOn
  10019. ? AttributedType::attr_hlsl_row_major
  10020. : AttributedType::attr_hlsl_column_major,
  10021. EltTy, EltTy);
  10022. QualType NewTy = NewEltTy;
  10023. if (Ty->isArrayType()) {
  10024. // Build new array type.
  10025. SmallVector<const ArrayType *, 2> arrayTys;
  10026. while (EltTy->isArrayType()) {
  10027. const ArrayType *AT = EltTy->getAsArrayTypeUnsafe();
  10028. arrayTys.emplace_back(AT);
  10029. }
  10030. for (auto rit = arrayTys.rbegin(); rit != arrayTys.rend(); rit++) {
  10031. // Create array type with NewTy.
  10032. const ArrayType *AT = *rit;
  10033. if (const ConstantArrayType *CAT =
  10034. dyn_cast<ConstantArrayType>(AT)) {
  10035. NewTy = Context.getConstantArrayType(
  10036. NewTy, CAT->getSize(), CAT->getSizeModifier(),
  10037. CAT->getIndexTypeCVRQualifiers());
  10038. } else if (const IncompleteArrayType *IAT =
  10039. dyn_cast<IncompleteArrayType>(AT)) {
  10040. NewTy = Context.getIncompleteArrayType(NewTy, IAT->getSizeModifier(),
  10041. IAT->getIndexTypeCVRQualifiers());
  10042. } else {
  10043. DXASSERT(false, "");
  10044. }
  10045. }
  10046. }
  10047. // Update Type.
  10048. VD->setType(NewTy);
  10049. }
  10050. }
  10051. }
  10052. }
  10053. }
  10054. /// Checks whether a usage attribute is compatible with those seen so far and
  10055. /// maintains history.
  10056. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  10057. bool &usageOut) {
  10058. switch (kind) {
  10059. case AttributeList::AT_HLSLIn:
  10060. if (usageIn)
  10061. return false;
  10062. usageIn = true;
  10063. break;
  10064. case AttributeList::AT_HLSLOut:
  10065. if (usageOut)
  10066. return false;
  10067. usageOut = true;
  10068. break;
  10069. default:
  10070. assert(kind == AttributeList::AT_HLSLInOut);
  10071. if (usageOut || usageIn)
  10072. return false;
  10073. usageIn = usageOut = true;
  10074. break;
  10075. }
  10076. return true;
  10077. }
  10078. // Diagnose valid/invalid modifiers for HLSL.
  10079. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC, Expr *BitWidth,
  10080. TypeSourceInfo *TInfo, bool isParameter) {
  10081. assert(getLangOpts().HLSL &&
  10082. "otherwise this is called without checking language first");
  10083. // NOTE: some tests may declare templates.
  10084. if (DC->isNamespace() || DC->isDependentContext()) return true;
  10085. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  10086. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  10087. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  10088. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  10089. bool result = true;
  10090. bool isTypedef = storage == DeclSpec::SCS_typedef;
  10091. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  10092. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  10093. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  10094. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  10095. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  10096. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  10097. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  10098. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  10099. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  10100. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  10101. // Function declarations are not allowed in parameter declaration
  10102. // TODO : Remove this check once we support function declarations/pointers in HLSL
  10103. if (isParameter && isFunction) {
  10104. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  10105. D.setInvalidType();
  10106. return false;
  10107. }
  10108. assert(
  10109. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  10110. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  10111. (isParameter ? 1 : 0))
  10112. && "exactly one type of declarator is being processed");
  10113. // qt/pType captures either the type being modified, or the return type in the
  10114. // case of a function (or method).
  10115. QualType qt = TInfo->getType();
  10116. const Type* pType = qt.getTypePtrOrNull();
  10117. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  10118. // Early checks - these are not simple attribution errors, but constructs that
  10119. // are fundamentally unsupported,
  10120. // and so we avoid errors that might indicate they can be repaired.
  10121. if (DC->isRecord()) {
  10122. unsigned int nestedDiagId = 0;
  10123. if (isTypedef) {
  10124. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  10125. }
  10126. if (isField && pType && pType->isIncompleteArrayType()) {
  10127. nestedDiagId = diag::err_hlsl_unsupported_incomplete_array;
  10128. }
  10129. if (nestedDiagId) {
  10130. Diag(D.getLocStart(), nestedDiagId);
  10131. D.setInvalidType();
  10132. return false;
  10133. }
  10134. }
  10135. // String and subobject declarations are supported only as top level global variables.
  10136. // Const and static modifiers are implied - add them if missing.
  10137. if ((hlsl::IsStringType(qt) || hlslSource->IsSubobjectType(qt)) && !D.isInvalidType()) {
  10138. // string are supported only as top level global variables
  10139. if (!DC->isTranslationUnit()) {
  10140. Diag(D.getLocStart(), diag::err_hlsl_object_not_global) << (int)hlsl::IsStringType(qt);
  10141. result = false;
  10142. }
  10143. if (isExtern) {
  10144. Diag(D.getLocStart(), diag::err_hlsl_object_extern_not_supported) << (int)hlsl::IsStringType(qt);
  10145. result = false;
  10146. }
  10147. const char *PrevSpec = nullptr;
  10148. unsigned DiagID = 0;
  10149. if (!isStatic) {
  10150. D.getMutableDeclSpec().SetStorageClassSpec(*this, DeclSpec::SCS_static, D.getLocStart(), PrevSpec, DiagID, Context.getPrintingPolicy());
  10151. isStatic = true;
  10152. }
  10153. if (!isConst) {
  10154. D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, D.getLocStart(), PrevSpec, DiagID, getLangOpts());
  10155. isConst = true;
  10156. }
  10157. }
  10158. const char* declarationType =
  10159. (isLocalVar) ? "local variable" :
  10160. (isTypedef) ? "typedef" :
  10161. (isFunction) ? "function" :
  10162. (isMethod) ? "method" :
  10163. (isGlobal) ? "global variable" :
  10164. (isParameter) ? "parameter" :
  10165. (isField) ? "field" : "<unknown>";
  10166. if (pType && D.isFunctionDeclarator()) {
  10167. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  10168. if (pFP) {
  10169. qt = pFP->getReturnType();
  10170. pType = qt.getTypePtrOrNull();
  10171. // prohibit string as a return type
  10172. if (hlsl::IsStringType(qt)) {
  10173. static const unsigned selectReturnValueIdx = 2;
  10174. Diag(D.getLocStart(), diag::err_hlsl_unsupported_string_decl) << selectReturnValueIdx;
  10175. D.setInvalidType();
  10176. }
  10177. }
  10178. }
  10179. // Check for deprecated effect object type here, warn, and invalidate decl
  10180. bool bDeprecatedEffectObject = false;
  10181. bool bIsObject = false;
  10182. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  10183. bIsObject = true;
  10184. if (bDeprecatedEffectObject) {
  10185. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  10186. D.setInvalidType();
  10187. return false;
  10188. }
  10189. // Add methods if not ready.
  10190. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  10191. } else if (qt->isArrayType()) {
  10192. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  10193. while (eltQt->isArrayType())
  10194. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  10195. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  10196. // Add methods if not ready.
  10197. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  10198. }
  10199. }
  10200. if (isExtern) {
  10201. if (!(isFunction || isGlobal)) {
  10202. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  10203. << declarationType;
  10204. result = false;
  10205. }
  10206. }
  10207. if (isStatic) {
  10208. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  10209. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  10210. << declarationType;
  10211. result = false;
  10212. }
  10213. }
  10214. if (isVolatile) {
  10215. if (!(isLocalVar || isTypedef)) {
  10216. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  10217. << declarationType;
  10218. result = false;
  10219. }
  10220. }
  10221. if (isConst) {
  10222. if (isField && !isStatic) {
  10223. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  10224. << declarationType;
  10225. result = false;
  10226. }
  10227. }
  10228. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  10229. if (hasSignSpec) {
  10230. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  10231. // vectors or matrices can only have unsigned integer types.
  10232. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  10233. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  10234. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  10235. << g_ArBasicTypeNames[basicKind];
  10236. result = false;
  10237. }
  10238. }
  10239. else {
  10240. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  10241. result = false;
  10242. }
  10243. }
  10244. // Validate attributes
  10245. clang::AttributeList
  10246. *pUniform = nullptr,
  10247. *pUsage = nullptr,
  10248. *pNoInterpolation = nullptr,
  10249. *pLinear = nullptr,
  10250. *pNoPerspective = nullptr,
  10251. *pSample = nullptr,
  10252. *pCentroid = nullptr,
  10253. *pCenter = nullptr,
  10254. *pAnyLinear = nullptr, // first linear attribute found
  10255. *pTopology = nullptr;
  10256. bool usageIn = false;
  10257. bool usageOut = false;
  10258. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  10259. pAttr != NULL; pAttr = pAttr->getNext()) {
  10260. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  10261. continue;
  10262. switch (pAttr->getKind()) {
  10263. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  10264. break;
  10265. case AttributeList::AT_HLSLShared:
  10266. if (!isGlobal) {
  10267. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10268. << pAttr->getName() << declarationType << pAttr->getRange();
  10269. result = false;
  10270. }
  10271. if (isStatic) {
  10272. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10273. << "'static'" << pAttr->getName() << declarationType
  10274. << pAttr->getRange();
  10275. result = false;
  10276. }
  10277. break;
  10278. case AttributeList::AT_HLSLGroupShared:
  10279. if (!isGlobal) {
  10280. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10281. << pAttr->getName() << declarationType << pAttr->getRange();
  10282. result = false;
  10283. }
  10284. if (isExtern) {
  10285. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10286. << "'extern'" << pAttr->getName() << declarationType
  10287. << pAttr->getRange();
  10288. result = false;
  10289. }
  10290. break;
  10291. case AttributeList::AT_HLSLGloballyCoherent:
  10292. if (!bIsObject) {
  10293. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10294. << pAttr->getName() << "non-UAV type";
  10295. result = false;
  10296. }
  10297. break;
  10298. case AttributeList::AT_HLSLUniform:
  10299. if (!(isGlobal || isParameter)) {
  10300. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10301. << pAttr->getName() << declarationType << pAttr->getRange();
  10302. result = false;
  10303. }
  10304. if (isStatic) {
  10305. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10306. << "'static'" << pAttr->getName() << declarationType
  10307. << pAttr->getRange();
  10308. result = false;
  10309. }
  10310. pUniform = pAttr;
  10311. break;
  10312. case AttributeList::AT_HLSLIn:
  10313. case AttributeList::AT_HLSLOut:
  10314. case AttributeList::AT_HLSLInOut:
  10315. if (!isParameter) {
  10316. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  10317. << pAttr->getName() << pAttr->getRange();
  10318. result = false;
  10319. }
  10320. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  10321. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  10322. << pAttr->getName() << pAttr->getRange();
  10323. result = false;
  10324. }
  10325. pUsage = pAttr;
  10326. break;
  10327. case AttributeList::AT_HLSLNoInterpolation:
  10328. if (!(isParameter || isField || isFunction)) {
  10329. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10330. << pAttr->getName() << declarationType << pAttr->getRange();
  10331. result = false;
  10332. }
  10333. if (pNoInterpolation) {
  10334. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10335. << pAttr->getName() << pAttr->getRange();
  10336. }
  10337. pNoInterpolation = pAttr;
  10338. break;
  10339. case AttributeList::AT_HLSLLinear:
  10340. case AttributeList::AT_HLSLCenter:
  10341. case AttributeList::AT_HLSLNoPerspective:
  10342. case AttributeList::AT_HLSLSample:
  10343. case AttributeList::AT_HLSLCentroid:
  10344. if (!(isParameter || isField || isFunction)) {
  10345. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10346. << pAttr->getName() << declarationType << pAttr->getRange();
  10347. result = false;
  10348. }
  10349. if (nullptr == pAnyLinear)
  10350. pAnyLinear = pAttr;
  10351. switch (pAttr->getKind()) {
  10352. case AttributeList::AT_HLSLLinear:
  10353. if (pLinear) {
  10354. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10355. << pAttr->getName() << pAttr->getRange();
  10356. }
  10357. pLinear = pAttr;
  10358. break;
  10359. case AttributeList::AT_HLSLCenter:
  10360. if (pCenter) {
  10361. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10362. << pAttr->getName() << pAttr->getRange();
  10363. }
  10364. pCenter = pAttr;
  10365. break;
  10366. case AttributeList::AT_HLSLNoPerspective:
  10367. if (pNoPerspective) {
  10368. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10369. << pAttr->getName() << pAttr->getRange();
  10370. }
  10371. pNoPerspective = pAttr;
  10372. break;
  10373. case AttributeList::AT_HLSLSample:
  10374. if (pSample) {
  10375. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10376. << pAttr->getName() << pAttr->getRange();
  10377. }
  10378. pSample = pAttr;
  10379. break;
  10380. case AttributeList::AT_HLSLCentroid:
  10381. if (pCentroid) {
  10382. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10383. << pAttr->getName() << pAttr->getRange();
  10384. }
  10385. pCentroid = pAttr;
  10386. break;
  10387. default:
  10388. // Only relevant to the four attribs included in this block.
  10389. break;
  10390. }
  10391. break;
  10392. case AttributeList::AT_HLSLPoint:
  10393. case AttributeList::AT_HLSLLine:
  10394. case AttributeList::AT_HLSLLineAdj:
  10395. case AttributeList::AT_HLSLTriangle:
  10396. case AttributeList::AT_HLSLTriangleAdj:
  10397. if (!(isParameter)) {
  10398. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10399. << pAttr->getName() << declarationType << pAttr->getRange();
  10400. result = false;
  10401. }
  10402. if (pTopology) {
  10403. if (pTopology->getKind() == pAttr->getKind()) {
  10404. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10405. << pAttr->getName() << pAttr->getRange();
  10406. } else {
  10407. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10408. << pAttr->getName() << pTopology->getName()
  10409. << declarationType << pAttr->getRange();
  10410. result = false;
  10411. }
  10412. }
  10413. pTopology = pAttr;
  10414. break;
  10415. case AttributeList::AT_HLSLExport:
  10416. if (!isFunction) {
  10417. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10418. << pAttr->getName() << declarationType << pAttr->getRange();
  10419. result = false;
  10420. }
  10421. if (isStatic) {
  10422. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10423. << "'static'" << pAttr->getName() << declarationType
  10424. << pAttr->getRange();
  10425. result = false;
  10426. }
  10427. break;
  10428. default:
  10429. break;
  10430. }
  10431. }
  10432. if (pNoInterpolation && pAnyLinear) {
  10433. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10434. << pNoInterpolation->getName() << pAnyLinear->getName()
  10435. << declarationType << pNoInterpolation->getRange();
  10436. result = false;
  10437. }
  10438. if (pSample && pCentroid) {
  10439. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  10440. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  10441. }
  10442. if (pCenter && pCentroid) {
  10443. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  10444. << pCenter->getName() << pCentroid->getName() << pCenter->getRange();
  10445. }
  10446. if (pSample && pCenter) {
  10447. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  10448. << pCenter->getName() << pSample->getName() << pCenter->getRange();
  10449. }
  10450. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  10451. pNoInterpolation ? pNoInterpolation : pTopology);
  10452. if (pUniform && pNonUniformAttr) {
  10453. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10454. << pNonUniformAttr->getName()
  10455. << pUniform->getName() << declarationType << pUniform->getRange();
  10456. result = false;
  10457. }
  10458. if (pAnyLinear && pTopology) {
  10459. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  10460. << pTopology->getName()
  10461. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  10462. result = false;
  10463. }
  10464. if (pNoInterpolation && pTopology) {
  10465. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10466. << pTopology->getName()
  10467. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  10468. result = false;
  10469. }
  10470. if (pUniform && pUsage) {
  10471. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  10472. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10473. << pUsage->getName() << pUniform->getName() << declarationType
  10474. << pUniform->getRange();
  10475. result = false;
  10476. }
  10477. }
  10478. // Validate that stream-ouput objects are marked as inout
  10479. if (isParameter && !(usageIn && usageOut) &&
  10480. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  10481. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  10482. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  10483. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  10484. result = false;
  10485. }
  10486. // SPIRV change starts
  10487. #ifdef ENABLE_SPIRV_CODEGEN
  10488. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  10489. if (!getLangOpts().SPIRV) {
  10490. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  10491. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  10492. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  10493. << g_ArBasicTypeNames[basicKind];
  10494. result = false;
  10495. }
  10496. }
  10497. #endif // ENABLE_SPIRV_CODEGEN
  10498. // SPIRV change ends
  10499. // Disallow bitfields
  10500. if (BitWidth) {
  10501. Diag(BitWidth->getExprLoc(), diag::err_hlsl_bitfields);
  10502. result = false;
  10503. }
  10504. // Validate unusual annotations.
  10505. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  10506. auto && unusualIter = D.UnusualAnnotations.begin();
  10507. auto && unusualEnd = D.UnusualAnnotations.end();
  10508. for (; unusualIter != unusualEnd; ++unusualIter) {
  10509. switch ((*unusualIter)->getKind()) {
  10510. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10511. hlsl::ConstantPacking *constantPacking =
  10512. cast<hlsl::ConstantPacking>(*unusualIter);
  10513. if (!isGlobal || HLSLBuffers.size() == 0) {
  10514. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  10515. continue;
  10516. }
  10517. if (constantPacking->ComponentOffset > 0) {
  10518. // Validate that this will fit.
  10519. if (!qt.isNull()) {
  10520. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  10521. constantPacking->ComponentOffset);
  10522. }
  10523. }
  10524. break;
  10525. }
  10526. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10527. hlsl::RegisterAssignment *registerAssignment =
  10528. cast<hlsl::RegisterAssignment>(*unusualIter);
  10529. if (registerAssignment->IsValid) {
  10530. if (!qt.isNull()) {
  10531. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  10532. registerAssignment->RegisterType);
  10533. }
  10534. }
  10535. break;
  10536. }
  10537. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10538. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  10539. if (isTypedef || isLocalVar) {
  10540. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  10541. << "semantic" << declarationType;
  10542. }
  10543. break;
  10544. }
  10545. }
  10546. }
  10547. if (!result) {
  10548. D.setInvalidType();
  10549. }
  10550. return result;
  10551. }
  10552. // Diagnose HLSL types on lookup
  10553. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  10554. const DeclarationNameInfo declName = R.getLookupNameInfo();
  10555. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  10556. if (idInfo) {
  10557. StringRef nameIdentifier = idInfo->getName();
  10558. HLSLScalarType parsedType;
  10559. int rowCount, colCount;
  10560. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  10561. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  10562. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  10563. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  10564. }
  10565. }
  10566. return true;
  10567. }
  10568. static QualType getUnderlyingType(QualType Type)
  10569. {
  10570. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  10571. {
  10572. if (const TypedefNameDecl* pDecl = TD->getDecl())
  10573. Type = pDecl->getUnderlyingType();
  10574. else
  10575. break;
  10576. }
  10577. return Type;
  10578. }
  10579. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  10580. /// <param name="self">Sema with context.</param>
  10581. /// <param name="type">QualType to inspect.</param>
  10582. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  10583. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  10584. void hlsl::GetHLSLAttributedTypes(
  10585. _In_ clang::Sema* self,
  10586. clang::QualType type,
  10587. _Inout_opt_ const clang::AttributedType** ppMatrixOrientation,
  10588. _Inout_opt_ const clang::AttributedType** ppNorm)
  10589. {
  10590. if (ppMatrixOrientation)
  10591. *ppMatrixOrientation = nullptr;
  10592. if (ppNorm)
  10593. *ppNorm = nullptr;
  10594. // Note: we clear output pointers once set so we can stop searching
  10595. QualType Desugared = getUnderlyingType(type);
  10596. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  10597. while (AT && (ppMatrixOrientation || ppNorm)) {
  10598. AttributedType::Kind Kind = AT->getAttrKind();
  10599. if (Kind == AttributedType::attr_hlsl_row_major ||
  10600. Kind == AttributedType::attr_hlsl_column_major)
  10601. {
  10602. if (ppMatrixOrientation)
  10603. {
  10604. *ppMatrixOrientation = AT;
  10605. ppMatrixOrientation = nullptr;
  10606. }
  10607. }
  10608. else if (Kind == AttributedType::attr_hlsl_unorm ||
  10609. Kind == AttributedType::attr_hlsl_snorm)
  10610. {
  10611. if (ppNorm)
  10612. {
  10613. *ppNorm = AT;
  10614. ppNorm = nullptr;
  10615. }
  10616. }
  10617. Desugared = getUnderlyingType(AT->getEquivalentType());
  10618. AT = dyn_cast<AttributedType>(Desugared);
  10619. }
  10620. // Unwrap component type on vector or matrix and check snorm/unorm
  10621. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  10622. AT = dyn_cast<AttributedType>(Desugared);
  10623. while (AT && ppNorm) {
  10624. AttributedType::Kind Kind = AT->getAttrKind();
  10625. if (Kind == AttributedType::attr_hlsl_unorm ||
  10626. Kind == AttributedType::attr_hlsl_snorm)
  10627. {
  10628. *ppNorm = AT;
  10629. ppNorm = nullptr;
  10630. }
  10631. Desugared = getUnderlyingType(AT->getEquivalentType());
  10632. AT = dyn_cast<AttributedType>(Desugared);
  10633. }
  10634. }
  10635. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  10636. /// <param name="self">Sema with context.</param>
  10637. /// <param name="type">QualType to check.</param>
  10638. bool hlsl::IsMatrixType(
  10639. _In_ clang::Sema* self,
  10640. _In_ clang::QualType type)
  10641. {
  10642. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  10643. }
  10644. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  10645. /// <param name="self">Sema with context.</param>
  10646. /// <param name="type">QualType to check.</param>
  10647. bool hlsl::IsVectorType(
  10648. _In_ clang::Sema* self,
  10649. _In_ clang::QualType type)
  10650. {
  10651. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  10652. }
  10653. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  10654. /// <param name="self">Sema with context.</param>
  10655. /// <param name="type">Matrix or Vector type.</param>
  10656. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  10657. _In_ clang::QualType type)
  10658. {
  10659. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  10660. // without losing the AttributedType on the template parameter
  10661. if (const Type* pType = type.getTypePtrOrNull()) {
  10662. // A non-dependent template specialization type is always "sugar",
  10663. // typically for a RecordType. For example, a class template
  10664. // specialization type of @c vector<int> will refer to a tag type for
  10665. // the instantiation @c std::vector<int, std::allocator<int>>.
  10666. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  10667. // If we have enough arguments, pull them from the template directly, rather than doing
  10668. // the extra lookups.
  10669. if (pTemplate->getNumArgs() > 0)
  10670. return pTemplate->getArg(0).getAsType();
  10671. QualType templateRecord = pTemplate->desugar();
  10672. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  10673. if (pTemplateRecordType) {
  10674. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  10675. if (pTemplateTagType) {
  10676. const ClassTemplateSpecializationDecl *specializationDecl =
  10677. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  10678. pTemplateTagType->getDecl());
  10679. if (specializationDecl) {
  10680. return specializationDecl->getTemplateArgs()[0].getAsType();
  10681. }
  10682. }
  10683. }
  10684. }
  10685. }
  10686. return QualType();
  10687. }
  10688. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  10689. /// <param name="self">Sema with context.</param>
  10690. /// <param name="type">Input type.</param>
  10691. clang::QualType hlsl::GetOriginalElementType(
  10692. _In_ clang::Sema* self,
  10693. _In_ clang::QualType type)
  10694. {
  10695. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  10696. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  10697. return GetOriginalMatrixOrVectorElementType(type);
  10698. }
  10699. return type;
  10700. }
  10701. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  10702. switch (A->getKind()) {
  10703. // Parameter modifiers
  10704. case clang::attr::HLSLIn:
  10705. Out << "in ";
  10706. break;
  10707. case clang::attr::HLSLInOut:
  10708. Out << "inout ";
  10709. break;
  10710. case clang::attr::HLSLOut:
  10711. Out << "out ";
  10712. break;
  10713. // Interpolation modifiers
  10714. case clang::attr::HLSLLinear:
  10715. Out << "linear ";
  10716. break;
  10717. case clang::attr::HLSLCenter:
  10718. Out << "center ";
  10719. break;
  10720. case clang::attr::HLSLCentroid:
  10721. Out << "centroid ";
  10722. break;
  10723. case clang::attr::HLSLNoInterpolation:
  10724. Out << "nointerpolation ";
  10725. break;
  10726. case clang::attr::HLSLNoPerspective:
  10727. Out << "noperspective ";
  10728. break;
  10729. case clang::attr::HLSLSample:
  10730. Out << "sample ";
  10731. break;
  10732. // Function attributes
  10733. case clang::attr::HLSLClipPlanes:
  10734. {
  10735. Attr * noconst = const_cast<Attr*>(A);
  10736. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  10737. if (!ACast->getClipPlane1())
  10738. break;
  10739. Indent(Indentation, Out);
  10740. Out << "[clipplanes(";
  10741. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  10742. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  10743. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  10744. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  10745. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  10746. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  10747. Out << ")]\n";
  10748. break;
  10749. }
  10750. case clang::attr::HLSLDomain:
  10751. {
  10752. Attr * noconst = const_cast<Attr*>(A);
  10753. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  10754. Indent(Indentation, Out);
  10755. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  10756. break;
  10757. }
  10758. case clang::attr::HLSLEarlyDepthStencil:
  10759. Indent(Indentation, Out);
  10760. Out << "[earlydepthstencil]\n";
  10761. break;
  10762. case clang::attr::HLSLInstance: //TODO - test
  10763. {
  10764. Attr * noconst = const_cast<Attr*>(A);
  10765. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  10766. Indent(Indentation, Out);
  10767. Out << "[instance(" << ACast->getCount() << ")]\n";
  10768. break;
  10769. }
  10770. case clang::attr::HLSLMaxTessFactor: //TODO - test
  10771. {
  10772. Attr * noconst = const_cast<Attr*>(A);
  10773. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  10774. Indent(Indentation, Out);
  10775. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  10776. break;
  10777. }
  10778. case clang::attr::HLSLNumThreads: //TODO - test
  10779. {
  10780. Attr * noconst = const_cast<Attr*>(A);
  10781. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  10782. Indent(Indentation, Out);
  10783. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  10784. break;
  10785. }
  10786. case clang::attr::HLSLRootSignature:
  10787. {
  10788. Attr * noconst = const_cast<Attr*>(A);
  10789. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  10790. Indent(Indentation, Out);
  10791. Out << "[RootSignature(" << ACast->getSignatureName() << ")]\n";
  10792. break;
  10793. }
  10794. case clang::attr::HLSLOutputControlPoints:
  10795. {
  10796. Attr * noconst = const_cast<Attr*>(A);
  10797. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  10798. Indent(Indentation, Out);
  10799. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  10800. break;
  10801. }
  10802. case clang::attr::HLSLOutputTopology:
  10803. {
  10804. Attr * noconst = const_cast<Attr*>(A);
  10805. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  10806. Indent(Indentation, Out);
  10807. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  10808. break;
  10809. }
  10810. case clang::attr::HLSLPartitioning:
  10811. {
  10812. Attr * noconst = const_cast<Attr*>(A);
  10813. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  10814. Indent(Indentation, Out);
  10815. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  10816. break;
  10817. }
  10818. case clang::attr::HLSLPatchConstantFunc:
  10819. {
  10820. Attr * noconst = const_cast<Attr*>(A);
  10821. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  10822. Indent(Indentation, Out);
  10823. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  10824. break;
  10825. }
  10826. case clang::attr::HLSLShader:
  10827. {
  10828. Attr * noconst = const_cast<Attr*>(A);
  10829. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  10830. Indent(Indentation, Out);
  10831. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  10832. break;
  10833. }
  10834. case clang::attr::HLSLExperimental:
  10835. {
  10836. Attr * noconst = const_cast<Attr*>(A);
  10837. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  10838. Indent(Indentation, Out);
  10839. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  10840. break;
  10841. }
  10842. case clang::attr::HLSLMaxVertexCount:
  10843. {
  10844. Attr * noconst = const_cast<Attr*>(A);
  10845. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  10846. Indent(Indentation, Out);
  10847. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  10848. break;
  10849. }
  10850. case clang::attr::NoInline:
  10851. Indent(Indentation, Out);
  10852. Out << "[noinline]\n";
  10853. break;
  10854. case clang::attr::HLSLExport:
  10855. Indent(Indentation, Out);
  10856. Out << "export\n";
  10857. break;
  10858. // Statement attributes
  10859. case clang::attr::HLSLAllowUAVCondition:
  10860. Indent(Indentation, Out);
  10861. Out << "[allow_uav_condition]\n";
  10862. break;
  10863. case clang::attr::HLSLBranch:
  10864. Indent(Indentation, Out);
  10865. Out << "[branch]\n";
  10866. break;
  10867. case clang::attr::HLSLCall:
  10868. Indent(Indentation, Out);
  10869. Out << "[call]\n";
  10870. break;
  10871. case clang::attr::HLSLFastOpt:
  10872. Indent(Indentation, Out);
  10873. Out << "[fastopt]\n";
  10874. break;
  10875. case clang::attr::HLSLFlatten:
  10876. Indent(Indentation, Out);
  10877. Out << "[flatten]\n";
  10878. break;
  10879. case clang::attr::HLSLForceCase:
  10880. Indent(Indentation, Out);
  10881. Out << "[forcecase]\n";
  10882. break;
  10883. case clang::attr::HLSLLoop:
  10884. Indent(Indentation, Out);
  10885. Out << "[loop]\n";
  10886. break;
  10887. case clang::attr::HLSLUnroll:
  10888. {
  10889. Attr * noconst = const_cast<Attr*>(A);
  10890. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  10891. Indent(Indentation, Out);
  10892. if (ACast->getCount() == 0)
  10893. Out << "[unroll]\n";
  10894. else
  10895. Out << "[unroll(" << ACast->getCount() << ")]\n";
  10896. break;
  10897. }
  10898. // Variable modifiers
  10899. case clang::attr::HLSLGroupShared:
  10900. Out << "groupshared ";
  10901. break;
  10902. case clang::attr::HLSLPrecise:
  10903. Out << "precise ";
  10904. break;
  10905. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  10906. break;
  10907. case clang::attr::HLSLShared:
  10908. Out << "shared ";
  10909. break;
  10910. case clang::attr::HLSLUniform:
  10911. Out << "uniform ";
  10912. break;
  10913. // These four cases are printed in TypePrinter::printAttributedBefore
  10914. case clang::attr::HLSLColumnMajor:
  10915. case clang::attr::HLSLRowMajor:
  10916. case clang::attr::HLSLSnorm:
  10917. case clang::attr::HLSLUnorm:
  10918. break;
  10919. case clang::attr::HLSLPoint:
  10920. Out << "point ";
  10921. break;
  10922. case clang::attr::HLSLLine:
  10923. Out << "line ";
  10924. break;
  10925. case clang::attr::HLSLLineAdj:
  10926. Out << "lineadj ";
  10927. break;
  10928. case clang::attr::HLSLTriangle:
  10929. Out << "triangle ";
  10930. break;
  10931. case clang::attr::HLSLTriangleAdj:
  10932. Out << "triangleadj ";
  10933. break;
  10934. case clang::attr::HLSLGloballyCoherent:
  10935. Out << "globallycoherent ";
  10936. break;
  10937. default:
  10938. A->printPretty(Out, Policy);
  10939. break;
  10940. }
  10941. }
  10942. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  10943. switch (AttrKind){
  10944. case clang::attr::HLSLAllowUAVCondition:
  10945. case clang::attr::HLSLBranch:
  10946. case clang::attr::HLSLCall:
  10947. case clang::attr::HLSLCentroid:
  10948. case clang::attr::HLSLClipPlanes:
  10949. case clang::attr::HLSLColumnMajor:
  10950. case clang::attr::HLSLDomain:
  10951. case clang::attr::HLSLEarlyDepthStencil:
  10952. case clang::attr::HLSLFastOpt:
  10953. case clang::attr::HLSLFlatten:
  10954. case clang::attr::HLSLForceCase:
  10955. case clang::attr::HLSLGroupShared:
  10956. case clang::attr::HLSLIn:
  10957. case clang::attr::HLSLInOut:
  10958. case clang::attr::HLSLInstance:
  10959. case clang::attr::HLSLLinear:
  10960. case clang::attr::HLSLCenter:
  10961. case clang::attr::HLSLLoop:
  10962. case clang::attr::HLSLMaxTessFactor:
  10963. case clang::attr::HLSLNoInterpolation:
  10964. case clang::attr::HLSLNoPerspective:
  10965. case clang::attr::HLSLNumThreads:
  10966. case clang::attr::HLSLRootSignature:
  10967. case clang::attr::HLSLOut:
  10968. case clang::attr::HLSLOutputControlPoints:
  10969. case clang::attr::HLSLOutputTopology:
  10970. case clang::attr::HLSLPartitioning:
  10971. case clang::attr::HLSLPatchConstantFunc:
  10972. case clang::attr::HLSLMaxVertexCount:
  10973. case clang::attr::HLSLPrecise:
  10974. case clang::attr::HLSLRowMajor:
  10975. case clang::attr::HLSLSample:
  10976. case clang::attr::HLSLSemantic:
  10977. case clang::attr::HLSLShared:
  10978. case clang::attr::HLSLSnorm:
  10979. case clang::attr::HLSLUniform:
  10980. case clang::attr::HLSLUnorm:
  10981. case clang::attr::HLSLUnroll:
  10982. case clang::attr::HLSLPoint:
  10983. case clang::attr::HLSLLine:
  10984. case clang::attr::HLSLLineAdj:
  10985. case clang::attr::HLSLTriangle:
  10986. case clang::attr::HLSLTriangleAdj:
  10987. case clang::attr::HLSLGloballyCoherent:
  10988. case clang::attr::NoInline:
  10989. case clang::attr::HLSLExport:
  10990. case clang::attr::VKBinding:
  10991. case clang::attr::VKBuiltIn:
  10992. case clang::attr::VKConstantId:
  10993. case clang::attr::VKCounterBinding:
  10994. case clang::attr::VKIndex:
  10995. case clang::attr::VKInputAttachmentIndex:
  10996. case clang::attr::VKLocation:
  10997. case clang::attr::VKOffset:
  10998. case clang::attr::VKPushConstant:
  10999. return true;
  11000. default:
  11001. // Only HLSL/VK Attributes return true. Only used for printPretty(), which doesn't support them.
  11002. break;
  11003. }
  11004. return false;
  11005. }
  11006. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  11007. if (ClipPlane) {
  11008. Out << ", ";
  11009. ClipPlane->printPretty(Out, 0, Policy);
  11010. }
  11011. }
  11012. bool hlsl::IsObjectType(
  11013. _In_ clang::Sema* self,
  11014. _In_ clang::QualType type,
  11015. _Inout_opt_ bool *isDeprecatedEffectObject)
  11016. {
  11017. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  11018. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  11019. if (isDeprecatedEffectObject)
  11020. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  11021. return true;
  11022. }
  11023. if (isDeprecatedEffectObject)
  11024. *isDeprecatedEffectObject = false;
  11025. return false;
  11026. }
  11027. bool hlsl::CanConvert(
  11028. _In_ clang::Sema* self,
  11029. clang::SourceLocation loc,
  11030. _In_ clang::Expr* sourceExpr,
  11031. clang::QualType target,
  11032. bool explicitConversion,
  11033. _Inout_opt_ clang::StandardConversionSequence* standard)
  11034. {
  11035. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  11036. }
  11037. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  11038. {
  11039. for (unsigned i = 0; i != Indentation; ++i)
  11040. Out << " ";
  11041. }
  11042. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  11043. {
  11044. DXASSERT_NOMSG(self != nullptr);
  11045. DXASSERT_NOMSG(table != nullptr);
  11046. HLSLExternalSource* source = (HLSLExternalSource*)self;
  11047. source->RegisterIntrinsicTable(table);
  11048. }
  11049. clang::QualType hlsl::CheckVectorConditional(
  11050. _In_ clang::Sema* self,
  11051. _In_ clang::ExprResult &Cond,
  11052. _In_ clang::ExprResult &LHS,
  11053. _In_ clang::ExprResult &RHS,
  11054. _In_ clang::SourceLocation QuestionLoc)
  11055. {
  11056. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  11057. }
  11058. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  11059. UINT count;
  11060. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  11061. }
  11062. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  11063. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  11064. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  11065. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  11066. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  11067. llvm::APSInt index;
  11068. if (RHS->EvaluateAsInt(index, Context)) {
  11069. int64_t intIndex = index.getLimitedValue();
  11070. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  11071. if (IsVectorType(this, LHSQualType)) {
  11072. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  11073. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  11074. // we also have to check the first subscript oprator by recursively calling
  11075. // this funciton for the first CXXOperatorCallExpr
  11076. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  11077. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  11078. }
  11079. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  11080. Diag(RHS->getExprLoc(),
  11081. diag::err_hlsl_vector_element_index_out_of_bounds)
  11082. << (int)intIndex;
  11083. }
  11084. }
  11085. else if (IsMatrixType(this, LHSQualType)) {
  11086. uint32_t rowCount, colCount;
  11087. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  11088. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  11089. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  11090. << (int)intIndex;
  11091. }
  11092. }
  11093. }
  11094. }
  11095. clang::QualType ApplyTypeSpecSignToParsedType(
  11096. _In_ clang::Sema* self,
  11097. _In_ clang::QualType &type,
  11098. _In_ clang::TypeSpecifierSign TSS,
  11099. _In_ clang::SourceLocation Loc
  11100. )
  11101. {
  11102. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  11103. }