SemaHLSL.cpp 444 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857
  1. //===--- SemaHLSL.cpp - HLSL support for AST nodes and operations ---===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // SemaHLSL.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This file implements the semantic support for HLSL. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "llvm/ADT/SmallPtrSet.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExternalASTSource.h"
  21. #include "clang/AST/RecursiveASTVisitor.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/AST/HlslTypes.h"
  24. #include "clang/Sema/Overload.h"
  25. #include "clang/Sema/SemaDiagnostic.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/ExternalSemaSource.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/Template.h"
  30. #include "clang/Sema/TemplateDeduction.h"
  31. #include "clang/Sema/SemaHLSL.h"
  32. #include "dxc/Support/Global.h"
  33. #include "dxc/Support/WinIncludes.h"
  34. #include "dxc/Support/WinAdapter.h"
  35. #include "dxc/dxcapi.internal.h"
  36. #include "dxc/HlslIntrinsicOp.h"
  37. #include "gen_intrin_main_tables_15.h"
  38. #include "dxc/HLSL/HLOperations.h"
  39. #include "dxc/DXIL/DxilShaderModel.h"
  40. #include <array>
  41. #include <float.h>
  42. enum ArBasicKind {
  43. AR_BASIC_BOOL,
  44. AR_BASIC_LITERAL_FLOAT,
  45. AR_BASIC_FLOAT16,
  46. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  47. AR_BASIC_FLOAT32,
  48. AR_BASIC_FLOAT64,
  49. AR_BASIC_LITERAL_INT,
  50. AR_BASIC_INT8,
  51. AR_BASIC_UINT8,
  52. AR_BASIC_INT16,
  53. AR_BASIC_UINT16,
  54. AR_BASIC_INT32,
  55. AR_BASIC_UINT32,
  56. AR_BASIC_INT64,
  57. AR_BASIC_UINT64,
  58. AR_BASIC_MIN10FLOAT,
  59. AR_BASIC_MIN16FLOAT,
  60. AR_BASIC_MIN12INT,
  61. AR_BASIC_MIN16INT,
  62. AR_BASIC_MIN16UINT,
  63. AR_BASIC_ENUM,
  64. AR_BASIC_COUNT,
  65. //
  66. // Pseudo-entries for intrinsic tables and such.
  67. //
  68. AR_BASIC_NONE,
  69. AR_BASIC_UNKNOWN,
  70. AR_BASIC_NOCAST,
  71. //
  72. // The following pseudo-entries represent higher-level
  73. // object types that are treated as units.
  74. //
  75. AR_BASIC_POINTER,
  76. AR_BASIC_ENUM_CLASS,
  77. AR_OBJECT_NULL,
  78. AR_OBJECT_STRING_LITERAL,
  79. AR_OBJECT_STRING,
  80. // AR_OBJECT_TEXTURE,
  81. AR_OBJECT_TEXTURE1D,
  82. AR_OBJECT_TEXTURE1D_ARRAY,
  83. AR_OBJECT_TEXTURE2D,
  84. AR_OBJECT_TEXTURE2D_ARRAY,
  85. AR_OBJECT_TEXTURE3D,
  86. AR_OBJECT_TEXTURECUBE,
  87. AR_OBJECT_TEXTURECUBE_ARRAY,
  88. AR_OBJECT_TEXTURE2DMS,
  89. AR_OBJECT_TEXTURE2DMS_ARRAY,
  90. AR_OBJECT_SAMPLER,
  91. AR_OBJECT_SAMPLER1D,
  92. AR_OBJECT_SAMPLER2D,
  93. AR_OBJECT_SAMPLER3D,
  94. AR_OBJECT_SAMPLERCUBE,
  95. AR_OBJECT_SAMPLERCOMPARISON,
  96. AR_OBJECT_BUFFER,
  97. //
  98. // View objects are only used as variable/types within the Effects
  99. // framework, for example in calls to OMSetRenderTargets.
  100. //
  101. AR_OBJECT_RENDERTARGETVIEW,
  102. AR_OBJECT_DEPTHSTENCILVIEW,
  103. //
  104. // Shader objects are only used as variable/types within the Effects
  105. // framework, for example as a result of CompileShader().
  106. //
  107. AR_OBJECT_COMPUTESHADER,
  108. AR_OBJECT_DOMAINSHADER,
  109. AR_OBJECT_GEOMETRYSHADER,
  110. AR_OBJECT_HULLSHADER,
  111. AR_OBJECT_PIXELSHADER,
  112. AR_OBJECT_VERTEXSHADER,
  113. AR_OBJECT_PIXELFRAGMENT,
  114. AR_OBJECT_VERTEXFRAGMENT,
  115. AR_OBJECT_STATEBLOCK,
  116. AR_OBJECT_RASTERIZER,
  117. AR_OBJECT_DEPTHSTENCIL,
  118. AR_OBJECT_BLEND,
  119. AR_OBJECT_POINTSTREAM,
  120. AR_OBJECT_LINESTREAM,
  121. AR_OBJECT_TRIANGLESTREAM,
  122. AR_OBJECT_INPUTPATCH,
  123. AR_OBJECT_OUTPUTPATCH,
  124. AR_OBJECT_RWTEXTURE1D,
  125. AR_OBJECT_RWTEXTURE1D_ARRAY,
  126. AR_OBJECT_RWTEXTURE2D,
  127. AR_OBJECT_RWTEXTURE2D_ARRAY,
  128. AR_OBJECT_RWTEXTURE3D,
  129. AR_OBJECT_RWBUFFER,
  130. AR_OBJECT_BYTEADDRESS_BUFFER,
  131. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  132. AR_OBJECT_STRUCTURED_BUFFER,
  133. AR_OBJECT_RWSTRUCTURED_BUFFER,
  134. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  135. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  136. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  137. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  138. AR_OBJECT_CONSTANT_BUFFER,
  139. AR_OBJECT_TEXTURE_BUFFER,
  140. AR_OBJECT_ROVBUFFER,
  141. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  142. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  143. AR_OBJECT_ROVTEXTURE1D,
  144. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  145. AR_OBJECT_ROVTEXTURE2D,
  146. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  147. AR_OBJECT_ROVTEXTURE3D,
  148. AR_OBJECT_FEEDBACKTEXTURE2D,
  149. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  150. // SPIRV change starts
  151. #ifdef ENABLE_SPIRV_CODEGEN
  152. AR_OBJECT_VK_SUBPASS_INPUT,
  153. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  154. #endif // ENABLE_SPIRV_CODEGEN
  155. // SPIRV change ends
  156. AR_OBJECT_INNER, // Used for internal type object
  157. AR_OBJECT_LEGACY_EFFECT,
  158. AR_OBJECT_WAVE,
  159. AR_OBJECT_RAY_DESC,
  160. AR_OBJECT_ACCELERATION_STRUCT,
  161. AR_OBJECT_USER_DEFINED_TYPE,
  162. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  163. // subobjects
  164. AR_OBJECT_STATE_OBJECT_CONFIG,
  165. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  166. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  167. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  168. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  169. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  170. AR_OBJECT_TRIANGLE_HIT_GROUP,
  171. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  172. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  173. // RayQuery
  174. AR_OBJECT_RAY_QUERY,
  175. // Resource
  176. AR_OBJECT_RESOURCE,
  177. AR_BASIC_MAXIMUM_COUNT
  178. };
  179. #define AR_BASIC_TEXTURE_MS_CASES \
  180. case AR_OBJECT_TEXTURE2DMS: \
  181. case AR_OBJECT_TEXTURE2DMS_ARRAY
  182. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  183. case AR_OBJECT_TEXTURE1D: \
  184. case AR_OBJECT_TEXTURE1D_ARRAY: \
  185. case AR_OBJECT_TEXTURE2D: \
  186. case AR_OBJECT_TEXTURE2D_ARRAY: \
  187. case AR_OBJECT_TEXTURE3D: \
  188. case AR_OBJECT_TEXTURECUBE: \
  189. case AR_OBJECT_TEXTURECUBE_ARRAY
  190. #define AR_BASIC_TEXTURE_CASES \
  191. AR_BASIC_TEXTURE_MS_CASES: \
  192. AR_BASIC_NON_TEXTURE_MS_CASES
  193. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  194. case AR_OBJECT_SAMPLER: \
  195. case AR_OBJECT_SAMPLER1D: \
  196. case AR_OBJECT_SAMPLER2D: \
  197. case AR_OBJECT_SAMPLER3D: \
  198. case AR_OBJECT_SAMPLERCUBE
  199. #define AR_BASIC_ROBJECT_CASES \
  200. case AR_OBJECT_BLEND: \
  201. case AR_OBJECT_RASTERIZER: \
  202. case AR_OBJECT_DEPTHSTENCIL: \
  203. case AR_OBJECT_STATEBLOCK
  204. //
  205. // Properties of entries in the ArBasicKind enumeration.
  206. // These properties are intended to allow easy identification
  207. // of classes of basic kinds. More specific checks on the
  208. // actual kind values could then be done.
  209. //
  210. // The first four bits are used as a subtype indicator,
  211. // such as bit count for primitive kinds or specific
  212. // types for non-primitive-data kinds.
  213. #define BPROP_SUBTYPE_MASK 0x0000000f
  214. // Bit counts must be ordered from smaller to larger.
  215. #define BPROP_BITS0 0x00000000
  216. #define BPROP_BITS8 0x00000001
  217. #define BPROP_BITS10 0x00000002
  218. #define BPROP_BITS12 0x00000003
  219. #define BPROP_BITS16 0x00000004
  220. #define BPROP_BITS32 0x00000005
  221. #define BPROP_BITS64 0x00000006
  222. #define BPROP_BITS_NON_PRIM 0x00000007
  223. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  224. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  225. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  226. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  227. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  228. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  229. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  230. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  231. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  232. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  233. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  234. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  235. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  236. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  237. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  238. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  239. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  240. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  241. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  242. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  243. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  244. #define BPROP_FEEDBACKTEXTURE 0x00800000 // Whether the type is a feedback texture.
  245. #define BPROP_ENUM 0x01000000 // Whether the type is a enum
  246. #define GET_BPROP_PRIM_KIND(_Props) \
  247. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  248. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  249. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  250. #define IS_BPROP_PRIMITIVE(_Props) \
  251. (((_Props) & BPROP_PRIMITIVE) != 0)
  252. #define IS_BPROP_BOOL(_Props) \
  253. (((_Props) & BPROP_BOOLEAN) != 0)
  254. #define IS_BPROP_FLOAT(_Props) \
  255. (((_Props) & BPROP_FLOATING) != 0)
  256. #define IS_BPROP_SINT(_Props) \
  257. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  258. BPROP_INTEGER)
  259. #define IS_BPROP_UINT(_Props) \
  260. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  261. (BPROP_INTEGER | BPROP_UNSIGNED))
  262. #define IS_BPROP_AINT(_Props) \
  263. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  264. #define IS_BPROP_STREAM(_Props) \
  265. (((_Props) & BPROP_STREAM) != 0)
  266. #define IS_BPROP_SAMPLER(_Props) \
  267. (((_Props) & BPROP_SAMPLER) != 0)
  268. #define IS_BPROP_TEXTURE(_Props) \
  269. (((_Props) & BPROP_TEXTURE) != 0)
  270. #define IS_BPROP_OBJECT(_Props) \
  271. (((_Props) & BPROP_OBJECT) != 0)
  272. #define IS_BPROP_MIN_PRECISION(_Props) \
  273. (((_Props) & BPROP_MIN_PRECISION) != 0)
  274. #define IS_BPROP_UNSIGNABLE(_Props) \
  275. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  276. #define IS_BPROP_ENUM(_Props) \
  277. (((_Props) & BPROP_ENUM) != 0)
  278. const UINT g_uBasicKindProps[] =
  279. {
  280. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  281. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  282. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  283. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  284. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  285. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  286. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  287. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  288. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  289. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  290. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  291. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  292. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  293. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  294. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  295. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  296. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  297. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  298. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  299. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  300. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  301. BPROP_OTHER, // AR_BASIC_COUNT
  302. //
  303. // Pseudo-entries for intrinsic tables and such.
  304. //
  305. 0, // AR_BASIC_NONE
  306. BPROP_OTHER, // AR_BASIC_UNKNOWN
  307. BPROP_OTHER, // AR_BASIC_NOCAST
  308. //
  309. // The following pseudo-entries represent higher-level
  310. // object types that are treated as units.
  311. //
  312. BPROP_POINTER, // AR_BASIC_POINTER
  313. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  314. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  315. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING_LITERAL
  316. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  317. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  318. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  319. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  320. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  321. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  322. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  323. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  324. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  325. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  326. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  327. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  328. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  329. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  330. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  331. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  332. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  333. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  334. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  335. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  336. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  337. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  338. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  339. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  340. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  341. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  342. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  343. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  344. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  345. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  346. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  347. BPROP_OBJECT, // AR_OBJECT_BLEND
  348. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  349. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  350. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  351. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  352. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  353. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  354. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  355. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  356. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  357. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  358. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  359. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  360. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  361. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  362. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  363. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  364. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  365. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  366. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  367. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  368. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  369. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  370. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  371. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  372. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  373. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  374. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  375. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  376. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  377. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D
  378. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  379. // SPIRV change starts
  380. #ifdef ENABLE_SPIRV_CODEGEN
  381. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  382. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  383. #endif // ENABLE_SPIRV_CODEGEN
  384. // SPIRV change ends
  385. BPROP_OBJECT, // AR_OBJECT_INNER
  386. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  387. BPROP_OBJECT, // AR_OBJECT_WAVE
  388. LICOMPTYPE_RAYDESC, // AR_OBJECT_RAY_DESC
  389. LICOMPTYPE_ACCELERATION_STRUCT, // AR_OBJECT_ACCELERATION_STRUCT
  390. LICOMPTYPE_USER_DEFINED_TYPE, // AR_OBJECT_USER_DEFINED_TYPE
  391. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  392. // subobjects
  393. 0, //AR_OBJECT_STATE_OBJECT_CONFIG,
  394. 0, //AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  395. 0, //AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  396. 0, //AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  397. 0, //AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  398. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  399. 0, //AR_OBJECT_TRIANGLE_HIT_GROUP,
  400. 0, //AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  401. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  402. 0, //AR_OBJECT_RAY_QUERY,
  403. 0, //AR_OBJECT_RESOURCE,
  404. // AR_BASIC_MAXIMUM_COUNT
  405. };
  406. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  407. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  408. #define GET_BASIC_BITS(_Kind) \
  409. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  410. #define GET_BASIC_PRIM_KIND(_Kind) \
  411. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  412. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  413. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  414. #define IS_BASIC_PRIMITIVE(_Kind) \
  415. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  416. #define IS_BASIC_BOOL(_Kind) \
  417. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  418. #define IS_BASIC_FLOAT(_Kind) \
  419. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  420. #define IS_BASIC_SINT(_Kind) \
  421. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  422. #define IS_BASIC_UINT(_Kind) \
  423. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  424. #define IS_BASIC_AINT(_Kind) \
  425. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  426. #define IS_BASIC_STREAM(_Kind) \
  427. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  428. #define IS_BASIC_SAMPLER(_Kind) \
  429. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  430. #define IS_BASIC_TEXTURE(_Kind) \
  431. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  432. #define IS_BASIC_OBJECT(_Kind) \
  433. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  434. #define IS_BASIC_MIN_PRECISION(_Kind) \
  435. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  436. #define IS_BASIC_UNSIGNABLE(_Kind) \
  437. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  438. #define IS_BASIC_ENUM(_Kind) \
  439. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  440. #define BITWISE_ENUM_OPS(_Type) \
  441. inline _Type operator|(_Type F1, _Type F2) \
  442. { \
  443. return (_Type)((UINT)F1 | (UINT)F2); \
  444. } \
  445. inline _Type operator&(_Type F1, _Type F2) \
  446. { \
  447. return (_Type)((UINT)F1 & (UINT)F2); \
  448. } \
  449. inline _Type& operator|=(_Type& F1, _Type F2) \
  450. { \
  451. F1 = F1 | F2; \
  452. return F1; \
  453. } \
  454. inline _Type& operator&=(_Type& F1, _Type F2) \
  455. { \
  456. F1 = F1 & F2; \
  457. return F1; \
  458. } \
  459. inline _Type& operator&=(_Type& F1, UINT F2) \
  460. { \
  461. F1 = (_Type)((UINT)F1 & F2); \
  462. return F1; \
  463. }
  464. enum ArTypeObjectKind {
  465. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  466. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  467. AR_TOBJ_BASIC, // Represents a primitive type.
  468. AR_TOBJ_COMPOUND, // Represents a struct or class.
  469. AR_TOBJ_INTERFACE, // Represents an interface.
  470. AR_TOBJ_POINTER, // Represents a pointer to another type.
  471. AR_TOBJ_OBJECT, // Represents a built-in object.
  472. AR_TOBJ_ARRAY, // Represents an array of other types.
  473. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  474. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  475. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  476. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  477. // indexer object used to implement .mips[1].
  478. AR_TOBJ_STRING, // Represents a string
  479. };
  480. enum TYPE_CONVERSION_FLAGS
  481. {
  482. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  483. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  484. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  485. };
  486. enum TYPE_CONVERSION_REMARKS
  487. {
  488. TYPE_CONVERSION_NONE = 0x00000000,
  489. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  490. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  491. TYPE_CONVERSION_TO_VOID = 0x00000004,
  492. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  493. };
  494. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  495. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  496. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  497. #define AR_TPROP_VOID 0x0000000000000001
  498. #define AR_TPROP_CONST 0x0000000000000002
  499. #define AR_TPROP_IMP_CONST 0x0000000000000004
  500. #define AR_TPROP_OBJECT 0x0000000000000008
  501. #define AR_TPROP_SCALAR 0x0000000000000010
  502. #define AR_TPROP_UNSIGNED 0x0000000000000020
  503. #define AR_TPROP_NUMERIC 0x0000000000000040
  504. #define AR_TPROP_INTEGRAL 0x0000000000000080
  505. #define AR_TPROP_FLOATING 0x0000000000000100
  506. #define AR_TPROP_LITERAL 0x0000000000000200
  507. #define AR_TPROP_POINTER 0x0000000000000400
  508. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  509. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  510. #define AR_TPROP_INH_IFACE 0x0000000000002000
  511. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  512. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  513. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  514. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  515. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  516. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  517. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  518. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  519. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  520. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  521. #define AR_TPROP_INDEXABLE 0x0000000001000000
  522. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  523. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  524. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  525. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  526. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  527. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  528. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  529. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  530. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  531. #define AR_TPROP_ALL 0xffffffffffffffff
  532. #define AR_TPROP_HAS_OBJECTS \
  533. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  534. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  535. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  536. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  537. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  538. #define AR_TPROP_HAS_BASIC_RESOURCES \
  539. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  540. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  541. AR_TPROP_HAS_UAVS)
  542. #define AR_TPROP_UNION_BITS \
  543. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  544. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  545. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  546. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  547. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  548. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  549. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  550. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  551. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  552. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  553. #define AR_TINFO_PACK_SCALAR 0x00000010
  554. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  555. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  556. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  557. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  558. #define AR_TINFO_PACK_CBUFFER 0
  559. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  560. #define AR_TINFO_SIMPLE_OBJECTS \
  561. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  562. struct ArTypeInfo {
  563. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  564. ArBasicKind EltKind; // The primitive type of elements in this type.
  565. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  566. UINT uRows;
  567. UINT uCols;
  568. UINT uTotalElts;
  569. };
  570. using namespace clang;
  571. using namespace clang::sema;
  572. using namespace hlsl;
  573. extern const char *HLSLScalarTypeNames[];
  574. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  575. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  576. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  577. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  578. static const SourceLocation NoLoc; // no source location attribution available
  579. static const SourceRange NoRange; // no source range attribution available
  580. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  581. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  582. static const bool IsConstexprFalse = false; // function is not constexpr
  583. static const bool ListInitializationFalse = false;// not performing a list initialization
  584. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  585. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  586. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  587. static const int OneRow = 1; // a single row for a type
  588. static const bool MipsFalse = false; // a type does not support the .mips member
  589. static const bool MipsTrue = true; // a type supports the .mips member
  590. static const bool SampleFalse = false; // a type does not support the .sample member
  591. static const bool SampleTrue = true; // a type supports the .sample member
  592. static const size_t MaxVectorSize = 4; // maximum size for a vector
  593. static
  594. QualType GetOrCreateTemplateSpecialization(
  595. ASTContext& context,
  596. Sema& sema,
  597. _In_ ClassTemplateDecl* templateDecl,
  598. ArrayRef<TemplateArgument> templateArgs
  599. )
  600. {
  601. DXASSERT_NOMSG(templateDecl);
  602. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  603. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  604. for (const TemplateArgument& Arg : templateArgs) {
  605. if (Arg.getKind() == TemplateArgument::Type) {
  606. // the class template need to use CanonicalType
  607. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  608. }else
  609. templateArgsForDecl.emplace_back(Arg);
  610. }
  611. // First, try looking up existing specialization
  612. void* InsertPos = nullptr;
  613. ClassTemplateSpecializationDecl* specializationDecl =
  614. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  615. if (specializationDecl) {
  616. // Instantiate the class template if not yet.
  617. if (specializationDecl->getInstantiatedFrom().isNull()) {
  618. // InstantiateClassTemplateSpecialization returns true if it finds an
  619. // error.
  620. DXVERIFY_NOMSG(false ==
  621. sema.InstantiateClassTemplateSpecialization(
  622. NoLoc, specializationDecl,
  623. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  624. true));
  625. }
  626. return context.getTemplateSpecializationType(
  627. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  628. context.getTypeDeclType(specializationDecl));
  629. }
  630. specializationDecl = ClassTemplateSpecializationDecl::Create(
  631. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  632. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  633. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  634. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  635. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  636. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  637. specializationDecl->setImplicit(true);
  638. QualType canonType = context.getTypeDeclType(specializationDecl);
  639. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  640. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  641. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  642. for (unsigned i = 0; i < templateArgs.size(); i++) {
  643. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  644. }
  645. return context.getTemplateSpecializationType(
  646. TemplateName(templateDecl), templateArgumentList, canonType);
  647. }
  648. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  649. static
  650. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  651. _In_ ClassTemplateDecl* matrixTemplateDecl,
  652. QualType elementType, uint64_t rowCount, uint64_t colCount)
  653. {
  654. DXASSERT_NOMSG(sema);
  655. TemplateArgument templateArgs[3] = {
  656. TemplateArgument(elementType),
  657. TemplateArgument(
  658. context,
  659. llvm::APSInt(
  660. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  661. context.IntTy),
  662. TemplateArgument(
  663. context,
  664. llvm::APSInt(
  665. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  666. context.IntTy)};
  667. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  668. #ifdef DBG
  669. // Verify that we can read the field member from the template record.
  670. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  671. "type of non-dependent specialization is not a RecordType");
  672. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  673. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  674. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  675. #endif
  676. return matrixSpecializationType;
  677. }
  678. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  679. static
  680. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  681. _In_ ClassTemplateDecl* vectorTemplateDecl,
  682. QualType elementType, uint64_t colCount)
  683. {
  684. DXASSERT_NOMSG(sema);
  685. DXASSERT_NOMSG(vectorTemplateDecl);
  686. TemplateArgument templateArgs[2] = {
  687. TemplateArgument(elementType),
  688. TemplateArgument(
  689. context,
  690. llvm::APSInt(
  691. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  692. context.IntTy)};
  693. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  694. #ifdef DBG
  695. // Verify that we can read the field member from the template record.
  696. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  697. "type of non-dependent specialization is not a RecordType");
  698. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  699. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  700. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  701. #endif
  702. return vectorSpecializationType;
  703. }
  704. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  705. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  706. static const unsigned kAtomicDstOperandIdx = 1;
  707. static const ArTypeObjectKind g_ScalarTT[] =
  708. {
  709. AR_TOBJ_SCALAR,
  710. AR_TOBJ_UNKNOWN
  711. };
  712. static const ArTypeObjectKind g_VectorTT[] =
  713. {
  714. AR_TOBJ_VECTOR,
  715. AR_TOBJ_UNKNOWN
  716. };
  717. static const ArTypeObjectKind g_MatrixTT[] =
  718. {
  719. AR_TOBJ_MATRIX,
  720. AR_TOBJ_UNKNOWN
  721. };
  722. static const ArTypeObjectKind g_AnyTT[] =
  723. {
  724. AR_TOBJ_SCALAR,
  725. AR_TOBJ_VECTOR,
  726. AR_TOBJ_MATRIX,
  727. AR_TOBJ_UNKNOWN
  728. };
  729. static const ArTypeObjectKind g_ObjectTT[] =
  730. {
  731. AR_TOBJ_OBJECT,
  732. AR_TOBJ_UNKNOWN
  733. };
  734. static const ArTypeObjectKind g_NullTT[] =
  735. {
  736. AR_TOBJ_VOID,
  737. AR_TOBJ_UNKNOWN
  738. };
  739. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  740. {
  741. g_NullTT,
  742. g_ScalarTT,
  743. g_VectorTT,
  744. g_MatrixTT,
  745. g_AnyTT,
  746. g_ObjectTT,
  747. };
  748. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  749. //
  750. // The first one is used to name the representative group, so make
  751. // sure its name will make sense in error messages.
  752. //
  753. static const ArBasicKind g_BoolCT[] =
  754. {
  755. AR_BASIC_BOOL,
  756. AR_BASIC_UNKNOWN
  757. };
  758. static const ArBasicKind g_IntCT[] =
  759. {
  760. AR_BASIC_INT32,
  761. AR_BASIC_LITERAL_INT,
  762. AR_BASIC_UNKNOWN
  763. };
  764. static const ArBasicKind g_UIntCT[] =
  765. {
  766. AR_BASIC_UINT32,
  767. AR_BASIC_LITERAL_INT,
  768. AR_BASIC_UNKNOWN
  769. };
  770. // We use the first element for default if matching kind is missing in the list.
  771. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  772. static const ArBasicKind g_AnyIntCT[] =
  773. {
  774. AR_BASIC_INT32,
  775. AR_BASIC_INT16,
  776. AR_BASIC_UINT32,
  777. AR_BASIC_UINT16,
  778. AR_BASIC_INT64,
  779. AR_BASIC_UINT64,
  780. AR_BASIC_LITERAL_INT,
  781. AR_BASIC_UNKNOWN
  782. };
  783. static const ArBasicKind g_AnyInt32CT[] =
  784. {
  785. AR_BASIC_INT32,
  786. AR_BASIC_UINT32,
  787. AR_BASIC_LITERAL_INT,
  788. AR_BASIC_UNKNOWN
  789. };
  790. static const ArBasicKind g_UIntOnlyCT[] =
  791. {
  792. AR_BASIC_UINT32,
  793. AR_BASIC_UINT64,
  794. AR_BASIC_LITERAL_INT,
  795. AR_BASIC_NOCAST,
  796. AR_BASIC_UNKNOWN
  797. };
  798. static const ArBasicKind g_FloatCT[] =
  799. {
  800. AR_BASIC_FLOAT32,
  801. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  802. AR_BASIC_LITERAL_FLOAT,
  803. AR_BASIC_UNKNOWN
  804. };
  805. static const ArBasicKind g_AnyFloatCT[] =
  806. {
  807. AR_BASIC_FLOAT32,
  808. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  809. AR_BASIC_FLOAT16,
  810. AR_BASIC_FLOAT64,
  811. AR_BASIC_LITERAL_FLOAT,
  812. AR_BASIC_MIN10FLOAT,
  813. AR_BASIC_MIN16FLOAT,
  814. AR_BASIC_UNKNOWN
  815. };
  816. static const ArBasicKind g_FloatLikeCT[] =
  817. {
  818. AR_BASIC_FLOAT32,
  819. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  820. AR_BASIC_FLOAT16,
  821. AR_BASIC_LITERAL_FLOAT,
  822. AR_BASIC_MIN10FLOAT,
  823. AR_BASIC_MIN16FLOAT,
  824. AR_BASIC_UNKNOWN
  825. };
  826. static const ArBasicKind g_FloatDoubleCT[] =
  827. {
  828. AR_BASIC_FLOAT32,
  829. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  830. AR_BASIC_FLOAT64,
  831. AR_BASIC_LITERAL_FLOAT,
  832. AR_BASIC_UNKNOWN
  833. };
  834. static const ArBasicKind g_DoubleCT[] =
  835. {
  836. AR_BASIC_FLOAT64,
  837. AR_BASIC_LITERAL_FLOAT,
  838. AR_BASIC_UNKNOWN
  839. };
  840. static const ArBasicKind g_DoubleOnlyCT[] =
  841. {
  842. AR_BASIC_FLOAT64,
  843. AR_BASIC_NOCAST,
  844. AR_BASIC_UNKNOWN
  845. };
  846. static const ArBasicKind g_NumericCT[] =
  847. {
  848. AR_BASIC_LITERAL_FLOAT,
  849. AR_BASIC_FLOAT32,
  850. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  851. AR_BASIC_FLOAT16,
  852. AR_BASIC_FLOAT64,
  853. AR_BASIC_MIN10FLOAT,
  854. AR_BASIC_MIN16FLOAT,
  855. AR_BASIC_LITERAL_INT,
  856. AR_BASIC_INT16,
  857. AR_BASIC_INT32,
  858. AR_BASIC_UINT16,
  859. AR_BASIC_UINT32,
  860. AR_BASIC_MIN12INT,
  861. AR_BASIC_MIN16INT,
  862. AR_BASIC_MIN16UINT,
  863. AR_BASIC_INT64,
  864. AR_BASIC_UINT64,
  865. AR_BASIC_UNKNOWN
  866. };
  867. static const ArBasicKind g_Numeric32CT[] =
  868. {
  869. AR_BASIC_LITERAL_FLOAT,
  870. AR_BASIC_FLOAT32,
  871. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  872. AR_BASIC_LITERAL_INT,
  873. AR_BASIC_INT32,
  874. AR_BASIC_UINT32,
  875. AR_BASIC_UNKNOWN
  876. };
  877. static const ArBasicKind g_Numeric32OnlyCT[] =
  878. {
  879. AR_BASIC_LITERAL_FLOAT,
  880. AR_BASIC_FLOAT32,
  881. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  882. AR_BASIC_LITERAL_INT,
  883. AR_BASIC_INT32,
  884. AR_BASIC_UINT32,
  885. AR_BASIC_NOCAST,
  886. AR_BASIC_UNKNOWN
  887. };
  888. static const ArBasicKind g_AnyCT[] =
  889. {
  890. AR_BASIC_LITERAL_FLOAT,
  891. AR_BASIC_FLOAT32,
  892. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  893. AR_BASIC_FLOAT16,
  894. AR_BASIC_FLOAT64,
  895. AR_BASIC_MIN10FLOAT,
  896. AR_BASIC_MIN16FLOAT,
  897. AR_BASIC_LITERAL_INT,
  898. AR_BASIC_INT16,
  899. AR_BASIC_UINT16,
  900. AR_BASIC_INT32,
  901. AR_BASIC_UINT32,
  902. AR_BASIC_MIN12INT,
  903. AR_BASIC_MIN16INT,
  904. AR_BASIC_MIN16UINT,
  905. AR_BASIC_BOOL,
  906. AR_BASIC_INT64,
  907. AR_BASIC_UINT64,
  908. AR_BASIC_UNKNOWN
  909. };
  910. static const ArBasicKind g_Sampler1DCT[] =
  911. {
  912. AR_OBJECT_SAMPLER1D,
  913. AR_BASIC_UNKNOWN
  914. };
  915. static const ArBasicKind g_Sampler2DCT[] =
  916. {
  917. AR_OBJECT_SAMPLER2D,
  918. AR_BASIC_UNKNOWN
  919. };
  920. static const ArBasicKind g_Sampler3DCT[] =
  921. {
  922. AR_OBJECT_SAMPLER3D,
  923. AR_BASIC_UNKNOWN
  924. };
  925. static const ArBasicKind g_SamplerCUBECT[] =
  926. {
  927. AR_OBJECT_SAMPLERCUBE,
  928. AR_BASIC_UNKNOWN
  929. };
  930. static const ArBasicKind g_SamplerCmpCT[] =
  931. {
  932. AR_OBJECT_SAMPLERCOMPARISON,
  933. AR_BASIC_UNKNOWN
  934. };
  935. static const ArBasicKind g_SamplerCT[] =
  936. {
  937. AR_OBJECT_SAMPLER,
  938. AR_BASIC_UNKNOWN
  939. };
  940. static const ArBasicKind g_Texture2DCT[] =
  941. {
  942. AR_OBJECT_TEXTURE2D,
  943. AR_BASIC_UNKNOWN
  944. };
  945. static const ArBasicKind g_Texture2DArrayCT[] =
  946. {
  947. AR_OBJECT_TEXTURE2D_ARRAY,
  948. AR_BASIC_UNKNOWN
  949. };
  950. static const ArBasicKind g_ResourceCT[] = {AR_OBJECT_RESOURCE,
  951. AR_BASIC_UNKNOWN};
  952. static const ArBasicKind g_RayDescCT[] =
  953. {
  954. AR_OBJECT_RAY_DESC,
  955. AR_BASIC_UNKNOWN
  956. };
  957. static const ArBasicKind g_AccelerationStructCT[] =
  958. {
  959. AR_OBJECT_ACCELERATION_STRUCT,
  960. AR_BASIC_UNKNOWN
  961. };
  962. static const ArBasicKind g_UDTCT[] =
  963. {
  964. AR_OBJECT_USER_DEFINED_TYPE,
  965. AR_BASIC_UNKNOWN
  966. };
  967. static const ArBasicKind g_StringCT[] =
  968. {
  969. AR_OBJECT_STRING_LITERAL,
  970. AR_OBJECT_STRING,
  971. AR_BASIC_UNKNOWN
  972. };
  973. static const ArBasicKind g_NullCT[] =
  974. {
  975. AR_OBJECT_NULL,
  976. AR_BASIC_UNKNOWN
  977. };
  978. static const ArBasicKind g_WaveCT[] =
  979. {
  980. AR_OBJECT_WAVE,
  981. AR_BASIC_UNKNOWN
  982. };
  983. static const ArBasicKind g_UInt64CT[] =
  984. {
  985. AR_BASIC_UINT64,
  986. AR_BASIC_UNKNOWN
  987. };
  988. static const ArBasicKind g_Float16CT[] =
  989. {
  990. AR_BASIC_FLOAT16,
  991. AR_BASIC_LITERAL_FLOAT,
  992. AR_BASIC_UNKNOWN
  993. };
  994. static const ArBasicKind g_Int16CT[] =
  995. {
  996. AR_BASIC_INT16,
  997. AR_BASIC_LITERAL_INT,
  998. AR_BASIC_UNKNOWN
  999. };
  1000. static const ArBasicKind g_UInt16CT[] =
  1001. {
  1002. AR_BASIC_UINT16,
  1003. AR_BASIC_LITERAL_INT,
  1004. AR_BASIC_UNKNOWN
  1005. };
  1006. static const ArBasicKind g_Numeric16OnlyCT[] =
  1007. {
  1008. AR_BASIC_FLOAT16,
  1009. AR_BASIC_INT16,
  1010. AR_BASIC_UINT16,
  1011. AR_BASIC_LITERAL_FLOAT,
  1012. AR_BASIC_LITERAL_INT,
  1013. AR_BASIC_NOCAST,
  1014. AR_BASIC_UNKNOWN
  1015. };
  1016. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  1017. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  1018. {
  1019. g_NullCT, // LICOMPTYPE_VOID
  1020. g_BoolCT, // LICOMPTYPE_BOOL
  1021. g_IntCT, // LICOMPTYPE_INT
  1022. g_UIntCT, // LICOMPTYPE_UINT
  1023. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  1024. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  1025. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  1026. g_FloatCT, // LICOMPTYPE_FLOAT
  1027. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  1028. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  1029. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  1030. g_DoubleCT, // LICOMPTYPE_DOUBLE
  1031. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  1032. g_NumericCT, // LICOMPTYPE_NUMERIC
  1033. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  1034. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  1035. g_AnyCT, // LICOMPTYPE_ANY
  1036. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  1037. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  1038. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  1039. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  1040. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  1041. g_SamplerCT, // LICOMPTYPE_SAMPLER
  1042. g_StringCT, // LICOMPTYPE_STRING
  1043. g_WaveCT, // LICOMPTYPE_WAVE
  1044. g_UInt64CT, // LICOMPTYPE_UINT64
  1045. g_Float16CT, // LICOMPTYPE_FLOAT16
  1046. g_Int16CT, // LICOMPTYPE_INT16
  1047. g_UInt16CT, // LICOMPTYPE_UINT16
  1048. g_Numeric16OnlyCT, // LICOMPTYPE_NUMERIC16_ONLY
  1049. g_RayDescCT, // LICOMPTYPE_RAYDESC
  1050. g_AccelerationStructCT, // LICOMPTYPE_ACCELERATION_STRUCT,
  1051. g_UDTCT, // LICOMPTYPE_USER_DEFINED_TYPE
  1052. g_Texture2DCT, // LICOMPTYPE_TEXTURE2D
  1053. g_Texture2DArrayCT, // LICOMPTYPE_TEXTURE2DARRAY
  1054. g_ResourceCT, // LICOMPTYPE_RESOURCE
  1055. };
  1056. static_assert(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT,
  1057. "Intrinsic comp type table must be updated when new enumerants are added.");
  1058. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  1059. // Basic kind objects that are represented as HLSL structures or templates.
  1060. static
  1061. const ArBasicKind g_ArBasicKindsAsTypes[] =
  1062. {
  1063. AR_OBJECT_BUFFER, // Buffer
  1064. // AR_OBJECT_TEXTURE,
  1065. AR_OBJECT_TEXTURE1D, // Texture1D
  1066. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1067. AR_OBJECT_TEXTURE2D, // Texture2D
  1068. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1069. AR_OBJECT_TEXTURE3D, // Texture3D
  1070. AR_OBJECT_TEXTURECUBE, // TextureCube
  1071. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1072. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1073. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1074. AR_OBJECT_SAMPLER,
  1075. //AR_OBJECT_SAMPLER1D,
  1076. //AR_OBJECT_SAMPLER2D,
  1077. //AR_OBJECT_SAMPLER3D,
  1078. //AR_OBJECT_SAMPLERCUBE,
  1079. AR_OBJECT_SAMPLERCOMPARISON,
  1080. AR_OBJECT_POINTSTREAM,
  1081. AR_OBJECT_LINESTREAM,
  1082. AR_OBJECT_TRIANGLESTREAM,
  1083. AR_OBJECT_INPUTPATCH,
  1084. AR_OBJECT_OUTPUTPATCH,
  1085. AR_OBJECT_RWTEXTURE1D,
  1086. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1087. AR_OBJECT_RWTEXTURE2D,
  1088. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1089. AR_OBJECT_RWTEXTURE3D,
  1090. AR_OBJECT_RWBUFFER,
  1091. AR_OBJECT_BYTEADDRESS_BUFFER,
  1092. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1093. AR_OBJECT_STRUCTURED_BUFFER,
  1094. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1095. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1096. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1097. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1098. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1099. AR_OBJECT_ROVBUFFER,
  1100. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1101. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1102. AR_OBJECT_ROVTEXTURE1D,
  1103. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1104. AR_OBJECT_ROVTEXTURE2D,
  1105. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1106. AR_OBJECT_ROVTEXTURE3D,
  1107. AR_OBJECT_FEEDBACKTEXTURE2D,
  1108. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  1109. // SPIRV change starts
  1110. #ifdef ENABLE_SPIRV_CODEGEN
  1111. AR_OBJECT_VK_SUBPASS_INPUT,
  1112. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1113. #endif // ENABLE_SPIRV_CODEGEN
  1114. // SPIRV change ends
  1115. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1116. AR_OBJECT_WAVE,
  1117. AR_OBJECT_RAY_DESC,
  1118. AR_OBJECT_ACCELERATION_STRUCT,
  1119. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  1120. // subobjects
  1121. AR_OBJECT_STATE_OBJECT_CONFIG,
  1122. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1123. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1124. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1125. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1126. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1127. AR_OBJECT_TRIANGLE_HIT_GROUP,
  1128. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1129. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1130. AR_OBJECT_RAY_QUERY,
  1131. AR_OBJECT_RESOURCE,
  1132. };
  1133. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1134. static
  1135. const uint8_t g_ArBasicKindsTemplateCount[] =
  1136. {
  1137. 1, // AR_OBJECT_BUFFER
  1138. // AR_OBJECT_TEXTURE,
  1139. 1, // AR_OBJECT_TEXTURE1D
  1140. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1141. 1, // AR_OBJECT_TEXTURE2D
  1142. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1143. 1, // AR_OBJECT_TEXTURE3D
  1144. 1, // AR_OBJECT_TEXTURECUBE
  1145. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1146. 2, // AR_OBJECT_TEXTURE2DMS
  1147. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1148. 0, // AR_OBJECT_SAMPLER
  1149. //AR_OBJECT_SAMPLER1D,
  1150. //AR_OBJECT_SAMPLER2D,
  1151. //AR_OBJECT_SAMPLER3D,
  1152. //AR_OBJECT_SAMPLERCUBE,
  1153. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1154. 1, // AR_OBJECT_POINTSTREAM
  1155. 1, // AR_OBJECT_LINESTREAM
  1156. 1, // AR_OBJECT_TRIANGLESTREAM
  1157. 2, // AR_OBJECT_INPUTPATCH
  1158. 2, // AR_OBJECT_OUTPUTPATCH
  1159. 1, // AR_OBJECT_RWTEXTURE1D
  1160. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1161. 1, // AR_OBJECT_RWTEXTURE2D
  1162. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1163. 1, // AR_OBJECT_RWTEXTURE3D
  1164. 1, // AR_OBJECT_RWBUFFER
  1165. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1166. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1167. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1168. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1169. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1170. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1171. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1172. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1173. 1, // AR_OBJECT_ROVBUFFER
  1174. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1175. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1176. 1, // AR_OBJECT_ROVTEXTURE1D
  1177. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1178. 1, // AR_OBJECT_ROVTEXTURE2D
  1179. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1180. 1, // AR_OBJECT_ROVTEXTURE3D
  1181. 1, // AR_OBJECT_FEEDBACKTEXTURE2D
  1182. 1, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1183. // SPIRV change starts
  1184. #ifdef ENABLE_SPIRV_CODEGEN
  1185. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1186. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1187. #endif // ENABLE_SPIRV_CODEGEN
  1188. // SPIRV change ends
  1189. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1190. 0, // AR_OBJECT_WAVE
  1191. 0, // AR_OBJECT_RAY_DESC
  1192. 0, // AR_OBJECT_ACCELERATION_STRUCT
  1193. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1194. 0, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1195. 0, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1196. 0, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1197. 0, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1198. 0, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1199. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1200. 0, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1201. 0, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1202. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1203. 1, // AR_OBJECT_RAY_QUERY,
  1204. 0, // AR_OBJECT_RESOURCE,
  1205. };
  1206. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1207. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1208. struct SubscriptOperatorRecord
  1209. {
  1210. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1211. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1212. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1213. };
  1214. // Subscript operators for objects that are represented as HLSL structures or templates.
  1215. static
  1216. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1217. {
  1218. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1219. // AR_OBJECT_TEXTURE,
  1220. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1221. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1222. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1223. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1224. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1225. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1226. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1227. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1228. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1229. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1230. //AR_OBJECT_SAMPLER1D,
  1231. //AR_OBJECT_SAMPLER2D,
  1232. //AR_OBJECT_SAMPLER3D,
  1233. //AR_OBJECT_SAMPLERCUBE,
  1234. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1235. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1236. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1237. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1238. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1239. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1240. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1241. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1242. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1243. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1244. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1245. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1246. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1247. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1248. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1249. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1250. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1251. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1252. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1253. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1254. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1255. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1256. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1257. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1258. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1259. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1260. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1261. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1262. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D
  1263. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1264. // SPIRV change starts
  1265. #ifdef ENABLE_SPIRV_CODEGEN
  1266. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1267. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1268. #endif // ENABLE_SPIRV_CODEGEN
  1269. // SPIRV change ends
  1270. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1271. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_WAVE
  1272. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_DESC
  1273. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ACCELERATION_STRUCT
  1274. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1275. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1276. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1277. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1278. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1279. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1280. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1281. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1282. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1283. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1284. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_QUERY,
  1285. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RESOURCE,
  1286. };
  1287. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1288. // Type names for ArBasicKind values.
  1289. static
  1290. const char* g_ArBasicTypeNames[] =
  1291. {
  1292. "bool", "float", "half", "half", "float", "double",
  1293. "int", "sbyte", "byte", "short", "ushort",
  1294. "int", "uint", "long", "ulong",
  1295. "min10float", "min16float",
  1296. "min12int", "min16int", "min16uint",
  1297. "enum",
  1298. "<count>",
  1299. "<none>",
  1300. "<unknown>",
  1301. "<nocast>",
  1302. "<pointer>",
  1303. "enum class",
  1304. "null",
  1305. "literal string",
  1306. "string",
  1307. // "texture",
  1308. "Texture1D",
  1309. "Texture1DArray",
  1310. "Texture2D",
  1311. "Texture2DArray",
  1312. "Texture3D",
  1313. "TextureCube",
  1314. "TextureCubeArray",
  1315. "Texture2DMS",
  1316. "Texture2DMSArray",
  1317. "SamplerState",
  1318. "sampler1D",
  1319. "sampler2D",
  1320. "sampler3D",
  1321. "samplerCUBE",
  1322. "SamplerComparisonState",
  1323. "Buffer",
  1324. "RenderTargetView",
  1325. "DepthStencilView",
  1326. "ComputeShader",
  1327. "DomainShader",
  1328. "GeometryShader",
  1329. "HullShader",
  1330. "PixelShader",
  1331. "VertexShader",
  1332. "pixelfragment",
  1333. "vertexfragment",
  1334. "StateBlock",
  1335. "Rasterizer",
  1336. "DepthStencil",
  1337. "Blend",
  1338. "PointStream",
  1339. "LineStream",
  1340. "TriangleStream",
  1341. "InputPatch",
  1342. "OutputPatch",
  1343. "RWTexture1D",
  1344. "RWTexture1DArray",
  1345. "RWTexture2D",
  1346. "RWTexture2DArray",
  1347. "RWTexture3D",
  1348. "RWBuffer",
  1349. "ByteAddressBuffer",
  1350. "RWByteAddressBuffer",
  1351. "StructuredBuffer",
  1352. "RWStructuredBuffer",
  1353. "RWStructuredBuffer(Incrementable)",
  1354. "RWStructuredBuffer(Decrementable)",
  1355. "AppendStructuredBuffer",
  1356. "ConsumeStructuredBuffer",
  1357. "ConstantBuffer",
  1358. "TextureBuffer",
  1359. "RasterizerOrderedBuffer",
  1360. "RasterizerOrderedByteAddressBuffer",
  1361. "RasterizerOrderedStructuredBuffer",
  1362. "RasterizerOrderedTexture1D",
  1363. "RasterizerOrderedTexture1DArray",
  1364. "RasterizerOrderedTexture2D",
  1365. "RasterizerOrderedTexture2DArray",
  1366. "RasterizerOrderedTexture3D",
  1367. "FeedbackTexture2D",
  1368. "FeedbackTexture2DArray",
  1369. // SPIRV change starts
  1370. #ifdef ENABLE_SPIRV_CODEGEN
  1371. "SubpassInput",
  1372. "SubpassInputMS",
  1373. #endif // ENABLE_SPIRV_CODEGEN
  1374. // SPIRV change ends
  1375. "<internal inner type object>",
  1376. "deprecated effect object",
  1377. "wave_t",
  1378. "RayDesc",
  1379. "RaytracingAccelerationStructure",
  1380. "user defined type",
  1381. "BuiltInTriangleIntersectionAttributes",
  1382. // subobjects
  1383. "StateObjectConfig",
  1384. "GlobalRootSignature",
  1385. "LocalRootSignature",
  1386. "SubobjectToExportsAssociation",
  1387. "RaytracingShaderConfig",
  1388. "RaytracingPipelineConfig",
  1389. "TriangleHitGroup",
  1390. "ProceduralPrimitiveHitGroup",
  1391. "RaytracingPipelineConfig1",
  1392. "RayQuery",
  1393. "Resource",
  1394. };
  1395. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1396. static bool IsValidBasicKind(ArBasicKind kind) {
  1397. return kind != AR_BASIC_COUNT &&
  1398. kind != AR_BASIC_NONE &&
  1399. kind != AR_BASIC_UNKNOWN &&
  1400. kind != AR_BASIC_NOCAST &&
  1401. kind != AR_BASIC_POINTER &&
  1402. kind != AR_OBJECT_RENDERTARGETVIEW &&
  1403. kind != AR_OBJECT_DEPTHSTENCILVIEW &&
  1404. kind != AR_OBJECT_COMPUTESHADER &&
  1405. kind != AR_OBJECT_DOMAINSHADER &&
  1406. kind != AR_OBJECT_GEOMETRYSHADER &&
  1407. kind != AR_OBJECT_HULLSHADER &&
  1408. kind != AR_OBJECT_PIXELSHADER &&
  1409. kind != AR_OBJECT_VERTEXSHADER &&
  1410. kind != AR_OBJECT_PIXELFRAGMENT &&
  1411. kind != AR_OBJECT_VERTEXFRAGMENT;
  1412. }
  1413. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1414. #define DXASSERT_VALIDBASICKIND(kind) \
  1415. DXASSERT(IsValidBasicKind(kind), "otherwise caller is using a special flag or an unsupported kind value");
  1416. static
  1417. const char* g_DeprecatedEffectObjectNames[] =
  1418. {
  1419. // These are case insensitive in fxc, but we'll just create two case aliases
  1420. // to capture the majority of cases
  1421. "texture", "Texture",
  1422. "pixelshader", "PixelShader",
  1423. "vertexshader", "VertexShader",
  1424. // These are case sensitive in fxc
  1425. "pixelfragment", // 13
  1426. "vertexfragment", // 14
  1427. "ComputeShader", // 13
  1428. "DomainShader", // 12
  1429. "GeometryShader", // 14
  1430. "HullShader", // 10
  1431. "BlendState", // 10
  1432. "DepthStencilState",// 17
  1433. "DepthStencilView", // 16
  1434. "RasterizerState", // 15
  1435. "RenderTargetView", // 16
  1436. };
  1437. static bool IsVariadicIntrinsicFunction(const HLSL_INTRINSIC *fn) {
  1438. return fn->pArgs[fn->uNumArgs - 1].uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1439. }
  1440. static bool IsVariadicArgument(const HLSL_INTRINSIC_ARGUMENT &arg) {
  1441. return arg.uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1442. }
  1443. static hlsl::ParameterModifier
  1444. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1445. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1446. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1447. }
  1448. if (pArg->qwUsage == AR_QUAL_OUT) {
  1449. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1450. }
  1451. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1452. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1453. }
  1454. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1455. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1456. // The first argument is the return value, which isn't included.
  1457. UINT i = 1, size = paramMods.size();
  1458. for (; i < pIntrinsic->uNumArgs; ++i) {
  1459. // Once we reach varargs we can break out of this loop.
  1460. if (IsVariadicArgument(pIntrinsic->pArgs[i]))
  1461. break;
  1462. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1463. }
  1464. // For variadic functions, any argument not explicitly specified will be
  1465. // considered an input argument.
  1466. if (IsVariadicIntrinsicFunction(pIntrinsic)) {
  1467. for (; i < size; ++i) {
  1468. paramMods.push_back(
  1469. hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In));
  1470. }
  1471. }
  1472. }
  1473. static bool IsAtomicOperation(IntrinsicOp op) {
  1474. switch (op) {
  1475. case IntrinsicOp::IOP_InterlockedAdd:
  1476. case IntrinsicOp::IOP_InterlockedAnd:
  1477. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1478. case IntrinsicOp::IOP_InterlockedCompareStore:
  1479. case IntrinsicOp::IOP_InterlockedExchange:
  1480. case IntrinsicOp::IOP_InterlockedMax:
  1481. case IntrinsicOp::IOP_InterlockedMin:
  1482. case IntrinsicOp::IOP_InterlockedOr:
  1483. case IntrinsicOp::IOP_InterlockedXor:
  1484. case IntrinsicOp::MOP_InterlockedAdd:
  1485. case IntrinsicOp::MOP_InterlockedAnd:
  1486. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1487. case IntrinsicOp::MOP_InterlockedCompareStore:
  1488. case IntrinsicOp::MOP_InterlockedExchange:
  1489. case IntrinsicOp::MOP_InterlockedMax:
  1490. case IntrinsicOp::MOP_InterlockedMin:
  1491. case IntrinsicOp::MOP_InterlockedOr:
  1492. case IntrinsicOp::MOP_InterlockedXor:
  1493. return true;
  1494. default:
  1495. return false;
  1496. }
  1497. }
  1498. static bool IsBuiltinTable(LPCSTR tableName) {
  1499. return tableName == kBuiltinIntrinsicTableName;
  1500. }
  1501. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1502. LPCSTR tableName, LPCSTR lowering,
  1503. const HLSL_INTRINSIC *pIntrinsic) {
  1504. unsigned opcode = (unsigned)pIntrinsic->Op;
  1505. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1506. QualType Ty = FD->getReturnType();
  1507. if (pIntrinsic->iOverloadParamIndex != -1) {
  1508. const FunctionProtoType *FT =
  1509. FD->getFunctionType()->getAs<FunctionProtoType>();
  1510. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1511. // To go thru reference type.
  1512. if (Ty->isReferenceType())
  1513. Ty = Ty.getNonReferenceType();
  1514. }
  1515. // TODO: refine the code for getting element type
  1516. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1517. Ty = VecTy->getElementType();
  1518. }
  1519. // Make sure to use unsigned op when return type is 'unsigned' matrix
  1520. bool isUnsignedMatOp =
  1521. IsHLSLMatType(Ty) && GetHLSLMatElementType(Ty)->isUnsignedIntegerType();
  1522. if (Ty->isUnsignedIntegerType() || isUnsignedMatOp) {
  1523. opcode = hlsl::GetUnsignedOpcode(opcode);
  1524. }
  1525. }
  1526. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1527. if (pIntrinsic->bReadNone)
  1528. FD->addAttr(ConstAttr::CreateImplicit(context));
  1529. if (pIntrinsic->bReadOnly)
  1530. FD->addAttr(PureAttr::CreateImplicit(context));
  1531. if (pIntrinsic->bIsWave)
  1532. FD->addAttr(HLSLWaveSensitiveAttr::CreateImplicit(context));
  1533. }
  1534. static
  1535. FunctionDecl *AddHLSLIntrinsicFunction(
  1536. ASTContext &context, _In_ NamespaceDecl *NS,
  1537. LPCSTR tableName, LPCSTR lowering,
  1538. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1539. std::vector<QualType> *functionArgQualTypesVector)
  1540. {
  1541. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1542. std::vector<QualType> &functionArgQualTypes = *functionArgQualTypesVector;
  1543. const size_t functionArgTypeCount = functionArgQualTypes.size();
  1544. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  1545. DXASSERT(isVariadic || functionArgTypeCount - 1 <= g_MaxIntrinsicParamCount,
  1546. "otherwise g_MaxIntrinsicParamCount should be larger");
  1547. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1548. if (isVariadic) {
  1549. // For variadic functions, the number of arguments is larger than the
  1550. // function declaration signature.
  1551. paramMods.resize(functionArgTypeCount);
  1552. }
  1553. InitParamMods(pIntrinsic, paramMods);
  1554. // Change dest address into reference type for atomic.
  1555. if (IsBuiltinTable(tableName)) {
  1556. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1557. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1558. "else operation was misrecognized");
  1559. functionArgQualTypes[kAtomicDstOperandIdx] =
  1560. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1561. }
  1562. }
  1563. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1564. // Change out/inout param to reference type.
  1565. if (paramMods[i-1].isAnyOut()) {
  1566. QualType Ty = functionArgQualTypes[i];
  1567. // Aggregate type will be indirect param convert to pointer type.
  1568. // Don't need add reference for it.
  1569. if ((!Ty->isArrayType() && !Ty->isRecordType()) ||
  1570. hlsl::IsHLSLVecMatType(Ty)) {
  1571. functionArgQualTypes[i] = context.getLValueReferenceType(Ty);
  1572. }
  1573. }
  1574. }
  1575. IdentifierInfo &functionId = context.Idents.get(
  1576. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1577. DeclarationName functionName(&functionId);
  1578. auto protoInfo = clang::FunctionProtoType::ExtProtoInfo();
  1579. protoInfo.Variadic = isVariadic;
  1580. // functionArgQualTypes first element is the function return type, and
  1581. // function argument types start at index 1.
  1582. const QualType fnReturnType = functionArgQualTypes[0];
  1583. std::vector<QualType> fnArgTypes(functionArgQualTypes.begin() + 1,
  1584. functionArgQualTypes.end());
  1585. QualType functionType =
  1586. context.getFunctionType(fnReturnType, fnArgTypes, protoInfo, paramMods);
  1587. FunctionDecl *functionDecl = FunctionDecl::Create(
  1588. context, currentDeclContext, NoLoc,
  1589. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1590. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1591. currentDeclContext->addDecl(functionDecl);
  1592. functionDecl->setLexicalDeclContext(currentDeclContext);
  1593. // put under hlsl namespace
  1594. functionDecl->setDeclContext(NS);
  1595. // Add intrinsic attribute
  1596. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1597. llvm::SmallVector<ParmVarDecl *, 4> paramDecls;
  1598. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1599. // For variadic functions all non-explicit arguments will have the same
  1600. // name: "..."
  1601. std::string name = i < pIntrinsic->uNumArgs - 1
  1602. ? pIntrinsic->pArgs[i].pName
  1603. : pIntrinsic->pArgs[pIntrinsic->uNumArgs - 1].pName;
  1604. IdentifierInfo &parameterId =
  1605. context.Idents.get(name, tok::TokenKind::identifier);
  1606. ParmVarDecl *paramDecl =
  1607. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1608. functionArgQualTypes[i], nullptr,
  1609. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1610. functionDecl->addDecl(paramDecl);
  1611. paramDecls.push_back(paramDecl);
  1612. }
  1613. functionDecl->setParams(paramDecls);
  1614. functionDecl->setImplicit(true);
  1615. return functionDecl;
  1616. }
  1617. /// <summary>
  1618. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1619. /// </summary>
  1620. static
  1621. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1622. {
  1623. DXASSERT_NOMSG(expr != nullptr);
  1624. expr = expr->IgnoreParens();
  1625. return
  1626. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1627. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1628. }
  1629. /// <summary>
  1630. /// Silences diagnostics for the initialization sequence, typically because they have already
  1631. /// been emitted.
  1632. /// </summary>
  1633. static
  1634. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1635. {
  1636. DXASSERT_NOMSG(initSequence != nullptr);
  1637. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1638. }
  1639. class UsedIntrinsic
  1640. {
  1641. public:
  1642. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1643. {
  1644. // The canonical representations are unique'd in an ASTContext, and so these
  1645. // should be stable.
  1646. return RHS.getTypePtr() - LHS.getTypePtr();
  1647. }
  1648. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1649. {
  1650. // The intrinsics are defined in a single static table, and so should be stable.
  1651. return RHS - LHS;
  1652. }
  1653. int compare(const UsedIntrinsic& other) const
  1654. {
  1655. // Check whether it's the same instance.
  1656. if (this == &other) return 0;
  1657. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1658. if (result != 0) return result;
  1659. // At this point, it's the exact same intrinsic name.
  1660. // Compare the arguments for ordering then.
  1661. DXASSERT(IsVariadicIntrinsicFunction(m_intrinsicSource) ||
  1662. m_args.size() == other.m_args.size(),
  1663. "only variadic intrinsics can be overloaded on argument count");
  1664. // For variadic functions with different number of args, order by number of
  1665. // arguments.
  1666. if (m_args.size() != other.m_args.size())
  1667. return m_args.size() - other.m_args.size();
  1668. for (size_t i = 0; i < m_args.size(); i++) {
  1669. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1670. if (argComparison != 0) return argComparison;
  1671. }
  1672. // Exactly the same.
  1673. return 0;
  1674. }
  1675. public:
  1676. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, llvm::ArrayRef<QualType> args)
  1677. : m_args(args.begin(), args.end()), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1678. {
  1679. }
  1680. void setFunctionDecl(FunctionDecl* value) const
  1681. {
  1682. DXASSERT(value != nullptr, "no reason to clear this out");
  1683. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1684. m_functionDecl = value;
  1685. }
  1686. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1687. bool operator==(const UsedIntrinsic& other) const
  1688. {
  1689. return compare(other) == 0;
  1690. }
  1691. bool operator<(const UsedIntrinsic& other) const
  1692. {
  1693. return compare(other) < 0;
  1694. }
  1695. private:
  1696. std::vector<QualType> m_args;
  1697. const HLSL_INTRINSIC* m_intrinsicSource;
  1698. mutable FunctionDecl* m_functionDecl;
  1699. };
  1700. template <typename T>
  1701. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1702. {
  1703. if (ptr != nullptr)
  1704. {
  1705. *ptr = value;
  1706. }
  1707. }
  1708. static bool CombineBasicTypes(ArBasicKind LeftKind,
  1709. ArBasicKind RightKind,
  1710. _Out_ ArBasicKind* pOutKind)
  1711. {
  1712. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1713. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1714. return false;
  1715. }
  1716. if (LeftKind == RightKind) {
  1717. *pOutKind = LeftKind;
  1718. return true;
  1719. }
  1720. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1721. UINT uRightProps = GetBasicKindProps(RightKind);
  1722. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1723. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1724. UINT uBothFlags = uLeftProps & uRightProps;
  1725. UINT uEitherFlags = uLeftProps | uRightProps;
  1726. // Notes: all numeric types have either BPROP_FLOATING or BPROP_INTEGER (even bool)
  1727. // unsigned only applies to non-literal ints, not bool or enum
  1728. // literals, bool, and enum are all BPROP_BITS0
  1729. if (uBothFlags & BPROP_BOOLEAN) {
  1730. *pOutKind = AR_BASIC_BOOL;
  1731. return true;
  1732. }
  1733. bool bFloatResult = 0 != (uEitherFlags & BPROP_FLOATING);
  1734. if (uBothFlags & BPROP_LITERAL) {
  1735. *pOutKind = bFloatResult ? AR_BASIC_LITERAL_FLOAT : AR_BASIC_LITERAL_INT;
  1736. return true;
  1737. }
  1738. // Starting approximation of result properties:
  1739. // - float if either are float, otherwise int (see Notes above)
  1740. // - min/partial precision if both have same flag
  1741. // - if not float, add unsigned if either is unsigned
  1742. UINT uResultFlags =
  1743. (uBothFlags & (BPROP_INTEGER | BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION)) |
  1744. (uEitherFlags & BPROP_FLOATING) |
  1745. (!bFloatResult ? (uEitherFlags & BPROP_UNSIGNED) : 0);
  1746. // If one is literal/bool/enum, use min/partial precision from the other
  1747. if (uEitherFlags & (BPROP_LITERAL | BPROP_BOOLEAN | BPROP_ENUM)) {
  1748. uResultFlags |= uEitherFlags & (BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION);
  1749. }
  1750. // Now if we have partial precision, we know the result must be half
  1751. if (uResultFlags & BPROP_PARTIAL_PRECISION) {
  1752. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1753. return true;
  1754. }
  1755. // uBits are already initialized to max of either side, so now:
  1756. // if only one is float, get result props from float side
  1757. // min16float + int -> min16float
  1758. // also take min precision from that side
  1759. if (bFloatResult && 0 == (uBothFlags & BPROP_FLOATING)) {
  1760. uResultFlags = (uLeftProps & BPROP_FLOATING) ? uLeftProps : uRightProps;
  1761. uBits = GET_BPROP_BITS(uResultFlags);
  1762. uResultFlags &= ~BPROP_LITERAL;
  1763. }
  1764. bool bMinPrecisionResult = uResultFlags & BPROP_MIN_PRECISION;
  1765. // if uBits is 0 here, upgrade to 32-bits
  1766. // this happens if bool, literal or enum on both sides,
  1767. // or if float came from literal side
  1768. if (uBits == BPROP_BITS0)
  1769. uBits = BPROP_BITS32;
  1770. DXASSERT(uBits != BPROP_BITS0, "CombineBasicTypes: uBits should not be zero at this point");
  1771. DXASSERT(uBits != BPROP_BITS8, "CombineBasicTypes: 8-bit types not supported at this time");
  1772. if (bMinPrecisionResult) {
  1773. DXASSERT(uBits < BPROP_BITS32, "CombineBasicTypes: min-precision result must be less than 32-bits");
  1774. } else {
  1775. DXASSERT(uBits > BPROP_BITS12, "CombineBasicTypes: 10 or 12 bit result must be min precision");
  1776. }
  1777. if (bFloatResult) {
  1778. DXASSERT(uBits != BPROP_BITS12, "CombineBasicTypes: 12-bit result must be int");
  1779. } else {
  1780. DXASSERT(uBits != BPROP_BITS10, "CombineBasicTypes: 10-bit result must be float");
  1781. }
  1782. if (uBits == BPROP_BITS12) {
  1783. DXASSERT(!(uResultFlags & BPROP_UNSIGNED), "CombineBasicTypes: 12-bit result must not be unsigned");
  1784. }
  1785. if (bFloatResult) {
  1786. switch (uBits) {
  1787. case BPROP_BITS10:
  1788. *pOutKind = AR_BASIC_MIN10FLOAT;
  1789. break;
  1790. case BPROP_BITS16:
  1791. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  1792. break;
  1793. case BPROP_BITS32:
  1794. *pOutKind = AR_BASIC_FLOAT32;
  1795. break;
  1796. case BPROP_BITS64:
  1797. *pOutKind = AR_BASIC_FLOAT64;
  1798. break;
  1799. default:
  1800. DXASSERT(false, "Unexpected bit count for float result");
  1801. break;
  1802. }
  1803. } else {
  1804. // int or unsigned int
  1805. switch (uBits) {
  1806. case BPROP_BITS12:
  1807. *pOutKind = AR_BASIC_MIN12INT;
  1808. break;
  1809. case BPROP_BITS16:
  1810. if (uResultFlags & BPROP_UNSIGNED)
  1811. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  1812. else
  1813. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  1814. break;
  1815. case BPROP_BITS32:
  1816. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT32 : AR_BASIC_INT32;
  1817. break;
  1818. case BPROP_BITS64:
  1819. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT64 : AR_BASIC_INT64;
  1820. break;
  1821. default:
  1822. DXASSERT(false, "Unexpected bit count for int result");
  1823. break;
  1824. }
  1825. }
  1826. return true;
  1827. }
  1828. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1829. {
  1830. };
  1831. static
  1832. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1833. {
  1834. DXASSERT_NOMSG(intrinsics != nullptr);
  1835. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1836. switch (kind)
  1837. {
  1838. case AR_OBJECT_TRIANGLESTREAM:
  1839. case AR_OBJECT_POINTSTREAM:
  1840. case AR_OBJECT_LINESTREAM:
  1841. *intrinsics = g_StreamMethods;
  1842. *intrinsicCount = _countof(g_StreamMethods);
  1843. break;
  1844. case AR_OBJECT_TEXTURE1D:
  1845. *intrinsics = g_Texture1DMethods;
  1846. *intrinsicCount = _countof(g_Texture1DMethods);
  1847. break;
  1848. case AR_OBJECT_TEXTURE1D_ARRAY:
  1849. *intrinsics = g_Texture1DArrayMethods;
  1850. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1851. break;
  1852. case AR_OBJECT_TEXTURE2D:
  1853. *intrinsics = g_Texture2DMethods;
  1854. *intrinsicCount = _countof(g_Texture2DMethods);
  1855. break;
  1856. case AR_OBJECT_TEXTURE2DMS:
  1857. *intrinsics = g_Texture2DMSMethods;
  1858. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1859. break;
  1860. case AR_OBJECT_TEXTURE2D_ARRAY:
  1861. *intrinsics = g_Texture2DArrayMethods;
  1862. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1863. break;
  1864. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1865. *intrinsics = g_Texture2DArrayMSMethods;
  1866. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1867. break;
  1868. case AR_OBJECT_TEXTURE3D:
  1869. *intrinsics = g_Texture3DMethods;
  1870. *intrinsicCount = _countof(g_Texture3DMethods);
  1871. break;
  1872. case AR_OBJECT_TEXTURECUBE:
  1873. *intrinsics = g_TextureCUBEMethods;
  1874. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1875. break;
  1876. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1877. *intrinsics = g_TextureCUBEArrayMethods;
  1878. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1879. break;
  1880. case AR_OBJECT_BUFFER:
  1881. *intrinsics = g_BufferMethods;
  1882. *intrinsicCount = _countof(g_BufferMethods);
  1883. break;
  1884. case AR_OBJECT_RWTEXTURE1D:
  1885. case AR_OBJECT_ROVTEXTURE1D:
  1886. *intrinsics = g_RWTexture1DMethods;
  1887. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1888. break;
  1889. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1890. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1891. *intrinsics = g_RWTexture1DArrayMethods;
  1892. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1893. break;
  1894. case AR_OBJECT_RWTEXTURE2D:
  1895. case AR_OBJECT_ROVTEXTURE2D:
  1896. *intrinsics = g_RWTexture2DMethods;
  1897. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1898. break;
  1899. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1900. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1901. *intrinsics = g_RWTexture2DArrayMethods;
  1902. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1903. break;
  1904. case AR_OBJECT_RWTEXTURE3D:
  1905. case AR_OBJECT_ROVTEXTURE3D:
  1906. *intrinsics = g_RWTexture3DMethods;
  1907. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1908. break;
  1909. case AR_OBJECT_FEEDBACKTEXTURE2D:
  1910. *intrinsics = g_FeedbackTexture2DMethods;
  1911. *intrinsicCount = _countof(g_FeedbackTexture2DMethods);
  1912. break;
  1913. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  1914. *intrinsics = g_FeedbackTexture2DArrayMethods;
  1915. *intrinsicCount = _countof(g_FeedbackTexture2DArrayMethods);
  1916. break;
  1917. case AR_OBJECT_RWBUFFER:
  1918. case AR_OBJECT_ROVBUFFER:
  1919. *intrinsics = g_RWBufferMethods;
  1920. *intrinsicCount = _countof(g_RWBufferMethods);
  1921. break;
  1922. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1923. *intrinsics = g_ByteAddressBufferMethods;
  1924. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1925. break;
  1926. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1927. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1928. *intrinsics = g_RWByteAddressBufferMethods;
  1929. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1930. break;
  1931. case AR_OBJECT_STRUCTURED_BUFFER:
  1932. *intrinsics = g_StructuredBufferMethods;
  1933. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1934. break;
  1935. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1936. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1937. *intrinsics = g_RWStructuredBufferMethods;
  1938. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1939. break;
  1940. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1941. *intrinsics = g_AppendStructuredBufferMethods;
  1942. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1943. break;
  1944. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1945. *intrinsics = g_ConsumeStructuredBufferMethods;
  1946. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1947. break;
  1948. case AR_OBJECT_RAY_QUERY:
  1949. *intrinsics = g_RayQueryMethods;
  1950. *intrinsicCount = _countof(g_RayQueryMethods);
  1951. break;
  1952. // SPIRV change starts
  1953. #ifdef ENABLE_SPIRV_CODEGEN
  1954. case AR_OBJECT_VK_SUBPASS_INPUT:
  1955. *intrinsics = g_VkSubpassInputMethods;
  1956. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  1957. break;
  1958. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1959. *intrinsics = g_VkSubpassInputMSMethods;
  1960. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  1961. break;
  1962. #endif // ENABLE_SPIRV_CODEGEN
  1963. // SPIRV change ends
  1964. default:
  1965. *intrinsics = nullptr;
  1966. *intrinsicCount = 0;
  1967. break;
  1968. }
  1969. }
  1970. static
  1971. bool IsRowOrColumnVariable(size_t value)
  1972. {
  1973. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1974. }
  1975. static
  1976. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1977. {
  1978. return
  1979. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1980. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1981. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1982. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1983. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1984. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1985. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1986. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1987. value == LICOMPTYPE_ANY; // any time
  1988. }
  1989. static
  1990. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1991. {
  1992. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1993. }
  1994. static
  1995. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  1996. {
  1997. // Note that LITEMPLATE_OBJECT can accept different types, but it
  1998. // specifies a single 'layout'. In practice, this information is used
  1999. // together with a component type that specifies a single object.
  2000. return value == LITEMPLATE_ANY; // Any layout
  2001. }
  2002. static
  2003. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  2004. {
  2005. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  2006. }
  2007. static
  2008. bool TemplateHasDefaultType(ArBasicKind kind)
  2009. {
  2010. switch (kind) {
  2011. case AR_OBJECT_BUFFER:
  2012. case AR_OBJECT_TEXTURE1D:
  2013. case AR_OBJECT_TEXTURE2D:
  2014. case AR_OBJECT_TEXTURE3D:
  2015. case AR_OBJECT_TEXTURE1D_ARRAY:
  2016. case AR_OBJECT_TEXTURE2D_ARRAY:
  2017. case AR_OBJECT_TEXTURECUBE:
  2018. case AR_OBJECT_TEXTURECUBE_ARRAY:
  2019. // SPIRV change starts
  2020. #ifdef ENABLE_SPIRV_CODEGEN
  2021. case AR_OBJECT_VK_SUBPASS_INPUT:
  2022. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  2023. #endif // ENABLE_SPIRV_CODEGEN
  2024. // SPIRV change ends
  2025. return true;
  2026. default:
  2027. // Objects with default types return true. Everything else is false.
  2028. return false;
  2029. }
  2030. }
  2031. /// <summary>
  2032. /// Use this class to iterate over intrinsic definitions that come from an external source.
  2033. /// </summary>
  2034. class IntrinsicTableDefIter
  2035. {
  2036. private:
  2037. StringRef _typeName;
  2038. StringRef _functionName;
  2039. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  2040. const HLSL_INTRINSIC* _tableIntrinsic;
  2041. UINT64 _tableLookupCookie;
  2042. unsigned _tableIndex;
  2043. unsigned _argCount;
  2044. bool _firstChecked;
  2045. IntrinsicTableDefIter(
  2046. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2047. StringRef typeName,
  2048. StringRef functionName,
  2049. unsigned argCount) :
  2050. _typeName(typeName), _functionName(functionName), _tables(tables),
  2051. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  2052. _argCount(argCount), _firstChecked(false)
  2053. {
  2054. }
  2055. void CheckForIntrinsic() {
  2056. if (_tableIndex >= _tables.size()) {
  2057. return;
  2058. }
  2059. _firstChecked = true;
  2060. // TODO: review this - this will allocate at least once per string
  2061. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  2062. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  2063. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  2064. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  2065. _tableLookupCookie = 0;
  2066. _tableIntrinsic = nullptr;
  2067. }
  2068. }
  2069. void MoveToNext() {
  2070. for (;;) {
  2071. // If we don't have an intrinsic, try the following table.
  2072. if (_firstChecked && _tableIntrinsic == nullptr) {
  2073. _tableIndex++;
  2074. }
  2075. CheckForIntrinsic();
  2076. if (_tableIndex == _tables.size() ||
  2077. (_tableIntrinsic != nullptr &&
  2078. _tableIntrinsic->uNumArgs ==
  2079. (_argCount + 1))) // uNumArgs includes return
  2080. break;
  2081. }
  2082. }
  2083. public:
  2084. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2085. StringRef typeName,
  2086. StringRef functionName,
  2087. unsigned argCount)
  2088. {
  2089. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  2090. return result;
  2091. }
  2092. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  2093. {
  2094. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  2095. result._tableIndex = tables.size();
  2096. return result;
  2097. }
  2098. bool operator!=(const IntrinsicTableDefIter& other)
  2099. {
  2100. if (!_firstChecked) {
  2101. MoveToNext();
  2102. }
  2103. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  2104. }
  2105. const HLSL_INTRINSIC* operator*()
  2106. {
  2107. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  2108. return _tableIntrinsic;
  2109. }
  2110. LPCSTR GetTableName()
  2111. {
  2112. LPCSTR tableName = nullptr;
  2113. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  2114. return nullptr;
  2115. }
  2116. return tableName;
  2117. }
  2118. LPCSTR GetLoweringStrategy()
  2119. {
  2120. LPCSTR lowering = nullptr;
  2121. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  2122. return nullptr;
  2123. }
  2124. return lowering;
  2125. }
  2126. IntrinsicTableDefIter& operator++()
  2127. {
  2128. MoveToNext();
  2129. return *this;
  2130. }
  2131. };
  2132. /// <summary>
  2133. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2134. /// </summary>
  2135. class IntrinsicDefIter
  2136. {
  2137. const HLSL_INTRINSIC* _current;
  2138. const HLSL_INTRINSIC* _end;
  2139. IntrinsicTableDefIter _tableIter;
  2140. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2141. _current(value), _end(end), _tableIter(tableIter)
  2142. { }
  2143. public:
  2144. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2145. {
  2146. return IntrinsicDefIter(start, table + count, tableIter);
  2147. }
  2148. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2149. {
  2150. return IntrinsicDefIter(table + count, table + count, tableIter);
  2151. }
  2152. bool operator!=(const IntrinsicDefIter& other)
  2153. {
  2154. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2155. }
  2156. const HLSL_INTRINSIC* operator*()
  2157. {
  2158. return (_current != _end) ? _current : *_tableIter;
  2159. }
  2160. LPCSTR GetTableName()
  2161. {
  2162. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2163. }
  2164. LPCSTR GetLoweringStrategy()
  2165. {
  2166. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2167. }
  2168. IntrinsicDefIter& operator++()
  2169. {
  2170. if (_current != _end) {
  2171. const HLSL_INTRINSIC* next = _current + 1;
  2172. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2173. _current = next;
  2174. }
  2175. else {
  2176. _current = _end;
  2177. }
  2178. } else {
  2179. ++_tableIter;
  2180. }
  2181. return *this;
  2182. }
  2183. };
  2184. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2185. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2186. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2187. }
  2188. static void CreateSimpleField(clang::ASTContext &context, CXXRecordDecl *recordDecl, StringRef Name,
  2189. QualType Ty, AccessSpecifier access = AccessSpecifier::AS_public) {
  2190. IdentifierInfo &fieldId =
  2191. context.Idents.get(Name, tok::TokenKind::identifier);
  2192. TypeSourceInfo *filedTypeSource = context.getTrivialTypeSourceInfo(Ty, NoLoc);
  2193. const bool MutableFalse = false;
  2194. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  2195. FieldDecl *fieldDecl =
  2196. FieldDecl::Create(context, recordDecl, NoLoc, NoLoc, &fieldId, Ty,
  2197. filedTypeSource, nullptr, MutableFalse, initStyle);
  2198. fieldDecl->setAccess(access);
  2199. fieldDecl->setImplicit(true);
  2200. recordDecl->addDecl(fieldDecl);
  2201. }
  2202. // struct RayDesc
  2203. //{
  2204. // float3 Origin;
  2205. // float TMin;
  2206. // float3 Direction;
  2207. // float TMax;
  2208. //};
  2209. static CXXRecordDecl *CreateRayDescStruct(clang::ASTContext &context,
  2210. QualType float3Ty) {
  2211. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  2212. IdentifierInfo &rayDesc =
  2213. context.Idents.get(StringRef("RayDesc"), tok::TokenKind::identifier);
  2214. CXXRecordDecl *rayDescDecl = CXXRecordDecl::Create(
  2215. context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc,
  2216. &rayDesc, nullptr, DelayTypeCreationTrue);
  2217. rayDescDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2218. rayDescDecl->startDefinition();
  2219. QualType floatTy = context.FloatTy;
  2220. // float3 Origin;
  2221. CreateSimpleField(context, rayDescDecl, "Origin", float3Ty);
  2222. // float TMin;
  2223. CreateSimpleField(context, rayDescDecl, "TMin", floatTy);
  2224. // float3 Direction;
  2225. CreateSimpleField(context, rayDescDecl, "Direction", float3Ty);
  2226. // float TMax;
  2227. CreateSimpleField(context, rayDescDecl, "TMax", floatTy);
  2228. rayDescDecl->completeDefinition();
  2229. // Both declarations need to be present for correct handling.
  2230. currentDeclContext->addDecl(rayDescDecl);
  2231. rayDescDecl->setImplicit(true);
  2232. return rayDescDecl;
  2233. }
  2234. // struct BuiltInTriangleIntersectionAttributes
  2235. // {
  2236. // float2 barycentrics;
  2237. // };
  2238. static CXXRecordDecl *AddBuiltInTriangleIntersectionAttributes(ASTContext& context, QualType baryType) {
  2239. DeclContext *curDC = context.getTranslationUnitDecl();
  2240. IdentifierInfo &attributesId =
  2241. context.Idents.get(StringRef("BuiltInTriangleIntersectionAttributes"),
  2242. tok::TokenKind::identifier);
  2243. CXXRecordDecl *attributesDecl = CXXRecordDecl::Create(
  2244. context, TagTypeKind::TTK_Struct, curDC, NoLoc, NoLoc,
  2245. &attributesId, nullptr, DelayTypeCreationTrue);
  2246. attributesDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2247. attributesDecl->startDefinition();
  2248. // float2 barycentrics;
  2249. CreateSimpleField(context, attributesDecl, "barycentrics", baryType);
  2250. attributesDecl->completeDefinition();
  2251. attributesDecl->setImplicit(true);
  2252. curDC->addDecl(attributesDecl);
  2253. return attributesDecl;
  2254. }
  2255. //
  2256. // Subobjects
  2257. static CXXRecordDecl *StartSubobjectDecl(ASTContext& context, const char *name) {
  2258. IdentifierInfo &id = context.Idents.get(StringRef(name), tok::TokenKind::identifier);
  2259. CXXRecordDecl *decl = CXXRecordDecl::Create( context, TagTypeKind::TTK_Struct,
  2260. context.getTranslationUnitDecl(), NoLoc, NoLoc, &id, nullptr, DelayTypeCreationTrue);
  2261. decl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2262. decl->startDefinition();
  2263. return decl;
  2264. }
  2265. void FinishSubobjectDecl(ASTContext& context, CXXRecordDecl *decl) {
  2266. decl->completeDefinition();
  2267. context.getTranslationUnitDecl()->addDecl(decl);
  2268. decl->setImplicit(true);
  2269. }
  2270. // struct StateObjectConfig
  2271. // {
  2272. // uint32_t Flags;
  2273. // };
  2274. static CXXRecordDecl *CreateSubobjectStateObjectConfig(ASTContext& context) {
  2275. CXXRecordDecl *decl = StartSubobjectDecl(context, "StateObjectConfig");
  2276. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2277. FinishSubobjectDecl(context, decl);
  2278. return decl;
  2279. }
  2280. // struct GlobalRootSignature
  2281. // {
  2282. // string signature;
  2283. // };
  2284. static CXXRecordDecl *CreateSubobjectRootSignature(ASTContext& context, bool global) {
  2285. CXXRecordDecl *decl = StartSubobjectDecl(context, global ? "GlobalRootSignature" : "LocalRootSignature");
  2286. CreateSimpleField(context, decl, "Data", context.HLSLStringTy, AccessSpecifier::AS_private);
  2287. FinishSubobjectDecl(context, decl);
  2288. return decl;
  2289. }
  2290. // struct SubobjectToExportsAssociation
  2291. // {
  2292. // string Subobject;
  2293. // string Exports;
  2294. // };
  2295. static CXXRecordDecl *CreateSubobjectSubobjectToExportsAssoc(ASTContext& context) {
  2296. CXXRecordDecl *decl = StartSubobjectDecl(context, "SubobjectToExportsAssociation");
  2297. CreateSimpleField(context, decl, "Subobject", context.HLSLStringTy, AccessSpecifier::AS_private);
  2298. CreateSimpleField(context, decl, "Exports", context.HLSLStringTy, AccessSpecifier::AS_private);
  2299. FinishSubobjectDecl(context, decl);
  2300. return decl;
  2301. }
  2302. // struct RaytracingShaderConfig
  2303. // {
  2304. // uint32_t MaxPayloadSizeInBytes;
  2305. // uint32_t MaxAttributeSizeInBytes;
  2306. // };
  2307. static CXXRecordDecl *CreateSubobjectRaytracingShaderConfig(ASTContext& context) {
  2308. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingShaderConfig");
  2309. CreateSimpleField(context, decl, "MaxPayloadSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2310. CreateSimpleField(context, decl, "MaxAttributeSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2311. FinishSubobjectDecl(context, decl);
  2312. return decl;
  2313. }
  2314. // struct RaytracingPipelineConfig
  2315. // {
  2316. // uint32_t MaxTraceRecursionDepth;
  2317. // };
  2318. static CXXRecordDecl *CreateSubobjectRaytracingPipelineConfig(ASTContext& context) {
  2319. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingPipelineConfig");
  2320. CreateSimpleField(context, decl, "MaxTraceRecursionDepth", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2321. FinishSubobjectDecl(context, decl);
  2322. return decl;
  2323. }
  2324. // struct RaytracingPipelineConfig1
  2325. // {
  2326. // uint32_t MaxTraceRecursionDepth;
  2327. // uint32_t Flags;
  2328. // };
  2329. static CXXRecordDecl *
  2330. CreateSubobjectRaytracingPipelineConfig1(ASTContext &context) {
  2331. CXXRecordDecl *decl =
  2332. StartSubobjectDecl(context, "RaytracingPipelineConfig1");
  2333. CreateSimpleField(context, decl, "MaxTraceRecursionDepth",
  2334. context.UnsignedIntTy, AccessSpecifier::AS_private);
  2335. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy,
  2336. AccessSpecifier::AS_private);
  2337. FinishSubobjectDecl(context, decl);
  2338. return decl;
  2339. }
  2340. // struct TriangleHitGroup
  2341. // {
  2342. // string AnyHit;
  2343. // string ClosestHit;
  2344. // };
  2345. static CXXRecordDecl *CreateSubobjectTriangleHitGroup(ASTContext& context) {
  2346. CXXRecordDecl *decl = StartSubobjectDecl(context, "TriangleHitGroup");
  2347. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2348. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2349. FinishSubobjectDecl(context, decl);
  2350. return decl;
  2351. }
  2352. // struct ProceduralPrimitiveHitGroup
  2353. // {
  2354. // string AnyHit;
  2355. // string ClosestHit;
  2356. // string Intersection;
  2357. // };
  2358. static CXXRecordDecl *CreateSubobjectProceduralPrimitiveHitGroup(ASTContext& context) {
  2359. CXXRecordDecl *decl = StartSubobjectDecl(context, "ProceduralPrimitiveHitGroup");
  2360. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2361. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2362. CreateSimpleField(context, decl, "Intersection", context.HLSLStringTy, AccessSpecifier::AS_private);
  2363. FinishSubobjectDecl(context, decl);
  2364. return decl;
  2365. }
  2366. //
  2367. // This is similar to clang/Analysis/CallGraph, but the following differences
  2368. // motivate this:
  2369. //
  2370. // - track traversed vs. observed nodes explicitly
  2371. // - fully visit all reachable functions
  2372. // - merge graph visiting with checking for recursion
  2373. // - track global variables and types used (NYI)
  2374. //
  2375. namespace hlsl {
  2376. struct CallNode {
  2377. FunctionDecl *CallerFn;
  2378. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2379. };
  2380. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2381. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2382. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2383. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2384. // Returns the definition of a function.
  2385. // This serves two purposes - ignore built-in functions, and pick
  2386. // a single Decl * to be used in maps and sets.
  2387. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2388. if (!F) return nullptr;
  2389. if (F->doesThisDeclarationHaveABody()) return F;
  2390. F = F->getFirstDecl();
  2391. for (auto &&Candidate : F->redecls()) {
  2392. if (Candidate->doesThisDeclarationHaveABody()) {
  2393. return Candidate;
  2394. }
  2395. }
  2396. return nullptr;
  2397. }
  2398. // AST visitor that maintains visited and pending collections, as well
  2399. // as recording nodes of caller/callees.
  2400. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2401. private:
  2402. CallNodes &m_callNodes;
  2403. FunctionSet &m_visitedFunctions;
  2404. PendingFunctions &m_pendingFunctions;
  2405. FunctionDecl *m_source;
  2406. CallNodes::iterator m_sourceIt;
  2407. public:
  2408. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2409. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2410. : m_callNodes(callNodes),
  2411. m_visitedFunctions(visitedFunctions),
  2412. m_pendingFunctions(pendingFunctions) {}
  2413. void setSourceFn(FunctionDecl *F) {
  2414. F = getFunctionWithBody(F);
  2415. m_source = F;
  2416. m_sourceIt = m_callNodes.find(F);
  2417. }
  2418. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2419. ValueDecl *valueDecl = ref->getDecl();
  2420. RecordFunctionDecl(dyn_cast_or_null<FunctionDecl>(valueDecl));
  2421. return true;
  2422. }
  2423. bool VisitCXXMemberCallExpr(CXXMemberCallExpr* callExpr)
  2424. {
  2425. RecordFunctionDecl(callExpr->getMethodDecl());
  2426. return true;
  2427. }
  2428. void RecordFunctionDecl(FunctionDecl* funcDecl)
  2429. {
  2430. funcDecl = getFunctionWithBody(funcDecl);
  2431. if (funcDecl) {
  2432. if (m_sourceIt == m_callNodes.end()) {
  2433. auto result = m_callNodes.insert(
  2434. std::pair<FunctionDecl*, CallNode>(m_source, CallNode{ m_source }));
  2435. DXASSERT(result.second == true,
  2436. "else setSourceFn didn't assign m_sourceIt");
  2437. m_sourceIt = result.first;
  2438. }
  2439. m_sourceIt->second.CalleeFns.insert(funcDecl);
  2440. if (!m_visitedFunctions.count(funcDecl)) {
  2441. m_pendingFunctions.push_back(funcDecl);
  2442. }
  2443. }
  2444. }
  2445. };
  2446. // A call graph that can check for reachability and recursion efficiently.
  2447. class CallGraphWithRecurseGuard {
  2448. private:
  2449. CallNodes m_callNodes;
  2450. FunctionSet m_visitedFunctions;
  2451. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2452. FunctionDecl *D) const {
  2453. if (CallStack.insert(D).second == false)
  2454. return D;
  2455. auto node = m_callNodes.find(D);
  2456. if (node != m_callNodes.end()) {
  2457. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2458. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2459. if (pResult)
  2460. return pResult;
  2461. }
  2462. }
  2463. CallStack.erase(D);
  2464. return nullptr;
  2465. }
  2466. public:
  2467. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2468. DXASSERT_NOMSG(EntryFnDecl);
  2469. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2470. PendingFunctions pendingFunctions;
  2471. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2472. pendingFunctions.push_back(EntryFnDecl);
  2473. while (!pendingFunctions.empty()) {
  2474. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2475. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2476. visitor.setSourceFn(pendingDecl);
  2477. visitor.TraverseDecl(pendingDecl);
  2478. }
  2479. }
  2480. }
  2481. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2482. FnCallStack CallStack;
  2483. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2484. return CheckRecursion(CallStack, EntryFnDecl);
  2485. }
  2486. void dump() const {
  2487. OutputDebugStringW(L"Call Nodes:\r\n");
  2488. for (auto &node : m_callNodes) {
  2489. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), (void*)node.first);
  2490. for (auto callee : node.second.CalleeFns) {
  2491. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), (void*)callee);
  2492. }
  2493. }
  2494. }
  2495. };
  2496. }
  2497. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2498. static
  2499. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2500. {
  2501. DXASSERT_NOMSG(context != nullptr);
  2502. DXASSERT_NOMSG(ident != nullptr);
  2503. DXASSERT_NOMSG(!baseType.isNull());
  2504. DeclContext* declContext = context->getTranslationUnitDecl();
  2505. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2506. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2507. declContext->addDecl(decl);
  2508. decl->setImplicit(true);
  2509. return decl;
  2510. }
  2511. class HLSLExternalSource : public ExternalSemaSource {
  2512. private:
  2513. // Inner types.
  2514. struct FindStructBasicTypeResult {
  2515. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2516. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2517. FindStructBasicTypeResult(ArBasicKind kind,
  2518. unsigned int basicKindAsTypeIndex)
  2519. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2520. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2521. };
  2522. // Declaration for matrix and vector templates.
  2523. ClassTemplateDecl* m_matrixTemplateDecl;
  2524. ClassTemplateDecl* m_vectorTemplateDecl;
  2525. // Namespace decl for hlsl intrin functions
  2526. NamespaceDecl* m_hlslNSDecl;
  2527. // Context being processed.
  2528. _Notnull_ ASTContext* m_context;
  2529. // Semantic analyzer being processed.
  2530. Sema* m_sema;
  2531. // Intrinsic tables available externally.
  2532. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2533. // Scalar types indexed by HLSLScalarType.
  2534. QualType m_scalarTypes[HLSLScalarTypeCount];
  2535. // Scalar types already built.
  2536. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2537. // 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.
  2538. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2539. // Matrix types already built, in shorthand form.
  2540. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2541. // Vector types already built.
  2542. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2543. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2544. // BuiltinType for each scalar type.
  2545. QualType m_baseTypes[HLSLScalarTypeCount];
  2546. // String type
  2547. QualType m_hlslStringType;
  2548. TypedefDecl* m_hlslStringTypedef;
  2549. // Built-in object types declarations, indexed by basic kind constant.
  2550. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2551. // Map from object decl to the object index.
  2552. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2553. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2554. // Mask for object which not has methods created.
  2555. uint64_t m_objectTypeLazyInitMask;
  2556. UsedIntrinsicStore m_usedIntrinsics;
  2557. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2558. void AddBaseTypes();
  2559. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2560. void AddHLSLScalarTypes();
  2561. /// <summary>Adds string type QualType for HSLS string declarations</summary>
  2562. void AddHLSLStringType();
  2563. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2564. {
  2565. DXASSERT_NOMSG(recordDecl != nullptr);
  2566. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2567. NamedDecl* parameterDecl = parameterList->getParam(0);
  2568. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2569. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2570. return QualType(parmDecl->getTypeForDecl(), 0);
  2571. }
  2572. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2573. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2574. {
  2575. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2576. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2577. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2578. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2579. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2580. if (
  2581. templateRef >= 0 &&
  2582. templateArg->uTemplateId == templateRef &&
  2583. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2584. componentRef >= 0 &&
  2585. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2586. componentArg->uComponentTypeId == 0 &&
  2587. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2588. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2589. !IsRowOrColumnVariable(matrixArg->uRows))
  2590. {
  2591. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2592. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2593. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2594. }
  2595. return QualType();
  2596. }
  2597. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2598. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2599. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2600. _Inout_ size_t* templateParamNamedDeclsCount)
  2601. {
  2602. DXASSERT_NOMSG(name != nullptr);
  2603. DXASSERT_NOMSG(recordDecl != nullptr);
  2604. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2605. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2606. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2607. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2608. // Create the declaration for the template parameter.
  2609. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2610. TemplateTypeParmDecl* templateTypeParmDecl =
  2611. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2612. id, TypenameTrue, ParameterPackFalse);
  2613. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2614. // Create the type that the parameter represents.
  2615. QualType result = m_context->getTemplateTypeParmType(
  2616. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2617. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2618. // it need not concern itself with maintaining this value.
  2619. (*templateParamNamedDeclsCount)++;
  2620. return result;
  2621. }
  2622. // Adds a function specified by the given intrinsic to a record declaration.
  2623. // The template depth will be zero for records that don't have a "template<>" line
  2624. // even if conceptual; or one if it does have one.
  2625. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2626. {
  2627. DXASSERT_NOMSG(recordDecl != nullptr);
  2628. DXASSERT_NOMSG(intrinsic != nullptr);
  2629. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2630. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2631. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2632. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2633. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2634. //
  2635. // Build template parameters, parameter types, and the return type.
  2636. // Parameter declarations are built after the function is created, to use it as their scope.
  2637. //
  2638. unsigned int numParams = intrinsic->uNumArgs - 1;
  2639. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2640. size_t templateParamNamedDeclsCount = 0;
  2641. QualType argsQTs[g_MaxIntrinsicParamCount];
  2642. StringRef argNames[g_MaxIntrinsicParamCount];
  2643. QualType functionResultQT = recordDecl->getASTContext().VoidTy;
  2644. DXASSERT(
  2645. _countof(templateParamNamedDecls) >= numParams + 1,
  2646. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2647. // Handle the return type.
  2648. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2649. // if (functionResultQT.isNull()) {
  2650. // Workaround for template parameter argument count mismatch.
  2651. // Create template parameter for return type always
  2652. // TODO: reenable the check and skip template argument.
  2653. functionResultQT = AddTemplateParamToArray(
  2654. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2655. &templateParamNamedDeclsCount);
  2656. // }
  2657. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2658. InitParamMods(intrinsic, paramMods);
  2659. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2660. // Handle parameters.
  2661. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2662. {
  2663. //
  2664. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2665. //
  2666. // However this may produce template instantiations with equivalent template arguments
  2667. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2668. // but the current intrinsic table has rules that are hard to process in their current form
  2669. // to find all cases.
  2670. //
  2671. char name[g_MaxIntrinsicParamName + 2];
  2672. name[0] = 'T';
  2673. name[1] = '\0';
  2674. strcat_s(name, intrinsic->pArgs[i].pName);
  2675. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2676. // Change out/inout param to reference type.
  2677. if (paramMods[i-1].isAnyOut())
  2678. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2679. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2680. }
  2681. // Create the declaration.
  2682. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2683. DeclarationName declarationName = DeclarationName(ii);
  2684. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2685. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2686. declarationName, true);
  2687. functionDecl->setImplicit(true);
  2688. // If the function is a template function, create the declaration and cross-reference.
  2689. if (templateParamNamedDeclsCount > 0)
  2690. {
  2691. hlsl::CreateFunctionTemplateDecl(
  2692. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2693. }
  2694. }
  2695. // Checks whether the two specified intrinsics generate equivalent templates.
  2696. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2697. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2698. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2699. {
  2700. if (left == right)
  2701. {
  2702. return true;
  2703. }
  2704. if (left == nullptr || right == nullptr)
  2705. {
  2706. return false;
  2707. }
  2708. return (left->uNumArgs == right->uNumArgs &&
  2709. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2710. }
  2711. // Adds all the intrinsic methods that correspond to the specified type.
  2712. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2713. {
  2714. DXASSERT_NOMSG(recordDecl != nullptr);
  2715. DXASSERT_NOMSG(templateDepth >= 0);
  2716. const HLSL_INTRINSIC* intrinsics;
  2717. const HLSL_INTRINSIC* prior = nullptr;
  2718. size_t intrinsicCount;
  2719. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2720. DXASSERT(
  2721. (intrinsics == nullptr) == (intrinsicCount == 0),
  2722. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2723. while (intrinsicCount--)
  2724. {
  2725. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2726. {
  2727. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2728. prior = intrinsics;
  2729. }
  2730. intrinsics++;
  2731. }
  2732. }
  2733. void AddDoubleSubscriptSupport(
  2734. _In_ ClassTemplateDecl* typeDecl,
  2735. _In_ CXXRecordDecl* recordDecl,
  2736. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2737. _In_z_ const char* type0Name,
  2738. _In_z_ const char* type1Name,
  2739. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2740. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2741. {
  2742. DXASSERT_NOMSG(typeDecl != nullptr);
  2743. DXASSERT_NOMSG(recordDecl != nullptr);
  2744. DXASSERT_NOMSG(memberName != nullptr);
  2745. DXASSERT_NOMSG(!elementType.isNull());
  2746. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2747. DXASSERT_NOMSG(type0Name != nullptr);
  2748. DXASSERT_NOMSG(type1Name != nullptr);
  2749. DXASSERT_NOMSG(indexer0Name != nullptr);
  2750. DXASSERT_NOMSG(!indexer0Type.isNull());
  2751. DXASSERT_NOMSG(indexer1Name != nullptr);
  2752. DXASSERT_NOMSG(!indexer1Type.isNull());
  2753. //
  2754. // Add inner types to the templates to represent the following C++ code inside the class.
  2755. // public:
  2756. // class sample_slice_type
  2757. // {
  2758. // public: TElement operator[](uint3 index);
  2759. // };
  2760. // class sample_type
  2761. // {
  2762. // public: sample_slice_type operator[](uint slice);
  2763. // };
  2764. // sample_type sample;
  2765. //
  2766. // Variable names reflect this structure, but this code will also produce the types
  2767. // for .mips access.
  2768. //
  2769. const bool MutableTrue = true;
  2770. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2771. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2772. &m_context->Idents.get(StringRef(type1Name)));
  2773. sampleSliceTypeDecl->setAccess(AS_public);
  2774. sampleSliceTypeDecl->setImplicit();
  2775. recordDecl->addDecl(sampleSliceTypeDecl);
  2776. sampleSliceTypeDecl->startDefinition();
  2777. const bool MutableFalse = false;
  2778. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2779. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2780. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2781. sliceHandleDecl->setAccess(AS_private);
  2782. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2783. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2784. sampleSliceTypeDecl, elementType,
  2785. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2786. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2787. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2788. sampleSliceTypeDecl->completeDefinition();
  2789. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2790. &m_context->Idents.get(StringRef(type0Name)));
  2791. sampleTypeDecl->setAccess(AS_public);
  2792. recordDecl->addDecl(sampleTypeDecl);
  2793. sampleTypeDecl->startDefinition();
  2794. sampleTypeDecl->setImplicit();
  2795. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2796. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2797. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2798. sampleHandleDecl->setAccess(AS_private);
  2799. sampleTypeDecl->addDecl(sampleHandleDecl);
  2800. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2801. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2802. sampleTypeDecl, m_context->getLValueReferenceType(sampleSliceType),
  2803. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2804. sampleTypeDecl->completeDefinition();
  2805. // Add subscript attribute
  2806. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2807. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2808. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2809. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2810. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2811. sampleFieldDecl->setAccess(AS_public);
  2812. recordDecl->addDecl(sampleFieldDecl);
  2813. }
  2814. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2815. _In_ CXXRecordDecl *recordDecl,
  2816. SubscriptOperatorRecord op) {
  2817. DXASSERT_NOMSG(typeDecl != nullptr);
  2818. DXASSERT_NOMSG(recordDecl != nullptr);
  2819. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2820. op.SubscriptCardinality <= 3);
  2821. DXASSERT(op.SubscriptCardinality > 0 ||
  2822. (op.HasMips == false && op.HasSample == false),
  2823. "objects that have .mips or .sample member also have a plain "
  2824. "subscript defined (otherwise static table is "
  2825. "likely incorrect, and this function won't know the cardinality "
  2826. "of the position parameter");
  2827. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2828. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2829. "read/write objects don't have .mips or .sample members");
  2830. // Return early if there is no work to be done.
  2831. if (op.SubscriptCardinality == 0) {
  2832. return;
  2833. }
  2834. const unsigned int templateDepth = 1;
  2835. // Add an operator[].
  2836. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2837. typeDecl->getTemplateParameters()->getParam(0));
  2838. QualType resultType = m_context->getTemplateTypeParmType(
  2839. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2840. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  2841. resultType = m_context->getLValueReferenceType(resultType);
  2842. QualType indexType =
  2843. op.SubscriptCardinality == 1
  2844. ? m_context->UnsignedIntTy
  2845. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2846. op.SubscriptCardinality);
  2847. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2848. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2849. ArrayRef<StringRef>(StringRef("index")),
  2850. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2851. hlsl::CreateFunctionTemplateDecl(
  2852. *m_context, recordDecl, functionDecl,
  2853. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2854. // Add a .mips member if necessary.
  2855. QualType uintType = m_context->UnsignedIntTy;
  2856. if (op.HasMips) {
  2857. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2858. templateTypeParmDecl, "mips_type",
  2859. "mips_slice_type", "mipSlice", uintType, "pos",
  2860. indexType);
  2861. }
  2862. // Add a .sample member if necessary.
  2863. if (op.HasSample) {
  2864. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2865. templateTypeParmDecl, "sample_type",
  2866. "sample_slice_type", "sampleSlice", uintType,
  2867. "pos", indexType);
  2868. // TODO: support operator[][](indexType, uint).
  2869. }
  2870. }
  2871. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2872. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2873. return a.first < b.first;
  2874. };
  2875. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2876. auto begin = m_objectTypeDeclsMap.begin();
  2877. auto end = m_objectTypeDeclsMap.end();
  2878. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2879. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2880. if (low == end)
  2881. return -1;
  2882. if (recordDecl == low->first)
  2883. return low->second;
  2884. else
  2885. return -1;
  2886. }
  2887. // Adds all built-in HLSL object types.
  2888. void AddObjectTypes()
  2889. {
  2890. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2891. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2892. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2893. m_objectTypeLazyInitMask = 0;
  2894. unsigned effectKindIndex = 0;
  2895. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2896. {
  2897. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2898. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2899. continue;
  2900. }
  2901. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2902. effectKindIndex = i;
  2903. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2904. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2905. const char* typeName = g_ArBasicTypeNames[kind];
  2906. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2907. CXXRecordDecl* recordDecl = nullptr;
  2908. if (kind == AR_OBJECT_RAY_DESC) {
  2909. QualType float3Ty = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 3);
  2910. recordDecl = CreateRayDescStruct(*m_context, float3Ty);
  2911. } else if (kind == AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES) {
  2912. QualType float2Type = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 2);
  2913. recordDecl = AddBuiltInTriangleIntersectionAttributes(*m_context, float2Type);
  2914. } else if (IsSubobjectBasicKind(kind)) {
  2915. switch (kind) {
  2916. case AR_OBJECT_STATE_OBJECT_CONFIG:
  2917. recordDecl = CreateSubobjectStateObjectConfig(*m_context);
  2918. break;
  2919. case AR_OBJECT_GLOBAL_ROOT_SIGNATURE:
  2920. recordDecl = CreateSubobjectRootSignature(*m_context, true);
  2921. break;
  2922. case AR_OBJECT_LOCAL_ROOT_SIGNATURE:
  2923. recordDecl = CreateSubobjectRootSignature(*m_context, false);
  2924. break;
  2925. case AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC:
  2926. recordDecl = CreateSubobjectSubobjectToExportsAssoc(*m_context);
  2927. break;
  2928. case AR_OBJECT_RAYTRACING_SHADER_CONFIG:
  2929. recordDecl = CreateSubobjectRaytracingShaderConfig(*m_context);
  2930. break;
  2931. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG:
  2932. recordDecl = CreateSubobjectRaytracingPipelineConfig(*m_context);
  2933. break;
  2934. case AR_OBJECT_TRIANGLE_HIT_GROUP:
  2935. recordDecl = CreateSubobjectTriangleHitGroup(*m_context);
  2936. break;
  2937. case AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP:
  2938. recordDecl = CreateSubobjectProceduralPrimitiveHitGroup(*m_context);
  2939. break;
  2940. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1:
  2941. recordDecl = CreateSubobjectRaytracingPipelineConfig1(*m_context);
  2942. break;
  2943. }
  2944. } else if (kind == AR_OBJECT_RAY_QUERY) {
  2945. recordDecl = DeclareRayQueryType(*m_context);
  2946. } else if (kind == AR_OBJECT_RESOURCE) {
  2947. recordDecl = DeclareResourceType(*m_context);
  2948. }
  2949. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D) {
  2950. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2D", "kind");
  2951. }
  2952. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY) {
  2953. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2DArray", "kind");
  2954. }
  2955. else if (templateArgCount == 0) {
  2956. recordDecl = DeclareRecordTypeWithHandle(*m_context, typeName);
  2957. }
  2958. else
  2959. {
  2960. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2961. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2962. recordDecl = DeclareTemplateTypeWithHandle(*m_context, typeName, templateArgCount, typeDefault);
  2963. }
  2964. m_objectTypeDecls[i] = recordDecl;
  2965. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2966. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2967. }
  2968. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2969. {
  2970. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2971. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2972. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2973. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2974. currentDeclContext->addDecl(samplerDecl);
  2975. samplerDecl->setImplicit(true);
  2976. // Create decls for each deprecated effect object type:
  2977. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2978. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2979. for (unsigned i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2980. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2981. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2982. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2983. currentDeclContext->addDecl(effectObjDecl);
  2984. effectObjDecl->setImplicit(true);
  2985. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2986. }
  2987. }
  2988. // Make sure it's in order.
  2989. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2990. }
  2991. FunctionDecl* AddSubscriptSpecialization(
  2992. _In_ FunctionTemplateDecl* functionTemplate,
  2993. QualType objectElement,
  2994. const FindStructBasicTypeResult& findResult);
  2995. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  2996. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2997. }
  2998. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  2999. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3000. }
  3001. static TYPE_CONVERSION_REMARKS RemarksUnused;
  3002. static ImplicitConversionKind ImplicitConversionKindUnused;
  3003. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType,
  3004. ImplicitConversionKind &convKind = ImplicitConversionKindUnused,
  3005. TYPE_CONVERSION_REMARKS &Remarks = RemarksUnused);
  3006. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  3007. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3008. rowCount <= 4 && colCount <= 4);
  3009. TypedefDecl *qts =
  3010. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  3011. if (qts == nullptr) {
  3012. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  3013. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  3014. rowCount, colCount);
  3015. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  3016. }
  3017. return qts;
  3018. }
  3019. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  3020. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3021. colCount <= 4);
  3022. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  3023. if (qts == nullptr) {
  3024. QualType type = LookupVectorType(scalarType, colCount);
  3025. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  3026. colCount);
  3027. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  3028. }
  3029. return qts;
  3030. }
  3031. public:
  3032. HLSLExternalSource() :
  3033. m_matrixTemplateDecl(nullptr),
  3034. m_vectorTemplateDecl(nullptr),
  3035. m_context(nullptr),
  3036. m_sema(nullptr),
  3037. m_hlslStringTypedef(nullptr)
  3038. {
  3039. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  3040. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  3041. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  3042. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  3043. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  3044. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  3045. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  3046. }
  3047. ~HLSLExternalSource() { }
  3048. static HLSLExternalSource* FromSema(_In_ Sema* self)
  3049. {
  3050. DXASSERT_NOMSG(self != nullptr);
  3051. ExternalSemaSource* externalSource = self->getExternalSource();
  3052. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  3053. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  3054. return hlsl;
  3055. }
  3056. void InitializeSema(Sema& S) override
  3057. {
  3058. m_sema = &S;
  3059. S.addExternalSource(this);
  3060. AddObjectTypes();
  3061. AddStdIsEqualImplementation(S.getASTContext(), S);
  3062. for (auto && intrinsic : m_intrinsicTables) {
  3063. AddIntrinsicTableMethods(intrinsic);
  3064. }
  3065. }
  3066. void ForgetSema() override
  3067. {
  3068. m_sema = nullptr;
  3069. }
  3070. Sema* getSema() {
  3071. return m_sema;
  3072. }
  3073. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  3074. // We shouldn't create Typedef for built in scalar types.
  3075. // For built in scalar types, this funciton may be called for
  3076. // TypoCorrection. In that case, we return a nullptr.
  3077. if (m_scalarTypes[scalarType].isNull()) {
  3078. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  3079. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  3080. }
  3081. return m_scalarTypeDefs[scalarType];
  3082. }
  3083. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  3084. {
  3085. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  3086. if (qt.isNull()) {
  3087. // lazy initialization of scalar types
  3088. if (m_scalarTypes[scalarType].isNull()) {
  3089. LookupScalarTypeDef(scalarType);
  3090. }
  3091. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  3092. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  3093. }
  3094. return qt;
  3095. }
  3096. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  3097. {
  3098. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  3099. if (qt.isNull()) {
  3100. if (m_scalarTypes[scalarType].isNull()) {
  3101. LookupScalarTypeDef(scalarType);
  3102. }
  3103. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  3104. m_vectorTypes[scalarType][colCount - 1] = qt;
  3105. }
  3106. return qt;
  3107. }
  3108. TypedefDecl* GetStringTypedef() {
  3109. if (m_hlslStringTypedef == nullptr) {
  3110. m_hlslStringTypedef = CreateGlobalTypedef(m_context, "string", m_hlslStringType);
  3111. m_hlslStringType = m_context->getTypeDeclType(m_hlslStringTypedef);
  3112. }
  3113. DXASSERT_NOMSG(m_hlslStringTypedef != nullptr);
  3114. return m_hlslStringTypedef;
  3115. }
  3116. static bool IsSubobjectBasicKind(ArBasicKind kind) {
  3117. return kind >= AR_OBJECT_STATE_OBJECT_CONFIG && kind <= AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1;
  3118. }
  3119. bool IsSubobjectType(QualType type) {
  3120. return IsSubobjectBasicKind(GetTypeElementKind(type));
  3121. }
  3122. bool IsRayQueryBasicKind(ArBasicKind kind) {
  3123. return kind == AR_OBJECT_RAY_QUERY;
  3124. }
  3125. bool IsRayQueryType(QualType type) {
  3126. return IsRayQueryBasicKind(GetTypeElementKind(type));
  3127. }
  3128. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  3129. // TODO: enalbe this once we introduce precise master option
  3130. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  3131. if (type == HLSLScalarType_int_min12) {
  3132. const char *PromotedType =
  3133. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  3134. : HLSLScalarTypeNames[HLSLScalarType_int16];
  3135. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3136. << HLSLScalarTypeNames[type] << PromotedType;
  3137. } else if (type == HLSLScalarType_float_min10) {
  3138. const char *PromotedType =
  3139. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  3140. : HLSLScalarTypeNames[HLSLScalarType_float16];
  3141. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3142. << HLSLScalarTypeNames[type] << PromotedType;
  3143. }
  3144. if (!UseMinPrecision) {
  3145. if (type == HLSLScalarType_float_min16) {
  3146. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3147. << HLSLScalarTypeNames[type]
  3148. << HLSLScalarTypeNames[HLSLScalarType_float16];
  3149. } else if (type == HLSLScalarType_int_min16) {
  3150. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3151. << HLSLScalarTypeNames[type]
  3152. << HLSLScalarTypeNames[HLSLScalarType_int16];
  3153. } else if (type == HLSLScalarType_uint_min16) {
  3154. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3155. << HLSLScalarTypeNames[type]
  3156. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  3157. }
  3158. }
  3159. }
  3160. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  3161. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  3162. switch (type) {
  3163. case HLSLScalarType_float16:
  3164. case HLSLScalarType_float32:
  3165. case HLSLScalarType_float64:
  3166. case HLSLScalarType_int16:
  3167. case HLSLScalarType_int32:
  3168. case HLSLScalarType_uint16:
  3169. case HLSLScalarType_uint32:
  3170. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  3171. << HLSLScalarTypeNames[type] << "2018";
  3172. return false;
  3173. default:
  3174. break;
  3175. }
  3176. }
  3177. if (getSema()->getLangOpts().UseMinPrecision) {
  3178. switch (type) {
  3179. case HLSLScalarType_float16:
  3180. case HLSLScalarType_int16:
  3181. case HLSLScalarType_uint16:
  3182. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  3183. << HLSLScalarTypeNames[type];
  3184. return false;
  3185. default:
  3186. break;
  3187. }
  3188. }
  3189. return true;
  3190. }
  3191. bool LookupUnqualified(LookupResult &R, Scope *S) override
  3192. {
  3193. const DeclarationNameInfo declName = R.getLookupNameInfo();
  3194. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3195. if (idInfo == nullptr) {
  3196. return false;
  3197. }
  3198. // Currently template instantiation is blocked when a fatal error is
  3199. // detected. So no faulting-in types at this point, instead we simply
  3200. // back out.
  3201. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  3202. return false;
  3203. }
  3204. StringRef nameIdentifier = idInfo->getName();
  3205. HLSLScalarType parsedType;
  3206. int rowCount;
  3207. int colCount;
  3208. // Try parsing hlsl scalar types that is not initialized at AST time.
  3209. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  3210. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  3211. if (rowCount == 0 && colCount == 0) { // scalar
  3212. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  3213. if (!typeDecl) return false;
  3214. R.addDecl(typeDecl);
  3215. }
  3216. else if (rowCount == 0) { // vector
  3217. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  3218. R.addDecl(qts);
  3219. }
  3220. else { // matrix
  3221. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  3222. R.addDecl(qts);
  3223. }
  3224. return true;
  3225. }
  3226. // string
  3227. else if (TryParseString(nameIdentifier.data(), nameIdentifier.size(), getSema()->getLangOpts())) {
  3228. TypedefDecl *strDecl = GetStringTypedef();
  3229. R.addDecl(strDecl);
  3230. }
  3231. return false;
  3232. }
  3233. /// <summary>
  3234. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  3235. /// </sumary>
  3236. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  3237. {
  3238. DXASSERT_NOMSG(type != nullptr);
  3239. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3240. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3241. if (templateSpecializationDecl) {
  3242. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  3243. if (decl == m_matrixTemplateDecl)
  3244. return AR_TOBJ_MATRIX;
  3245. else if (decl == m_vectorTemplateDecl)
  3246. return AR_TOBJ_VECTOR;
  3247. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  3248. return AR_TOBJ_OBJECT;
  3249. }
  3250. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3251. if (typeRecordDecl->getDeclContext()->isFileContext()) {
  3252. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3253. if (index != -1) {
  3254. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  3255. if ( AR_OBJECT_RAY_DESC == kind || AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES == kind)
  3256. return AR_TOBJ_COMPOUND;
  3257. }
  3258. return AR_TOBJ_OBJECT;
  3259. }
  3260. else
  3261. return AR_TOBJ_INNER_OBJ;
  3262. }
  3263. return AR_TOBJ_COMPOUND;
  3264. }
  3265. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  3266. bool IsBuiltInObjectType(QualType type)
  3267. {
  3268. type = GetStructuralForm(type);
  3269. if (!type.isNull() && type->isStructureOrClassType()) {
  3270. const RecordType* recordType = type->getAs<RecordType>();
  3271. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  3272. }
  3273. return false;
  3274. }
  3275. /// <summary>
  3276. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  3277. /// possibly refering to original template record if it's a specialization; this makes the result
  3278. /// suitable for looking up in initialization tables.
  3279. /// </summary>
  3280. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  3281. {
  3282. const CXXRecordDecl* recordDecl;
  3283. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  3284. {
  3285. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  3286. }
  3287. else
  3288. {
  3289. recordDecl = dyn_cast<CXXRecordDecl>(context);
  3290. }
  3291. return recordDecl;
  3292. }
  3293. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  3294. ArTypeObjectKind GetTypeObjectKind(QualType type)
  3295. {
  3296. DXASSERT_NOMSG(!type.isNull());
  3297. type = GetStructuralForm(type);
  3298. if (type->isVoidType()) return AR_TOBJ_VOID;
  3299. if (type->isArrayType()) {
  3300. return hlsl::IsArrayConstantStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_ARRAY;
  3301. }
  3302. if (type->isPointerType()) {
  3303. return hlsl::IsPointerStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_POINTER;
  3304. }
  3305. if (type->isStructureOrClassType()) {
  3306. const RecordType* recordType = type->getAs<RecordType>();
  3307. return ClassifyRecordType(recordType);
  3308. } else if (const InjectedClassNameType *ClassNameTy =
  3309. type->getAs<InjectedClassNameType>()) {
  3310. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  3311. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  3312. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3313. if (templateSpecializationDecl) {
  3314. ClassTemplateDecl *decl =
  3315. templateSpecializationDecl->getSpecializedTemplate();
  3316. if (decl == m_matrixTemplateDecl)
  3317. return AR_TOBJ_MATRIX;
  3318. else if (decl == m_vectorTemplateDecl)
  3319. return AR_TOBJ_VECTOR;
  3320. DXASSERT(decl->isImplicit(),
  3321. "otherwise object template decl is not set to implicit");
  3322. return AR_TOBJ_OBJECT;
  3323. }
  3324. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3325. if (typeRecordDecl->getDeclContext()->isFileContext())
  3326. return AR_TOBJ_OBJECT;
  3327. else
  3328. return AR_TOBJ_INNER_OBJ;
  3329. }
  3330. return AR_TOBJ_COMPOUND;
  3331. }
  3332. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  3333. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  3334. return AR_TOBJ_INVALID;
  3335. }
  3336. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  3337. QualType GetMatrixOrVectorElementType(QualType type)
  3338. {
  3339. type = GetStructuralForm(type);
  3340. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3341. DXASSERT_NOMSG(typeRecordDecl);
  3342. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3343. DXASSERT_NOMSG(templateSpecializationDecl);
  3344. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  3345. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  3346. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  3347. }
  3348. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  3349. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  3350. QualType GetStructuralForm(QualType type)
  3351. {
  3352. if (type.isNull()) {
  3353. return type;
  3354. }
  3355. const ReferenceType *RefType = nullptr;
  3356. const AttributedType *AttrType = nullptr;
  3357. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  3358. (AttrType = dyn_cast<AttributedType>(type)))
  3359. {
  3360. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  3361. }
  3362. // Despite its name, getCanonicalTypeUnqualified will preserve const for array elements or something
  3363. return QualType(type->getCanonicalTypeUnqualified()->getTypePtr(), 0);
  3364. }
  3365. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  3366. ArBasicKind GetTypeElementKind(QualType type)
  3367. {
  3368. type = GetStructuralForm(type);
  3369. ArTypeObjectKind kind = GetTypeObjectKind(type);
  3370. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  3371. QualType elementType = GetMatrixOrVectorElementType(type);
  3372. return GetTypeElementKind(elementType);
  3373. }
  3374. if (kind == AR_TOBJ_STRING) {
  3375. return type->isArrayType() ? AR_OBJECT_STRING_LITERAL : AR_OBJECT_STRING;
  3376. }
  3377. if (type->isArrayType()) {
  3378. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  3379. return GetTypeElementKind(arrayType->getElementType());
  3380. }
  3381. if (kind == AR_TOBJ_INNER_OBJ) {
  3382. return AR_OBJECT_INNER;
  3383. } else if (kind == AR_TOBJ_OBJECT) {
  3384. // Classify the object as the element type.
  3385. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  3386. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3387. // NOTE: this will likely need to be updated for specialized records
  3388. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  3389. return g_ArBasicKindsAsTypes[index];
  3390. }
  3391. CanQualType canType = type->getCanonicalTypeUnqualified();
  3392. return BasicTypeForScalarType(canType);
  3393. }
  3394. ArBasicKind BasicTypeForScalarType(CanQualType type)
  3395. {
  3396. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3397. {
  3398. switch (BT->getKind())
  3399. {
  3400. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3401. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3402. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3403. case BuiltinType::Half: return AR_BASIC_FLOAT16;
  3404. case BuiltinType::HalfFloat: return AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  3405. case BuiltinType::Int: return AR_BASIC_INT32;
  3406. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3407. case BuiltinType::Short: return AR_BASIC_INT16;
  3408. case BuiltinType::UShort: return AR_BASIC_UINT16;
  3409. case BuiltinType::Long: return AR_BASIC_INT32;
  3410. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3411. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3412. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3413. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3414. case BuiltinType::Min16Float: return AR_BASIC_MIN16FLOAT;
  3415. case BuiltinType::Min16Int: return AR_BASIC_MIN16INT;
  3416. case BuiltinType::Min16UInt: return AR_BASIC_MIN16UINT;
  3417. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3418. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3419. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3420. default:
  3421. // Only builtin types that have basickind equivalents.
  3422. break;
  3423. }
  3424. }
  3425. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3426. if (ET->getDecl()->isScopedUsingClassTag())
  3427. return AR_BASIC_ENUM_CLASS;
  3428. return AR_BASIC_ENUM;
  3429. }
  3430. return AR_BASIC_UNKNOWN;
  3431. }
  3432. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3433. DXASSERT_NOMSG(table != nullptr);
  3434. // Function intrinsics are added on-demand, objects get template methods.
  3435. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3436. // Grab information already processed by AddObjectTypes.
  3437. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3438. const char *typeName = g_ArBasicTypeNames[kind];
  3439. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3440. DXASSERT(templateArgCount <= 2, "otherwise a new case has been added");
  3441. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3442. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3443. if (recordDecl == nullptr) {
  3444. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3445. continue;
  3446. }
  3447. // This is a variation of AddObjectMethods using the new table.
  3448. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3449. const HLSL_INTRINSIC *pPrior = nullptr;
  3450. UINT64 lookupCookie = 0;
  3451. CA2W wideTypeName(typeName, CP_UTF8);
  3452. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3453. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3454. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3455. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3456. // NOTE: this only works with the current implementation because
  3457. // intrinsics are alive as long as the table is alive.
  3458. pPrior = pIntrinsic;
  3459. }
  3460. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3461. }
  3462. }
  3463. }
  3464. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3465. DXASSERT_NOMSG(table != nullptr);
  3466. m_intrinsicTables.push_back(table);
  3467. // If already initialized, add methods immediately.
  3468. if (m_sema != nullptr) {
  3469. AddIntrinsicTableMethods(table);
  3470. }
  3471. }
  3472. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3473. {
  3474. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3475. switch (kind) {
  3476. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3477. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3478. case AR_BASIC_FLOAT16: return HLSLScalarType_half;
  3479. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3480. return HLSLScalarType_float;
  3481. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3482. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3483. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3484. case AR_BASIC_INT8: return HLSLScalarType_int;
  3485. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3486. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3487. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3488. case AR_BASIC_INT32: return HLSLScalarType_int;
  3489. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3490. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3491. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3492. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3493. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3494. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3495. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3496. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3497. case AR_BASIC_ENUM: return HLSLScalarType_int;
  3498. default:
  3499. return HLSLScalarType_unknown;
  3500. }
  3501. }
  3502. QualType GetBasicKindType(ArBasicKind kind)
  3503. {
  3504. DXASSERT_VALIDBASICKIND(kind);
  3505. switch (kind) {
  3506. case AR_OBJECT_NULL: return m_context->VoidTy;
  3507. case AR_BASIC_BOOL: return m_context->BoolTy;
  3508. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3509. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3510. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->HalfFloatTy;
  3511. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3512. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3513. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3514. case AR_BASIC_INT8: return m_context->IntTy;
  3515. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3516. case AR_BASIC_INT16: return m_context->ShortTy;
  3517. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3518. case AR_BASIC_INT32: return m_context->IntTy;
  3519. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3520. case AR_BASIC_INT64: return m_context->LongLongTy;
  3521. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3522. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3523. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3524. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3525. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3526. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3527. case AR_BASIC_ENUM: return m_context->IntTy;
  3528. case AR_BASIC_ENUM_CLASS: return m_context->IntTy;
  3529. case AR_OBJECT_STRING: return m_hlslStringType;
  3530. case AR_OBJECT_STRING_LITERAL:
  3531. // m_hlslStringType is defined as 'char *'.
  3532. // for STRING_LITERAL we should use 'const char *'.
  3533. return m_context->getPointerType(m_context->CharTy.withConst());
  3534. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3535. case AR_OBJECT_TEXTURE1D:
  3536. case AR_OBJECT_TEXTURE1D_ARRAY:
  3537. case AR_OBJECT_TEXTURE2D:
  3538. case AR_OBJECT_TEXTURE2D_ARRAY:
  3539. case AR_OBJECT_TEXTURE3D:
  3540. case AR_OBJECT_TEXTURECUBE:
  3541. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3542. case AR_OBJECT_TEXTURE2DMS:
  3543. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3544. case AR_OBJECT_SAMPLER:
  3545. case AR_OBJECT_SAMPLERCOMPARISON:
  3546. case AR_OBJECT_RESOURCE:
  3547. case AR_OBJECT_BUFFER:
  3548. case AR_OBJECT_POINTSTREAM:
  3549. case AR_OBJECT_LINESTREAM:
  3550. case AR_OBJECT_TRIANGLESTREAM:
  3551. case AR_OBJECT_INPUTPATCH:
  3552. case AR_OBJECT_OUTPUTPATCH:
  3553. case AR_OBJECT_RWTEXTURE1D:
  3554. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3555. case AR_OBJECT_RWTEXTURE2D:
  3556. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3557. case AR_OBJECT_RWTEXTURE3D:
  3558. case AR_OBJECT_RWBUFFER:
  3559. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3560. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3561. case AR_OBJECT_STRUCTURED_BUFFER:
  3562. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3563. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3564. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3565. case AR_OBJECT_WAVE:
  3566. case AR_OBJECT_ACCELERATION_STRUCT:
  3567. case AR_OBJECT_RAY_DESC:
  3568. case AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES:
  3569. {
  3570. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3571. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3572. size_t index = match - g_ArBasicKindsAsTypes;
  3573. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3574. }
  3575. case AR_OBJECT_SAMPLER1D:
  3576. case AR_OBJECT_SAMPLER2D:
  3577. case AR_OBJECT_SAMPLER3D:
  3578. case AR_OBJECT_SAMPLERCUBE:
  3579. // Turn dimension-typed samplers into sampler states.
  3580. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3581. case AR_OBJECT_STATEBLOCK:
  3582. case AR_OBJECT_RASTERIZER:
  3583. case AR_OBJECT_DEPTHSTENCIL:
  3584. case AR_OBJECT_BLEND:
  3585. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3586. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3587. default:
  3588. return QualType();
  3589. }
  3590. }
  3591. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3592. /// <param name="E">Expression to typecast.</param>
  3593. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3594. ExprResult PromoteToIntIfBool(ExprResult& E);
  3595. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3596. {
  3597. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3598. (void)(qwUsages);
  3599. return type;
  3600. }
  3601. QualType NewSimpleAggregateType(
  3602. _In_ ArTypeObjectKind ExplicitKind,
  3603. _In_ ArBasicKind componentType,
  3604. _In_ UINT64 qwQual,
  3605. _In_ UINT uRows,
  3606. _In_ UINT uCols)
  3607. {
  3608. DXASSERT_VALIDBASICKIND(componentType);
  3609. QualType pType; // The type to return.
  3610. if (componentType < AR_BASIC_COUNT) {
  3611. // If basic numeric, call LookupScalarTypeDef to ensure on-demand
  3612. // initialization
  3613. LookupScalarTypeDef(ScalarTypeForBasic(componentType));
  3614. }
  3615. QualType pEltType = GetBasicKindType(componentType);
  3616. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3617. // TODO: handle adding qualifications like const
  3618. pType = NewQualifiedType(
  3619. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3620. pEltType);
  3621. if (uRows > 1 ||
  3622. uCols > 1 ||
  3623. ExplicitKind == AR_TOBJ_VECTOR ||
  3624. ExplicitKind == AR_TOBJ_MATRIX)
  3625. {
  3626. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3627. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3628. if ((uRows == 1 &&
  3629. ExplicitKind != AR_TOBJ_MATRIX) ||
  3630. ExplicitKind == AR_TOBJ_VECTOR)
  3631. {
  3632. pType = LookupVectorType(scalarType, uCols);
  3633. }
  3634. else
  3635. {
  3636. pType = LookupMatrixType(scalarType, uRows, uCols);
  3637. }
  3638. // TODO: handle colmajor/rowmajor
  3639. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3640. //{
  3641. // VN(pType = NewQualifiedType(pSrcLoc,
  3642. // qwQual & (AR_QUAL_COLMAJOR |
  3643. // AR_QUAL_ROWMAJOR),
  3644. // pMatrix));
  3645. //}
  3646. //else
  3647. //{
  3648. // pType = pMatrix;
  3649. //}
  3650. }
  3651. return pType;
  3652. }
  3653. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3654. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3655. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3656. /// <param name="Args">Invocation arguments to match.</param>
  3657. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3658. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  3659. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3660. bool MatchArguments(
  3661. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3662. _In_ QualType objectElement,
  3663. _In_ QualType functionTemplateTypeArg,
  3664. _In_ ArrayRef<Expr *> Args,
  3665. _Out_ std::vector<QualType> *);
  3666. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3667. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3668. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3669. bool IsValidateObjectElement(
  3670. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3671. _In_ QualType objectElement);
  3672. // Returns the iterator with the first entry that matches the requirement
  3673. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3674. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3675. size_t tableSize,
  3676. StringRef typeName,
  3677. StringRef nameIdentifier,
  3678. size_t argumentCount)
  3679. {
  3680. // This is implemented by a linear scan for now.
  3681. // We tested binary search on tables, and there was no performance gain on
  3682. // samples probably for the following reasons.
  3683. // 1. The tables are not big enough to make noticable difference
  3684. // 2. The user of this function assumes that it returns the first entry in
  3685. // the table that matches name and argument count. So even in the binary
  3686. // search, we have to scan backwards until the entry does not match the name
  3687. // or arg count. For linear search this is not a problem
  3688. for (unsigned int i = 0; i < tableSize; i++) {
  3689. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3690. const bool isVariadicFn = IsVariadicIntrinsicFunction(pIntrinsic);
  3691. // Do some quick checks to verify size and name.
  3692. if (!isVariadicFn && pIntrinsic->uNumArgs != 1 + argumentCount) {
  3693. continue;
  3694. }
  3695. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3696. continue;
  3697. }
  3698. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3699. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3700. }
  3701. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3702. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3703. }
  3704. bool AddOverloadedCallCandidates(
  3705. UnresolvedLookupExpr *ULE,
  3706. ArrayRef<Expr *> Args,
  3707. OverloadCandidateSet &CandidateSet,
  3708. bool PartialOverloading) override
  3709. {
  3710. DXASSERT_NOMSG(ULE != nullptr);
  3711. // Intrinsics live in the global namespace, so references to their names
  3712. // should be either unqualified or '::'-prefixed.
  3713. if (ULE->getQualifier() && ULE->getQualifier()->getKind() != NestedNameSpecifier::Global) {
  3714. return false;
  3715. }
  3716. const DeclarationNameInfo declName = ULE->getNameInfo();
  3717. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3718. if (idInfo == nullptr)
  3719. {
  3720. return false;
  3721. }
  3722. StringRef nameIdentifier = idInfo->getName();
  3723. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3724. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  3725. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3726. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3727. while (cursor != end)
  3728. {
  3729. // If this is the intrinsic we're interested in, build up a representation
  3730. // of the types we need.
  3731. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3732. LPCSTR tableName = cursor.GetTableName();
  3733. LPCSTR lowering = cursor.GetLoweringStrategy();
  3734. DXASSERT(
  3735. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3736. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3737. std::vector<QualType> functionArgTypes;
  3738. if (!MatchArguments(pIntrinsic, QualType(), QualType(), Args, &functionArgTypes))
  3739. {
  3740. ++cursor;
  3741. continue;
  3742. }
  3743. // Get or create the overload we're interested in.
  3744. FunctionDecl* intrinsicFuncDecl = nullptr;
  3745. std::pair<UsedIntrinsicStore::iterator, bool> insertResult =
  3746. m_usedIntrinsics.insert(UsedIntrinsic(pIntrinsic, functionArgTypes));
  3747. bool insertedNewValue = insertResult.second;
  3748. if (insertedNewValue)
  3749. {
  3750. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3751. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, &functionArgTypes);
  3752. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3753. }
  3754. else
  3755. {
  3756. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3757. }
  3758. OverloadCandidate& candidate = CandidateSet.addCandidate();
  3759. candidate.Function = intrinsicFuncDecl;
  3760. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3761. candidate.Viable = true;
  3762. return true;
  3763. }
  3764. return false;
  3765. }
  3766. bool Initialize(ASTContext& context)
  3767. {
  3768. m_context = &context;
  3769. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3770. /*Inline*/ false, SourceLocation(),
  3771. SourceLocation(), &context.Idents.get("hlsl"),
  3772. /*PrevDecl*/ nullptr);
  3773. m_hlslNSDecl->setImplicit();
  3774. AddBaseTypes();
  3775. AddHLSLScalarTypes();
  3776. AddHLSLStringType();
  3777. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3778. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  3779. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  3780. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  3781. // Initializing built in integers for ray tracing
  3782. AddRaytracingConstants(*m_context);
  3783. AddSamplerFeedbackConstants(*m_context);
  3784. return true;
  3785. }
  3786. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  3787. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  3788. /// <summary>Checks whether the specified type is a scalar type.</summary>
  3789. bool IsScalarType(const QualType& type) {
  3790. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  3791. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3792. }
  3793. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3794. bool IsValidVectorSize(size_t length) {
  3795. return 1 <= length && length <= 4;
  3796. }
  3797. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3798. bool IsValidMatrixColOrRowSize(size_t length) {
  3799. return 1 <= length && length <= 4;
  3800. }
  3801. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3802. if (type.isNull()) {
  3803. return false;
  3804. }
  3805. if (type.hasQualifiers()) {
  3806. return false;
  3807. }
  3808. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3809. if (type->getTypeClass() == Type::TemplateTypeParm)
  3810. return true;
  3811. QualType qt = GetStructuralForm(type);
  3812. if (requireScalar) {
  3813. if (!IsScalarType(qt)) {
  3814. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3815. return false;
  3816. }
  3817. return true;
  3818. }
  3819. else {
  3820. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3821. if (qt->isArrayType()) {
  3822. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3823. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3824. }
  3825. else if (objectKind == AR_TOBJ_VECTOR) {
  3826. bool valid = true;
  3827. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3828. valid = false;
  3829. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3830. }
  3831. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3832. valid = false;
  3833. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3834. }
  3835. return valid;
  3836. }
  3837. else if (objectKind == AR_TOBJ_MATRIX) {
  3838. bool valid = true;
  3839. UINT rowCount, colCount;
  3840. GetRowsAndCols(type, rowCount, colCount);
  3841. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3842. valid = false;
  3843. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3844. }
  3845. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3846. valid = false;
  3847. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3848. }
  3849. return valid;
  3850. }
  3851. else if (qt->isStructureType()) {
  3852. const RecordType* recordType = qt->getAsStructureType();
  3853. objectKind = ClassifyRecordType(recordType);
  3854. switch (objectKind)
  3855. {
  3856. case AR_TOBJ_OBJECT:
  3857. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3858. return false;
  3859. case AR_TOBJ_COMPOUND:
  3860. {
  3861. const RecordDecl* recordDecl = recordType->getDecl();
  3862. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3863. RecordDecl::field_iterator end = recordDecl->field_end();
  3864. bool result = true;
  3865. while (begin != end) {
  3866. const FieldDecl* fieldDecl = *begin;
  3867. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3868. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3869. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3870. result = false;
  3871. }
  3872. begin++;
  3873. }
  3874. return result;
  3875. }
  3876. default:
  3877. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3878. return false;
  3879. }
  3880. }
  3881. else if(IsScalarType(qt)) {
  3882. return true;
  3883. }
  3884. else {
  3885. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3886. return false;
  3887. }
  3888. }
  3889. }
  3890. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3891. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3892. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3893. _Inout_opt_ StandardConversionSequence* sequence);
  3894. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3895. void GetConversionForm(
  3896. QualType type,
  3897. bool explicitConversion,
  3898. ArTypeInfo* pTypeInfo);
  3899. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3900. bool suppressWarnings, bool suppressErrors,
  3901. _Inout_opt_ StandardConversionSequence* sequence);
  3902. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3903. bool ValidateTypeRequirements(
  3904. SourceLocation loc,
  3905. ArBasicKind elementKind,
  3906. ArTypeObjectKind objectKind,
  3907. bool requiresIntegrals,
  3908. bool requiresNumerics);
  3909. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3910. /// <param name="OpLoc">Source location for operator.</param>
  3911. /// <param name="Opc">Kind of binary operator.</param>
  3912. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3913. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3914. /// <param name="ResultTy">Result type for operator expression.</param>
  3915. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3916. /// <param name="CompResultTy">Type of computation result.</param>
  3917. void CheckBinOpForHLSL(
  3918. SourceLocation OpLoc,
  3919. BinaryOperatorKind Opc,
  3920. ExprResult& LHS,
  3921. ExprResult& RHS,
  3922. QualType& ResultTy,
  3923. QualType& CompLHSTy,
  3924. QualType& CompResultTy);
  3925. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3926. /// <param name="OpLoc">Source location for operator.</param>
  3927. /// <param name="Opc">Kind of operator.</param>
  3928. /// <param name="InputExpr">Input expression to the operator.</param>
  3929. /// <param name="VK">Value kind for resulting expression.</param>
  3930. /// <param name="OK">Object kind for resulting expression.</param>
  3931. /// <returns>The result type for the expression.</returns>
  3932. QualType CheckUnaryOpForHLSL(
  3933. SourceLocation OpLoc,
  3934. UnaryOperatorKind Opc,
  3935. ExprResult& InputExpr,
  3936. ExprValueKind& VK,
  3937. ExprObjectKind& OK);
  3938. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3939. /// <param name="Cond">Vector condition expression.</param>
  3940. /// <param name="LHS">Left hand side.</param>
  3941. /// <param name="RHS">Right hand side.</param>
  3942. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3943. /// <returns>Result type of vector conditional expression.</returns>
  3944. clang::QualType CheckVectorConditional(
  3945. _In_ ExprResult &Cond,
  3946. _In_ ExprResult &LHS,
  3947. _In_ ExprResult &RHS,
  3948. _In_ SourceLocation QuestionLoc);
  3949. clang::QualType ApplyTypeSpecSignToParsedType(
  3950. _In_ clang::QualType &type,
  3951. _In_ TypeSpecifierSign TSS,
  3952. _In_ SourceLocation Loc
  3953. );
  3954. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3955. {
  3956. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3957. {
  3958. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3959. return true;
  3960. }
  3961. return false;
  3962. }
  3963. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3964. bool
  3965. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3966. SourceLocation /* TemplateLoc */,
  3967. TemplateArgumentListInfo &TemplateArgList) {
  3968. DXASSERT_NOMSG(Template != nullptr);
  3969. // Determine which object type the template refers to.
  3970. StringRef templateName = Template->getName();
  3971. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3972. if (templateName.equals(StringRef("is_same"))) {
  3973. return false;
  3974. }
  3975. bool isMatrix = Template->getCanonicalDecl() ==
  3976. m_matrixTemplateDecl->getCanonicalDecl();
  3977. bool isVector = Template->getCanonicalDecl() ==
  3978. m_vectorTemplateDecl->getCanonicalDecl();
  3979. bool requireScalar = isMatrix || isVector;
  3980. // Check constraints on the type. Right now we only check that template
  3981. // types are primitive types.
  3982. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3983. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3984. SourceLocation argSrcLoc = argLoc.getLocation();
  3985. const TemplateArgument &arg = argLoc.getArgument();
  3986. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3987. QualType argType = arg.getAsType();
  3988. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3989. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3990. return true;
  3991. }
  3992. }
  3993. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  3994. if (isMatrix || isVector) {
  3995. Expr *expr = arg.getAsExpr();
  3996. llvm::APSInt constantResult;
  3997. if (expr != nullptr &&
  3998. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  3999. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  4000. return true;
  4001. }
  4002. }
  4003. }
  4004. }
  4005. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  4006. if (isMatrix || isVector) {
  4007. llvm::APSInt Val = arg.getAsIntegral();
  4008. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  4009. return true;
  4010. }
  4011. }
  4012. }
  4013. }
  4014. return false;
  4015. }
  4016. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  4017. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  4018. /// <param name="functionDeclContext">Declaration context of function.</param>
  4019. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  4020. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  4021. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  4022. void FindIntrinsicTable(
  4023. _In_ DeclContext* functionDeclContext,
  4024. _Outptr_result_z_ const char** name,
  4025. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  4026. _Out_ size_t* intrinsicCount);
  4027. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  4028. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  4029. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  4030. /// <param name="Args">Array of expressions being used as arguments.</param>
  4031. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  4032. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  4033. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  4034. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  4035. FunctionTemplateDecl *FunctionTemplate,
  4036. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  4037. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  4038. clang::OverloadingResult GetBestViableFunction(
  4039. clang::SourceLocation Loc,
  4040. clang::OverloadCandidateSet& set,
  4041. clang::OverloadCandidateSet::iterator& Best);
  4042. /// <summary>
  4043. /// Initializes the specified <paramref name="initSequence" /> describing how
  4044. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  4045. /// </summary>
  4046. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  4047. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  4048. /// <param name="Args">Arguments to the initialization.</param>
  4049. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  4050. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  4051. void InitializeInitSequenceForHLSL(
  4052. const InitializedEntity& Entity,
  4053. const InitializationKind& Kind,
  4054. MultiExprArg Args,
  4055. bool TopLevelOfInitList,
  4056. _Inout_ InitializationSequence* initSequence);
  4057. /// <summary>
  4058. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4059. /// </summary>
  4060. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4061. bool IsConversionToLessOrEqualElements(
  4062. const ExprResult& sourceExpr,
  4063. const QualType& targetType,
  4064. bool explicitConversion);
  4065. /// <summary>
  4066. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4067. /// </summary>
  4068. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4069. bool IsConversionToLessOrEqualElements(
  4070. const QualType& sourceType,
  4071. const QualType& targetType,
  4072. bool explicitConversion);
  4073. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  4074. /// <param name="BaseExpr">Base expression for member access.</param>
  4075. /// <param name="MemberName">Name of member to look up.</param>
  4076. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4077. /// <param name="OpLoc">Location of access operand.</param>
  4078. /// <param name="MemberLoc">Location of member.</param>
  4079. /// <returns>Result of lookup operation.</returns>
  4080. ExprResult LookupMatrixMemberExprForHLSL(
  4081. Expr& BaseExpr,
  4082. DeclarationName MemberName,
  4083. bool IsArrow,
  4084. SourceLocation OpLoc,
  4085. SourceLocation MemberLoc);
  4086. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  4087. /// <param name="BaseExpr">Base expression for member access.</param>
  4088. /// <param name="MemberName">Name of member to look up.</param>
  4089. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4090. /// <param name="OpLoc">Location of access operand.</param>
  4091. /// <param name="MemberLoc">Location of member.</param>
  4092. /// <returns>Result of lookup operation.</returns>
  4093. ExprResult LookupVectorMemberExprForHLSL(
  4094. Expr& BaseExpr,
  4095. DeclarationName MemberName,
  4096. bool IsArrow,
  4097. SourceLocation OpLoc,
  4098. SourceLocation MemberLoc);
  4099. /// <summary>Performs a member lookup on the specified BaseExpr if it's an array.</summary>
  4100. /// <param name="BaseExpr">Base expression for member access.</param>
  4101. /// <param name="MemberName">Name of member to look up.</param>
  4102. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4103. /// <param name="OpLoc">Location of access operand.</param>
  4104. /// <param name="MemberLoc">Location of member.</param>
  4105. /// <returns>Result of lookup operation.</returns>
  4106. ExprResult LookupArrayMemberExprForHLSL(
  4107. Expr& BaseExpr,
  4108. DeclarationName MemberName,
  4109. bool IsArrow,
  4110. SourceLocation OpLoc,
  4111. SourceLocation MemberLoc);
  4112. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  4113. /// <param name="E">Expression to convert.</param>
  4114. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  4115. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  4116. clang::Expr *HLSLImpCastToScalar(
  4117. _In_ clang::Sema* self,
  4118. _In_ clang::Expr* From,
  4119. ArTypeObjectKind FromShape,
  4120. ArBasicKind EltKind);
  4121. clang::ExprResult PerformHLSLConversion(
  4122. _In_ clang::Expr* From,
  4123. _In_ clang::QualType targetType,
  4124. _In_ const clang::StandardConversionSequence &SCS,
  4125. _In_ clang::Sema::CheckedConversionKind CCK);
  4126. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  4127. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  4128. /// <summary>
  4129. /// Checks if a static cast can be performed, and performs it if possible.
  4130. /// </summary>
  4131. /// <param name="SrcExpr">Expression to cast.</param>
  4132. /// <param name="DestType">Type to cast SrcExpr to.</param>
  4133. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  4134. /// <param name="OpRange">Source range for the cast operation.</param>
  4135. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  4136. /// <param name="Kind">The kind of operation required for a conversion.</param>
  4137. /// <param name="BasePath">A simple array of base specifiers.</param>
  4138. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  4139. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  4140. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  4141. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  4142. QualType DestType,
  4143. Sema::CheckedConversionKind CCK,
  4144. const SourceRange &OpRange, unsigned &msg,
  4145. CastKind &Kind, CXXCastPath &BasePath,
  4146. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  4147. _Inout_opt_ StandardConversionSequence* standard);
  4148. /// <summary>
  4149. /// Checks if a subscript index argument can be initialized from the given expression.
  4150. /// </summary>
  4151. /// <param name="SrcExpr">Source expression used as argument.</param>
  4152. /// <param name="DestType">Parameter type to initialize.</param>
  4153. /// <remarks>
  4154. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  4155. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  4156. /// </remarks>
  4157. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  4158. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  4159. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  4160. // Everything is ready.
  4161. if (m_objectTypeLazyInitMask == 0)
  4162. return;
  4163. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  4164. int idx = FindObjectBasicKindIndex(recordDecl);
  4165. // Not object type.
  4166. if (idx == -1)
  4167. return;
  4168. uint64_t bit = ((uint64_t)1)<<idx;
  4169. // Already created.
  4170. if ((m_objectTypeLazyInitMask & bit) == 0)
  4171. return;
  4172. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  4173. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  4174. int startDepth = 0;
  4175. if (templateArgCount > 0) {
  4176. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  4177. "otherwise a new case has been added");
  4178. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  4179. AddObjectSubscripts(kind, typeDecl, recordDecl,
  4180. g_ArBasicKindsSubscripts[idx]);
  4181. startDepth = 1;
  4182. }
  4183. AddObjectMethods(kind, recordDecl, startDepth);
  4184. // Clear the object.
  4185. m_objectTypeLazyInitMask &= ~bit;
  4186. }
  4187. FunctionDecl* AddHLSLIntrinsicMethod(
  4188. LPCSTR tableName,
  4189. LPCSTR lowering,
  4190. _In_ const HLSL_INTRINSIC* intrinsic,
  4191. _In_ FunctionTemplateDecl *FunctionTemplate,
  4192. ArrayRef<Expr *> Args,
  4193. _In_count_(parameterTypeCount) QualType* parameterTypes,
  4194. size_t parameterTypeCount)
  4195. {
  4196. DXASSERT_NOMSG(intrinsic != nullptr);
  4197. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  4198. DXASSERT_NOMSG(parameterTypes != nullptr);
  4199. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  4200. // Create the template arguments.
  4201. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  4202. for (size_t i = 0; i < parameterTypeCount; i++) {
  4203. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  4204. }
  4205. // Look for an existing specialization.
  4206. void *InsertPos = nullptr;
  4207. FunctionDecl *SpecFunc =
  4208. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  4209. if (SpecFunc != nullptr) {
  4210. return SpecFunc;
  4211. }
  4212. // Change return type to lvalue reference type for aggregate types
  4213. QualType retTy = parameterTypes[0];
  4214. if (hlsl::IsHLSLAggregateType(retTy))
  4215. parameterTypes[0] = m_context->getLValueReferenceType(retTy);
  4216. // Create a new specialization.
  4217. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  4218. InitParamMods(intrinsic, paramMods);
  4219. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4220. // Change out/inout parameter type to rvalue reference type.
  4221. if (paramMods[i - 1].isAnyOut()) {
  4222. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  4223. }
  4224. }
  4225. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  4226. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  4227. // Remove this when update intrinsic table not affect other things.
  4228. // Change vector<float,1> into float for bias.
  4229. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  4230. DXASSERT(parameterTypeCount > biasOperandID,
  4231. "else operation was misrecognized");
  4232. if (const ExtVectorType *VecTy =
  4233. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  4234. *m_context, parameterTypes[biasOperandID])) {
  4235. if (VecTy->getNumElements() == 1)
  4236. parameterTypes[biasOperandID] = VecTy->getElementType();
  4237. }
  4238. }
  4239. DeclContext *owner = FunctionTemplate->getDeclContext();
  4240. TemplateArgumentList templateArgumentList(
  4241. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  4242. templateArgs.size());
  4243. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4244. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  4245. mlTemplateArgumentList);
  4246. FunctionProtoType::ExtProtoInfo EmptyEPI;
  4247. QualType functionType = m_context->getFunctionType(
  4248. parameterTypes[0],
  4249. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  4250. EmptyEPI, paramMods);
  4251. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4252. FunctionProtoTypeLoc Proto =
  4253. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4254. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  4255. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4256. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  4257. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  4258. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  4259. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  4260. Params.push_back(paramDecl);
  4261. }
  4262. QualType T = TInfo->getType();
  4263. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  4264. CXXMethodDecl* method = CXXMethodDecl::Create(
  4265. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4266. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4267. // Add intrinsic attr
  4268. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  4269. // Record this function template specialization.
  4270. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  4271. *m_context, templateArgs.data(), templateArgs.size());
  4272. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  4273. // Attach the parameters
  4274. for (unsigned P = 0; P < Params.size(); ++P) {
  4275. Params[P]->setOwningFunction(method);
  4276. Proto.setParam(P, Params[P]);
  4277. }
  4278. method->setParams(Params);
  4279. // Adjust access.
  4280. method->setAccess(AccessSpecifier::AS_public);
  4281. FunctionTemplate->setAccess(method->getAccess());
  4282. return method;
  4283. }
  4284. // Overload support.
  4285. UINT64 ScoreCast(QualType leftType, QualType rightType);
  4286. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  4287. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  4288. unsigned GetNumElements(QualType anyType);
  4289. unsigned GetNumBasicElements(QualType anyType);
  4290. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  4291. QualType GetNthElementType(QualType type, unsigned index);
  4292. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  4293. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4294. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4295. };
  4296. TYPE_CONVERSION_REMARKS HLSLExternalSource::RemarksUnused = TYPE_CONVERSION_REMARKS::TYPE_CONVERSION_NONE;
  4297. ImplicitConversionKind HLSLExternalSource::ImplicitConversionKindUnused = ImplicitConversionKind::ICK_Identity;
  4298. // Use this class to flatten a type into HLSL primitives and iterate through them.
  4299. class FlattenedTypeIterator
  4300. {
  4301. private:
  4302. enum FlattenedIterKind {
  4303. FK_Simple,
  4304. FK_Fields,
  4305. FK_Expressions,
  4306. FK_IncompleteArray,
  4307. FK_Bases,
  4308. };
  4309. // Use this struct to represent a specific point in the tracked tree.
  4310. struct FlattenedTypeTracker {
  4311. QualType Type; // Type at this position in the tree.
  4312. unsigned int Count; // Count of consecutive types
  4313. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  4314. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  4315. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  4316. RecordDecl::field_iterator EndField; // STL-style end of fields.
  4317. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  4318. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  4319. FlattenedIterKind IterKind; // Kind of tracker.
  4320. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  4321. FlattenedTypeTracker(QualType type)
  4322. : Type(type), Count(0), CurrentExpr(nullptr),
  4323. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  4324. FlattenedTypeTracker(QualType type, unsigned int count,
  4325. MultiExprArg::iterator expression)
  4326. : Type(type), Count(count), CurrentExpr(expression),
  4327. IterKind(FK_Simple), IsConsidered(false) {}
  4328. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  4329. RecordDecl::field_iterator end)
  4330. : Type(type), Count(0), CurrentField(current), EndField(end),
  4331. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  4332. FlattenedTypeTracker(MultiExprArg::iterator current,
  4333. MultiExprArg::iterator end)
  4334. : Count(0), CurrentExpr(current), EndExpr(end),
  4335. IterKind(FK_Expressions), IsConsidered(false) {}
  4336. FlattenedTypeTracker(QualType type,
  4337. CXXRecordDecl::base_class_iterator current,
  4338. CXXRecordDecl::base_class_iterator end)
  4339. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  4340. IterKind(FK_Bases), IsConsidered(false) {}
  4341. /// <summary>Gets the current expression if one is available.</summary>
  4342. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  4343. /// <summary>Replaces the current expression.</summary>
  4344. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  4345. };
  4346. HLSLExternalSource& m_source; // Source driving the iteration.
  4347. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  4348. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  4349. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  4350. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  4351. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  4352. QualType m_firstType; // Name of first type found, used for diagnostics.
  4353. SourceLocation m_loc; // Location used for diagnostics.
  4354. static const size_t MaxTypeDepth = 100;
  4355. void advanceLeafTracker();
  4356. /// <summary>Consumes leaves.</summary>
  4357. void consumeLeaf();
  4358. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  4359. bool considerLeaf();
  4360. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  4361. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  4362. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  4363. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  4364. public:
  4365. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  4366. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  4367. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  4368. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  4369. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  4370. QualType getCurrentElement() const;
  4371. /// <summary>Get the number of repeated current elements.</summary>
  4372. unsigned int getCurrentElementSize() const;
  4373. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  4374. bool hasCurrentElement() const;
  4375. /// <summary>Consumes count elements on this iterator.</summary>
  4376. void advanceCurrentElement(unsigned int count);
  4377. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  4378. unsigned int countRemaining();
  4379. /// <summary>Gets the current expression if one is available.</summary>
  4380. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  4381. /// <summary>Replaces the current expression.</summary>
  4382. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  4383. struct ComparisonResult
  4384. {
  4385. unsigned int LeftCount;
  4386. unsigned int RightCount;
  4387. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  4388. bool AreElementsEqual;
  4389. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  4390. bool CanConvertElements;
  4391. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  4392. bool IsConvertibleAndEqualLength() const {
  4393. return CanConvertElements && LeftCount == RightCount;
  4394. }
  4395. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  4396. bool IsConvertibleAndLeftLonger() const {
  4397. return CanConvertElements && LeftCount > RightCount;
  4398. }
  4399. bool IsRightLonger() const {
  4400. return RightCount > LeftCount;
  4401. }
  4402. bool IsEqualLength() const {
  4403. return LeftCount == RightCount;
  4404. }
  4405. };
  4406. static ComparisonResult CompareIterators(
  4407. HLSLExternalSource& source, SourceLocation loc,
  4408. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  4409. static ComparisonResult CompareTypes(
  4410. HLSLExternalSource& source,
  4411. SourceLocation leftLoc, SourceLocation rightLoc,
  4412. QualType left, QualType right);
  4413. // Compares the arguments to initialize the left type, modifying them if necessary.
  4414. static ComparisonResult CompareTypesForInit(
  4415. HLSLExternalSource& source, QualType left, MultiExprArg args,
  4416. SourceLocation leftLoc, SourceLocation rightLoc);
  4417. };
  4418. static
  4419. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  4420. {
  4421. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  4422. if (specialization) {
  4423. const TemplateArgumentList& list = specialization->getTemplateArgs();
  4424. if (list.size()) {
  4425. if (list[0].getKind() == TemplateArgument::ArgKind::Type)
  4426. return list[0].getAsType();
  4427. }
  4428. }
  4429. return QualType();
  4430. }
  4431. void HLSLExternalSource::AddBaseTypes()
  4432. {
  4433. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4434. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4435. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4436. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4437. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4438. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->HalfFloatTy : m_context->HalfTy;
  4439. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4440. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4441. m_baseTypes[HLSLScalarType_float_min10] = m_context->Min10FloatTy;
  4442. m_baseTypes[HLSLScalarType_float_min16] = m_context->Min16FloatTy;
  4443. m_baseTypes[HLSLScalarType_int_min12] = m_context->Min12IntTy;
  4444. m_baseTypes[HLSLScalarType_int_min16] = m_context->Min16IntTy;
  4445. m_baseTypes[HLSLScalarType_uint_min16] = m_context->Min16UIntTy;
  4446. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4447. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4448. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4449. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4450. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4451. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4452. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4453. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4454. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4455. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4456. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4457. }
  4458. void HLSLExternalSource::AddHLSLScalarTypes()
  4459. {
  4460. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4461. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4462. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4463. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4464. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4465. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4466. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4467. }
  4468. void HLSLExternalSource::AddHLSLStringType() {
  4469. m_hlslStringType = m_context->HLSLStringTy;
  4470. }
  4471. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4472. _In_ FunctionTemplateDecl* functionTemplate,
  4473. QualType objectElement,
  4474. const FindStructBasicTypeResult& findResult)
  4475. {
  4476. DXASSERT_NOMSG(functionTemplate != nullptr);
  4477. DXASSERT_NOMSG(!objectElement.isNull());
  4478. DXASSERT_NOMSG(findResult.Found());
  4479. DXASSERT(
  4480. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4481. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4482. // Subscript is templated only on its return type.
  4483. // Create the template argument.
  4484. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4485. QualType resultType = objectElement;
  4486. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  4487. resultType = m_context->getLValueReferenceType(resultType);
  4488. TemplateArgument templateArgument(resultType);
  4489. unsigned subscriptCardinality =
  4490. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4491. QualType subscriptIndexType =
  4492. subscriptCardinality == 1
  4493. ? m_context->UnsignedIntTy
  4494. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4495. subscriptCardinality);
  4496. // Look for an existing specialization.
  4497. void* InsertPos = nullptr;
  4498. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4499. if (SpecFunc != nullptr) {
  4500. return SpecFunc;
  4501. }
  4502. // Create a new specialization.
  4503. DeclContext* owner = functionTemplate->getDeclContext();
  4504. TemplateArgumentList templateArgumentList(
  4505. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4506. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4507. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4508. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4509. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4510. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4511. QualType functionType = m_context->getFunctionType(
  4512. resultType, subscriptIndexType, templateEPI, None);
  4513. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4514. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4515. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4516. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4517. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4518. QualType T = TInfo->getType();
  4519. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4520. CXXMethodDecl* method = CXXMethodDecl::Create(
  4521. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4522. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4523. // Add subscript attribute
  4524. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4525. // Record this function template specialization.
  4526. method->setFunctionTemplateSpecialization(functionTemplate,
  4527. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4528. // Attach the parameters
  4529. indexerParam->setOwningFunction(method);
  4530. Proto.setParam(0, indexerParam);
  4531. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4532. // Adjust access.
  4533. method->setAccess(AccessSpecifier::AS_public);
  4534. functionTemplate->setAccess(method->getAccess());
  4535. return method;
  4536. }
  4537. /// <summary>
  4538. /// This routine combines Source into Target. If you have a symmetric operation
  4539. /// and want to treat either side equally you should call it twice, swapping the
  4540. /// parameter order.
  4541. /// </summary>
  4542. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4543. _Out_opt_ ArBasicKind *pCombined) {
  4544. if (Target == Source) {
  4545. AssignOpt(Target, pCombined);
  4546. return true;
  4547. }
  4548. if (Source == AR_OBJECT_NULL) {
  4549. // NULL is valid for any object type.
  4550. AssignOpt(Target, pCombined);
  4551. return true;
  4552. }
  4553. switch (Target) {
  4554. AR_BASIC_ROBJECT_CASES:
  4555. if (Source == AR_OBJECT_STATEBLOCK) {
  4556. AssignOpt(Target, pCombined);
  4557. return true;
  4558. }
  4559. break;
  4560. AR_BASIC_TEXTURE_CASES:
  4561. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4562. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4563. AssignOpt(Target, pCombined);
  4564. return true;
  4565. }
  4566. break;
  4567. case AR_OBJECT_SAMPLERCOMPARISON:
  4568. if (Source == AR_OBJECT_STATEBLOCK) {
  4569. AssignOpt(Target, pCombined);
  4570. return true;
  4571. }
  4572. break;
  4573. default:
  4574. // Not a combinable target.
  4575. break;
  4576. }
  4577. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4578. return false;
  4579. }
  4580. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4581. HLSLExternalSource *pHLSLExternalSource) {
  4582. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4583. llvm::APInt val = intLit->getValue();
  4584. unsigned width = val.getActiveBits();
  4585. bool isNeg = val.isNegative();
  4586. if (isNeg) {
  4587. // Signed.
  4588. if (width <= 32)
  4589. return ArBasicKind::AR_BASIC_INT32;
  4590. else
  4591. return ArBasicKind::AR_BASIC_INT64;
  4592. } else {
  4593. // Unsigned.
  4594. if (width <= 32)
  4595. return ArBasicKind::AR_BASIC_UINT32;
  4596. else
  4597. return ArBasicKind::AR_BASIC_UINT64;
  4598. }
  4599. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4600. llvm::APFloat val = floatLit->getValue();
  4601. unsigned width = val.getSizeInBits(val.getSemantics());
  4602. if (width <= 16)
  4603. return ArBasicKind::AR_BASIC_FLOAT16;
  4604. else if (width <= 32)
  4605. return ArBasicKind::AR_BASIC_FLOAT32;
  4606. else
  4607. return AR_BASIC_FLOAT64;
  4608. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4609. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4610. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4611. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4612. kind = ArBasicKind::AR_BASIC_INT32;
  4613. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4614. kind = ArBasicKind::AR_BASIC_INT64;
  4615. }
  4616. return kind;
  4617. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4618. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4619. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4620. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4621. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4622. CombineBasicTypes(kind, kind1, &kind);
  4623. return kind;
  4624. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4625. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4626. return kind;
  4627. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4628. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4629. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4630. CombineBasicTypes(kind, kind1, &kind);
  4631. return kind;
  4632. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4633. // Use target Type for cast.
  4634. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4635. return kind;
  4636. } else {
  4637. // Could only be function call.
  4638. CallExpr *CE = cast<CallExpr>(litExpr);
  4639. // TODO: calculate the function call result.
  4640. if (CE->getNumArgs() == 1)
  4641. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4642. else {
  4643. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4644. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4645. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4646. CombineBasicTypes(kind, kindI, &kind);
  4647. }
  4648. return kind;
  4649. }
  4650. }
  4651. }
  4652. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4653. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4654. if (kind == *pCT)
  4655. return true;
  4656. pCT++;
  4657. }
  4658. return false;
  4659. }
  4660. static ArBasicKind
  4661. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4662. unsigned uLegalComponentTypes,
  4663. HLSLExternalSource *pHLSLExternalSource) {
  4664. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4665. ArBasicKind defaultKind = *pCT;
  4666. // Use first none literal kind as defaultKind.
  4667. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4668. ArBasicKind kind = *pCT;
  4669. pCT++;
  4670. // Skip literal type.
  4671. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4672. continue;
  4673. defaultKind = kind;
  4674. break;
  4675. }
  4676. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4677. if (kind == AR_BASIC_LITERAL_INT) {
  4678. // Search for match first.
  4679. // For literal arg which don't affect return type, the search should always success.
  4680. // Unless use literal int on a float parameter.
  4681. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4682. return litKind;
  4683. // Return the default.
  4684. return defaultKind;
  4685. }
  4686. else {
  4687. // Search for float32 first.
  4688. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4689. return AR_BASIC_FLOAT32;
  4690. // Search for float64.
  4691. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4692. return AR_BASIC_FLOAT64;
  4693. // return default.
  4694. return defaultKind;
  4695. }
  4696. }
  4697. _Use_decl_annotations_ bool
  4698. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4699. QualType objectElement) {
  4700. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4701. switch (op) {
  4702. case IntrinsicOp::MOP_Sample:
  4703. case IntrinsicOp::MOP_SampleBias:
  4704. case IntrinsicOp::MOP_SampleCmp:
  4705. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4706. case IntrinsicOp::MOP_SampleGrad:
  4707. case IntrinsicOp::MOP_SampleLevel: {
  4708. ArBasicKind kind = GetTypeElementKind(objectElement);
  4709. UINT uBits = GET_BPROP_BITS(kind);
  4710. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4711. } break;
  4712. default:
  4713. return true;
  4714. }
  4715. }
  4716. _Use_decl_annotations_
  4717. bool HLSLExternalSource::MatchArguments(
  4718. const HLSL_INTRINSIC* pIntrinsic,
  4719. QualType objectElement,
  4720. QualType functionTemplateTypeArg,
  4721. ArrayRef<Expr *> Args,
  4722. std::vector<QualType> *argTypesVector)
  4723. {
  4724. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4725. DXASSERT_NOMSG(argTypesVector != nullptr);
  4726. std::vector<QualType> &argTypes = *argTypesVector;
  4727. argTypes.clear();
  4728. argTypes.resize(1 + Args.size()); // +1 for return type
  4729. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  4730. static const UINT UnusedSize = 0xFF;
  4731. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4732. #define CAB(_) { if (!(_)) return false; }
  4733. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4734. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4735. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4736. // Reset infos
  4737. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4738. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4739. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4740. const unsigned retArgIdx = 0;
  4741. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4742. // Populate the template for each argument.
  4743. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4744. ArrayRef<Expr*>::iterator end = Args.end();
  4745. unsigned int iArg = 1;
  4746. for (; iterArg != end; ++iterArg) {
  4747. Expr* pCallArg = *iterArg;
  4748. // If vararg is reached, we can break out of this loop.
  4749. if(pIntrinsic->pArgs[iArg].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  4750. break;
  4751. // Check bounds for non-variadic functions.
  4752. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  4753. return false;
  4754. }
  4755. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  4756. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  4757. DXASSERT(isVariadic ||
  4758. pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS,
  4759. "found vararg for non-variadic function");
  4760. QualType pType = pCallArg->getType();
  4761. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  4762. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  4763. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_RAYDESC) {
  4764. if (TypeInfoShapeKind == AR_TOBJ_COMPOUND) {
  4765. if (CXXRecordDecl *pDecl = pType->getAsCXXRecordDecl()) {
  4766. int index = FindObjectBasicKindIndex(pDecl);
  4767. if (index != -1 && AR_OBJECT_RAY_DESC == g_ArBasicKindsAsTypes[index]) {
  4768. ++iArg;
  4769. continue;
  4770. }
  4771. }
  4772. }
  4773. m_sema->Diag(pCallArg->getExprLoc(),
  4774. diag::err_hlsl_ray_desc_required);
  4775. return false;
  4776. }
  4777. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4778. DXASSERT(objectElement.isNull(), "");
  4779. QualType Ty = pCallArg->getType();
  4780. // Must be user define type for LICOMPTYPE_USER_DEFINED_TYPE arg.
  4781. if (TypeInfoShapeKind != AR_TOBJ_COMPOUND) {
  4782. m_sema->Diag(pCallArg->getExprLoc(),
  4783. diag::err_hlsl_no_struct_user_defined_type);
  4784. return false;
  4785. }
  4786. objectElement = Ty;
  4787. ++iArg;
  4788. continue;
  4789. }
  4790. // If we are a type and templateID requires one, this isn't a match.
  4791. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  4792. || pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  4793. ++iArg;
  4794. continue;
  4795. }
  4796. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  4797. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  4798. bool affectRetType =
  4799. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  4800. // For literal arg which don't affect return type, find concrete type.
  4801. // For literal arg affect return type,
  4802. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  4803. // where all argumentss are literal.
  4804. // CombineBasicTypes will cover the rest cases.
  4805. if (!affectRetType) {
  4806. TypeInfoEltKind = ConcreteLiteralType(
  4807. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  4808. }
  4809. }
  4810. UINT TypeInfoCols = 1;
  4811. UINT TypeInfoRows = 1;
  4812. switch (TypeInfoShapeKind) {
  4813. case AR_TOBJ_MATRIX:
  4814. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  4815. break;
  4816. case AR_TOBJ_VECTOR:
  4817. TypeInfoCols = GetHLSLVecSize(pType);
  4818. break;
  4819. case AR_TOBJ_BASIC:
  4820. case AR_TOBJ_OBJECT:
  4821. case AR_TOBJ_STRING:
  4822. break;
  4823. default:
  4824. return false; // no struct, arrays or void
  4825. }
  4826. DXASSERT(
  4827. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  4828. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  4829. // Compare template
  4830. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  4831. ((AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  4832. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind))) {
  4833. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  4834. }
  4835. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  4836. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  4837. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  4838. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  4839. return false;
  4840. }
  4841. }
  4842. else {
  4843. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  4844. return false;
  4845. }
  4846. }
  4847. DXASSERT(
  4848. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4849. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4850. // Merge ComponentTypes
  4851. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4852. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4853. }
  4854. else {
  4855. if (!CombineBasicTypes(
  4856. ComponentType[pIntrinsicArg->uComponentTypeId],
  4857. TypeInfoEltKind,
  4858. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4859. return false;
  4860. }
  4861. }
  4862. // Rows
  4863. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4864. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4865. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4866. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4867. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4868. uSpecialSize[uSpecialId] = TypeInfoRows;
  4869. }
  4870. }
  4871. else {
  4872. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4873. return false;
  4874. }
  4875. }
  4876. }
  4877. // Columns
  4878. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4879. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4880. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4881. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4882. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4883. uSpecialSize[uSpecialId] = TypeInfoCols;
  4884. }
  4885. }
  4886. else {
  4887. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4888. return false;
  4889. }
  4890. }
  4891. }
  4892. // Usage
  4893. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4894. if (pCallArg->getType().isConstQualified()) {
  4895. // Can't use a const type in an out or inout parameter.
  4896. return false;
  4897. }
  4898. }
  4899. iArg++;
  4900. }
  4901. DXASSERT(isVariadic || iterArg == end,
  4902. "otherwise the argument list wasn't fully processed");
  4903. // Default template and component type for return value
  4904. if (pIntrinsic->pArgs[0].qwUsage
  4905. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE
  4906. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_FUNCTION) {
  4907. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4908. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4909. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4910. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4911. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4912. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4913. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4914. // half return type should map to float for min precision
  4915. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  4916. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  4917. getSema()->getLangOpts().UseMinPrecision) {
  4918. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4919. ArBasicKind::AR_BASIC_FLOAT32;
  4920. }
  4921. else {
  4922. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4923. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4924. }
  4925. }
  4926. }
  4927. }
  4928. }
  4929. // Make sure all template, component type, and texture type selections are valid.
  4930. for (size_t i = 0; i < Args.size() + 1; i++) {
  4931. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4932. // If vararg is reached, we can break out of this loop.
  4933. if(pIntrinsic->pArgs[i].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  4934. break;
  4935. // Check template.
  4936. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  4937. || pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  4938. continue; // Already verified that this is available.
  4939. }
  4940. if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4941. continue;
  4942. }
  4943. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4944. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4945. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4946. Template[i] = *pTT;
  4947. }
  4948. else if(AR_TOBJ_STRING == Template[i] && *pTT == AR_TOBJ_OBJECT) {
  4949. Template[i] = *pTT;
  4950. }
  4951. else {
  4952. while (AR_TOBJ_UNKNOWN != *pTT) {
  4953. if (Template[i] == *pTT)
  4954. break;
  4955. pTT++;
  4956. }
  4957. }
  4958. if (AR_TOBJ_UNKNOWN == *pTT)
  4959. return false;
  4960. }
  4961. else if (pTT) {
  4962. Template[i] = *pTT;
  4963. }
  4964. // Check component type.
  4965. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4966. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4967. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4968. if (ComponentType[i] == *pCT)
  4969. break;
  4970. pCT++;
  4971. }
  4972. // has to be a strict match
  4973. if (*pCT == AR_BASIC_NOCAST)
  4974. return false;
  4975. // If it is an object, see if it can be cast to the first thing in the
  4976. // list, otherwise move on to next intrinsic.
  4977. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4978. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4979. return false;
  4980. }
  4981. }
  4982. if (AR_BASIC_UNKNOWN == *pCT) {
  4983. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4984. }
  4985. }
  4986. else if (pCT) {
  4987. ComponentType[i] = *pCT;
  4988. }
  4989. }
  4990. // Default to a void return type.
  4991. argTypes[0] = m_context->VoidTy;
  4992. // Default specials sizes.
  4993. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  4994. if (UnusedSize == uSpecialSize[i]) {
  4995. uSpecialSize[i] = 1;
  4996. }
  4997. }
  4998. // Populate argTypes.
  4999. for (size_t i = 0; i <= Args.size(); i++) {
  5000. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  5001. // If vararg is reached, we can break out of this loop.
  5002. if (pArgument->uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5003. break;
  5004. if (!pArgument->qwUsage)
  5005. continue;
  5006. QualType pNewType;
  5007. unsigned int quals = 0; // qualifications for this argument
  5008. // If we have no type, set it to our input type (templatized)
  5009. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  5010. // Use the templated input type, but resize it if the
  5011. // intrinsic's rows/cols isn't 0
  5012. if (pArgument->uRows && pArgument->uCols) {
  5013. UINT uRows, uCols = 0;
  5014. // if type is overriden, use new type size, for
  5015. // now it only supports scalars
  5016. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5017. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5018. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5019. uRows = uSpecialSize[uSpecialId];
  5020. }
  5021. else if (pArgument->uRows > 0) {
  5022. uRows = pArgument->uRows;
  5023. }
  5024. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5025. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5026. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5027. uCols = uSpecialSize[uSpecialId];
  5028. }
  5029. else if (pArgument->uCols > 0) {
  5030. uCols = pArgument->uCols;
  5031. }
  5032. // 1x1 numeric outputs are always scalar.. since these
  5033. // are most flexible
  5034. if ((1 == uCols) && (1 == uRows)) {
  5035. pNewType = objectElement;
  5036. if (pNewType.isNull()) {
  5037. return false;
  5038. }
  5039. }
  5040. else {
  5041. // non-scalars unsupported right now since nothing
  5042. // uses it, would have to create either a type
  5043. // list for sub-structures or just resize the
  5044. // given type
  5045. // VH(E_NOTIMPL);
  5046. return false;
  5047. }
  5048. }
  5049. else {
  5050. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  5051. if (objectElement.isNull()) {
  5052. return false;
  5053. }
  5054. pNewType = objectElement;
  5055. }
  5056. }
  5057. else if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5058. if (functionTemplateTypeArg.isNull()) {
  5059. if (i == 0) {
  5060. // [RW]ByteAddressBuffer.Load, default to uint
  5061. pNewType = m_context->UnsignedIntTy;
  5062. }
  5063. else {
  5064. // [RW]ByteAddressBuffer.Store, default to argument type
  5065. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5066. if (const BuiltinType *BuiltinTy = pNewType->getAs<BuiltinType>()) {
  5067. // For backcompat, ensure that Store(0, 42 or 42.0) matches a uint/float overload
  5068. // rather than a uint64_t/double one.
  5069. if (BuiltinTy->getKind() == BuiltinType::LitInt) {
  5070. pNewType = m_context->UnsignedIntTy;
  5071. } else if (BuiltinTy->getKind() == BuiltinType::LitFloat) {
  5072. pNewType = m_context->FloatTy;
  5073. }
  5074. }
  5075. }
  5076. }
  5077. else {
  5078. pNewType = functionTemplateTypeArg;
  5079. }
  5080. }
  5081. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5082. if (objectElement.isNull()) {
  5083. return false;
  5084. }
  5085. pNewType = objectElement;
  5086. }
  5087. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2D
  5088. || pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2DARRAY) {
  5089. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5090. }
  5091. else {
  5092. ArBasicKind pEltType;
  5093. // ComponentType, if the Id is special then it gets the
  5094. // component type from the first component of the type, if
  5095. // we need more (for the second component, e.g.), then we
  5096. // can use more specials, etc.
  5097. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  5098. if (objectElement.isNull()) {
  5099. return false;
  5100. }
  5101. pEltType = GetTypeElementKind(objectElement);
  5102. if (!IsValidBasicKind(pEltType)) {
  5103. // This can happen with Texture2D<Struct> or other invalid declarations
  5104. return false;
  5105. }
  5106. }
  5107. else {
  5108. pEltType = ComponentType[pArgument->uComponentTypeId];
  5109. DXASSERT_VALIDBASICKIND(pEltType);
  5110. }
  5111. UINT uRows, uCols;
  5112. // Rows
  5113. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5114. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5115. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5116. uRows = uSpecialSize[uSpecialId];
  5117. }
  5118. else {
  5119. uRows = pArgument->uRows;
  5120. }
  5121. // Cols
  5122. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5123. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5124. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5125. uCols = uSpecialSize[uSpecialId];
  5126. }
  5127. else {
  5128. uCols = pArgument->uCols;
  5129. }
  5130. // Verify that the final results are in bounds.
  5131. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  5132. // Const
  5133. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  5134. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  5135. qwQual |= AR_QUAL_CONST;
  5136. DXASSERT_VALIDBASICKIND(pEltType);
  5137. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  5138. }
  5139. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  5140. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  5141. // TODO: support out modifier
  5142. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  5143. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  5144. //}
  5145. }
  5146. // For variadic functions, we need to add the additional arguments here.
  5147. if(isVariadic) {
  5148. for (; iArg <= Args.size(); ++iArg) {
  5149. argTypes[iArg] = Args[iArg - 1]->getType().getNonReferenceType();
  5150. }
  5151. } else {
  5152. DXASSERT(iArg == pIntrinsic->uNumArgs,
  5153. "In the absence of varargs, a successful match would indicate we "
  5154. "have as many arguments and types as the intrinsic template");
  5155. }
  5156. return true;
  5157. #undef CAB
  5158. }
  5159. _Use_decl_annotations_
  5160. HLSLExternalSource::FindStructBasicTypeResult
  5161. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  5162. {
  5163. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5164. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  5165. // may be a simple class, such as RWByteAddressBuffer.
  5166. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  5167. // We save the caller from filtering out other types of context (like the translation unit itself).
  5168. if (recordDecl != nullptr)
  5169. {
  5170. int index = FindObjectBasicKindIndex(recordDecl);
  5171. if (index != -1) {
  5172. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  5173. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  5174. }
  5175. }
  5176. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  5177. }
  5178. _Use_decl_annotations_
  5179. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  5180. {
  5181. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5182. DXASSERT_NOMSG(name != nullptr);
  5183. DXASSERT_NOMSG(intrinsics != nullptr);
  5184. DXASSERT_NOMSG(intrinsicCount != nullptr);
  5185. *intrinsics = nullptr;
  5186. *intrinsicCount = 0;
  5187. *name = nullptr;
  5188. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  5189. if (lookup.Found()) {
  5190. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  5191. *name = g_ArBasicTypeNames[lookup.Kind];
  5192. }
  5193. }
  5194. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  5195. {
  5196. return
  5197. // Arithmetic operators.
  5198. Opc == BinaryOperatorKind::BO_Add ||
  5199. Opc == BinaryOperatorKind::BO_AddAssign ||
  5200. Opc == BinaryOperatorKind::BO_Sub ||
  5201. Opc == BinaryOperatorKind::BO_SubAssign ||
  5202. Opc == BinaryOperatorKind::BO_Rem ||
  5203. Opc == BinaryOperatorKind::BO_RemAssign ||
  5204. Opc == BinaryOperatorKind::BO_Div ||
  5205. Opc == BinaryOperatorKind::BO_DivAssign ||
  5206. Opc == BinaryOperatorKind::BO_Mul ||
  5207. Opc == BinaryOperatorKind::BO_MulAssign;
  5208. }
  5209. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  5210. {
  5211. return
  5212. // Arithmetic-and-assignment operators.
  5213. Opc == BinaryOperatorKind::BO_AddAssign ||
  5214. Opc == BinaryOperatorKind::BO_SubAssign ||
  5215. Opc == BinaryOperatorKind::BO_RemAssign ||
  5216. Opc == BinaryOperatorKind::BO_DivAssign ||
  5217. Opc == BinaryOperatorKind::BO_MulAssign ||
  5218. // Bitwise-and-assignment operators.
  5219. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5220. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5221. Opc == BinaryOperatorKind::BO_AndAssign ||
  5222. Opc == BinaryOperatorKind::BO_OrAssign ||
  5223. Opc == BinaryOperatorKind::BO_XorAssign;
  5224. }
  5225. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  5226. {
  5227. return
  5228. Opc == BinaryOperatorKind::BO_AndAssign ||
  5229. Opc == BinaryOperatorKind::BO_OrAssign ||
  5230. Opc == BinaryOperatorKind::BO_XorAssign;
  5231. }
  5232. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  5233. {
  5234. return
  5235. Opc == BinaryOperatorKind::BO_Shl ||
  5236. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5237. Opc == BinaryOperatorKind::BO_Shr ||
  5238. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5239. Opc == BinaryOperatorKind::BO_And ||
  5240. Opc == BinaryOperatorKind::BO_AndAssign ||
  5241. Opc == BinaryOperatorKind::BO_Or ||
  5242. Opc == BinaryOperatorKind::BO_OrAssign ||
  5243. Opc == BinaryOperatorKind::BO_Xor ||
  5244. Opc == BinaryOperatorKind::BO_XorAssign;
  5245. }
  5246. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  5247. {
  5248. return
  5249. Opc == BinaryOperatorKind::BO_Shl ||
  5250. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5251. Opc == BinaryOperatorKind::BO_Shr ||
  5252. Opc == BinaryOperatorKind::BO_ShrAssign;
  5253. }
  5254. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  5255. {
  5256. return
  5257. Opc == BinaryOperatorKind::BO_EQ ||
  5258. Opc == BinaryOperatorKind::BO_NE;
  5259. }
  5260. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  5261. {
  5262. return
  5263. Opc == BinaryOperatorKind::BO_LT ||
  5264. Opc == BinaryOperatorKind::BO_GT ||
  5265. Opc == BinaryOperatorKind::BO_LE ||
  5266. Opc == BinaryOperatorKind::BO_GE;
  5267. }
  5268. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  5269. {
  5270. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  5271. }
  5272. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  5273. {
  5274. return
  5275. Opc == BinaryOperatorKind::BO_LAnd ||
  5276. Opc == BinaryOperatorKind::BO_LOr;
  5277. }
  5278. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  5279. {
  5280. return
  5281. BinaryOperatorKindIsArithmetic(Opc) ||
  5282. BinaryOperatorKindIsOrderComparison(Opc) ||
  5283. BinaryOperatorKindIsLogical(Opc);
  5284. }
  5285. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  5286. {
  5287. return BinaryOperatorKindIsBitwise(Opc);
  5288. }
  5289. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  5290. {
  5291. return
  5292. BinaryOperatorKindIsBitwise(Opc) ||
  5293. BinaryOperatorKindIsArithmetic(Opc);
  5294. }
  5295. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  5296. {
  5297. return Opc == UnaryOperatorKind::UO_Not;
  5298. }
  5299. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  5300. {
  5301. return
  5302. Opc == UnaryOperatorKind::UO_LNot ||
  5303. Opc == UnaryOperatorKind::UO_Plus ||
  5304. Opc == UnaryOperatorKind::UO_Minus ||
  5305. // The omission in fxc caused objects and structs to accept this.
  5306. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5307. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5308. }
  5309. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  5310. {
  5311. return
  5312. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5313. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5314. }
  5315. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  5316. {
  5317. return
  5318. Opc == UnaryOperatorKind::UO_Not ||
  5319. Opc == UnaryOperatorKind::UO_Plus ||
  5320. Opc == UnaryOperatorKind::UO_Minus;
  5321. }
  5322. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  5323. {
  5324. return
  5325. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5326. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5327. }
  5328. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  5329. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  5330. }
  5331. /// <summary>
  5332. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  5333. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  5334. /// </summary>
  5335. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  5336. {
  5337. return
  5338. value == AR_TOBJ_BASIC ||
  5339. value == AR_TOBJ_MATRIX ||
  5340. value == AR_TOBJ_VECTOR;
  5341. }
  5342. static bool IsBasicKindIntegral(ArBasicKind value)
  5343. {
  5344. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  5345. }
  5346. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  5347. {
  5348. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  5349. }
  5350. static bool IsBasicKindNumeric(ArBasicKind value)
  5351. {
  5352. return GetBasicKindProps(value) & BPROP_NUMERIC;
  5353. }
  5354. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  5355. {
  5356. // An invalid expression is pass-through at this point.
  5357. if (E.isInvalid())
  5358. {
  5359. return E;
  5360. }
  5361. QualType qt = E.get()->getType();
  5362. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  5363. if (elementKind != AR_BASIC_BOOL)
  5364. {
  5365. return E;
  5366. }
  5367. // Construct a scalar/vector/matrix type with the same shape as E.
  5368. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  5369. QualType targetType;
  5370. UINT colCount, rowCount;
  5371. GetRowsAndColsForAny(qt, rowCount, colCount);
  5372. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  5373. if (E.get()->isLValue()) {
  5374. E = m_sema->DefaultLvalueConversion(E.get()).get();
  5375. }
  5376. switch (objectKind)
  5377. {
  5378. case AR_TOBJ_SCALAR:
  5379. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5380. case AR_TOBJ_ARRAY:
  5381. case AR_TOBJ_VECTOR:
  5382. case AR_TOBJ_MATRIX:
  5383. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5384. default:
  5385. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  5386. }
  5387. return E;
  5388. }
  5389. _Use_decl_annotations_
  5390. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  5391. {
  5392. DXASSERT_NOMSG(pTypeInfo != nullptr);
  5393. DXASSERT_NOMSG(!type.isNull());
  5394. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  5395. // TODO: Get* functions used here add up to a bunch of redundant code.
  5396. // Try to inline that here, making it cheaper to use this function
  5397. // when retrieving multiple properties.
  5398. pTypeInfo->ObjKind = GetTypeElementKind(type);
  5399. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  5400. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  5401. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  5402. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  5403. }
  5404. // Highest possible score (i.e., worst possible score).
  5405. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  5406. // Leave the first two score bits to handle higher-level
  5407. // variations like target type.
  5408. #define SCORE_MIN_SHIFT 2
  5409. // Space out scores to allow up to 128 parameters to
  5410. // vary between score sets spill into each other.
  5411. #define SCORE_PARAM_SHIFT 7
  5412. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  5413. if (anyType.isNull()) {
  5414. return 0;
  5415. }
  5416. anyType = GetStructuralForm(anyType);
  5417. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5418. switch (kind) {
  5419. case AR_TOBJ_BASIC:
  5420. case AR_TOBJ_OBJECT:
  5421. case AR_TOBJ_STRING:
  5422. return 1;
  5423. case AR_TOBJ_COMPOUND: {
  5424. // TODO: consider caching this value for perf
  5425. unsigned total = 0;
  5426. const RecordType *recordType = anyType->getAs<RecordType>();
  5427. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5428. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5429. while (fi != fend) {
  5430. total += GetNumElements(fi->getType());
  5431. ++fi;
  5432. }
  5433. return total;
  5434. }
  5435. case AR_TOBJ_ARRAY:
  5436. case AR_TOBJ_MATRIX:
  5437. case AR_TOBJ_VECTOR:
  5438. return GetElementCount(anyType);
  5439. default:
  5440. DXASSERT(kind == AR_TOBJ_VOID,
  5441. "otherwise the type cannot be classified or is not supported");
  5442. return 0;
  5443. }
  5444. }
  5445. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  5446. if (anyType.isNull()) {
  5447. return 0;
  5448. }
  5449. anyType = GetStructuralForm(anyType);
  5450. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5451. switch (kind) {
  5452. case AR_TOBJ_BASIC:
  5453. case AR_TOBJ_OBJECT:
  5454. case AR_TOBJ_STRING:
  5455. return 1;
  5456. case AR_TOBJ_COMPOUND: {
  5457. // TODO: consider caching this value for perf
  5458. unsigned total = 0;
  5459. const RecordType *recordType = anyType->getAs<RecordType>();
  5460. RecordDecl * RD = recordType->getDecl();
  5461. // Take care base.
  5462. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5463. if (CXXRD->getNumBases()) {
  5464. for (const auto &I : CXXRD->bases()) {
  5465. const CXXRecordDecl *BaseDecl =
  5466. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5467. if (BaseDecl->field_empty())
  5468. continue;
  5469. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5470. total += GetNumBasicElements(parentTy);
  5471. }
  5472. }
  5473. }
  5474. RecordDecl::field_iterator fi = RD->field_begin();
  5475. RecordDecl::field_iterator fend = RD->field_end();
  5476. while (fi != fend) {
  5477. total += GetNumBasicElements(fi->getType());
  5478. ++fi;
  5479. }
  5480. return total;
  5481. }
  5482. case AR_TOBJ_ARRAY: {
  5483. unsigned arraySize = GetElementCount(anyType);
  5484. unsigned eltSize = GetNumBasicElements(
  5485. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  5486. return arraySize * eltSize;
  5487. }
  5488. case AR_TOBJ_MATRIX:
  5489. case AR_TOBJ_VECTOR:
  5490. return GetElementCount(anyType);
  5491. default:
  5492. DXASSERT(kind == AR_TOBJ_VOID,
  5493. "otherwise the type cannot be classified or is not supported");
  5494. return 0;
  5495. }
  5496. }
  5497. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  5498. unsigned leftSize,
  5499. QualType rightType,
  5500. unsigned rightSize) {
  5501. // We can convert from a larger type to a smaller
  5502. // but not a smaller type to a larger so default
  5503. // to just comparing the destination size.
  5504. unsigned uElts = leftSize;
  5505. leftType = GetStructuralForm(leftType);
  5506. rightType = GetStructuralForm(rightType);
  5507. if (leftType->isArrayType() && rightType->isArrayType()) {
  5508. //
  5509. // If we're comparing arrays we don't
  5510. // need to compare every element of
  5511. // the arrays since all elements
  5512. // will have the same type.
  5513. // We only need to compare enough
  5514. // elements that we've tried every
  5515. // possible mix of dst and src elements.
  5516. //
  5517. // TODO: handle multidimensional arrays and arrays of arrays
  5518. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5519. unsigned uDstEltSize = GetNumElements(pDstElt);
  5520. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5521. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5522. if (uDstEltSize == uSrcEltSize) {
  5523. uElts = uDstEltSize;
  5524. } else if (uDstEltSize > uSrcEltSize) {
  5525. // If one size is not an even multiple of the other we need to let the
  5526. // full compare run in order to try all alignments.
  5527. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5528. uElts = uDstEltSize;
  5529. }
  5530. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5531. uElts = uSrcEltSize;
  5532. }
  5533. }
  5534. return uElts;
  5535. }
  5536. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5537. if (type.isNull()) {
  5538. return type;
  5539. }
  5540. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5541. switch (kind) {
  5542. case AR_TOBJ_BASIC:
  5543. case AR_TOBJ_OBJECT:
  5544. case AR_TOBJ_STRING:
  5545. return (index == 0) ? type : QualType();
  5546. case AR_TOBJ_COMPOUND: {
  5547. // TODO: consider caching this value for perf
  5548. const RecordType *recordType = type->getAsStructureType();
  5549. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5550. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5551. while (fi != fend) {
  5552. if (!fi->getType().isNull()) {
  5553. unsigned subElements = GetNumElements(fi->getType());
  5554. if (index < subElements) {
  5555. return GetNthElementType(fi->getType(), index);
  5556. } else {
  5557. index -= subElements;
  5558. }
  5559. }
  5560. ++fi;
  5561. }
  5562. return QualType();
  5563. }
  5564. case AR_TOBJ_ARRAY: {
  5565. unsigned arraySize;
  5566. QualType elementType;
  5567. unsigned elementCount;
  5568. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5569. elementCount = GetElementCount(elementType);
  5570. if (index < elementCount) {
  5571. return GetNthElementType(elementType, index);
  5572. }
  5573. arraySize = GetArraySize(type);
  5574. if (index >= arraySize * elementCount) {
  5575. return QualType();
  5576. }
  5577. return GetNthElementType(elementType, index % elementCount);
  5578. }
  5579. case AR_TOBJ_MATRIX:
  5580. case AR_TOBJ_VECTOR:
  5581. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5582. : QualType();
  5583. default:
  5584. DXASSERT(kind == AR_TOBJ_VOID,
  5585. "otherwise the type cannot be classified or is not supported");
  5586. return QualType();
  5587. }
  5588. }
  5589. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5590. // Eliminate exact matches first, then check for promotions.
  5591. if (leftKind == rightKind) {
  5592. return false;
  5593. }
  5594. switch (rightKind) {
  5595. case AR_BASIC_FLOAT16:
  5596. switch (leftKind) {
  5597. case AR_BASIC_FLOAT32:
  5598. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5599. case AR_BASIC_FLOAT64:
  5600. return true;
  5601. default:
  5602. return false; // No other type is a promotion.
  5603. }
  5604. break;
  5605. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5606. switch (leftKind) {
  5607. case AR_BASIC_FLOAT32:
  5608. case AR_BASIC_FLOAT64:
  5609. return true;
  5610. default:
  5611. return false; // No other type is a promotion.
  5612. }
  5613. break;
  5614. case AR_BASIC_FLOAT32:
  5615. switch (leftKind) {
  5616. case AR_BASIC_FLOAT64:
  5617. return true;
  5618. default:
  5619. return false; // No other type is a promotion.
  5620. }
  5621. break;
  5622. case AR_BASIC_MIN10FLOAT:
  5623. switch (leftKind) {
  5624. case AR_BASIC_MIN16FLOAT:
  5625. case AR_BASIC_FLOAT16:
  5626. case AR_BASIC_FLOAT32:
  5627. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5628. case AR_BASIC_FLOAT64:
  5629. return true;
  5630. default:
  5631. return false; // No other type is a promotion.
  5632. }
  5633. break;
  5634. case AR_BASIC_MIN16FLOAT:
  5635. switch (leftKind) {
  5636. case AR_BASIC_FLOAT16:
  5637. case AR_BASIC_FLOAT32:
  5638. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5639. case AR_BASIC_FLOAT64:
  5640. return true;
  5641. default:
  5642. return false; // No other type is a promotion.
  5643. }
  5644. break;
  5645. case AR_BASIC_INT8:
  5646. case AR_BASIC_UINT8:
  5647. // For backwards compat we consider signed/unsigned the same.
  5648. switch (leftKind) {
  5649. case AR_BASIC_INT16:
  5650. case AR_BASIC_INT32:
  5651. case AR_BASIC_INT64:
  5652. case AR_BASIC_UINT16:
  5653. case AR_BASIC_UINT32:
  5654. case AR_BASIC_UINT64:
  5655. return true;
  5656. default:
  5657. return false; // No other type is a promotion.
  5658. }
  5659. break;
  5660. case AR_BASIC_INT16:
  5661. case AR_BASIC_UINT16:
  5662. // For backwards compat we consider signed/unsigned the same.
  5663. switch (leftKind) {
  5664. case AR_BASIC_INT32:
  5665. case AR_BASIC_INT64:
  5666. case AR_BASIC_UINT32:
  5667. case AR_BASIC_UINT64:
  5668. return true;
  5669. default:
  5670. return false; // No other type is a promotion.
  5671. }
  5672. break;
  5673. case AR_BASIC_INT32:
  5674. case AR_BASIC_UINT32:
  5675. // For backwards compat we consider signed/unsigned the same.
  5676. switch (leftKind) {
  5677. case AR_BASIC_INT64:
  5678. case AR_BASIC_UINT64:
  5679. return true;
  5680. default:
  5681. return false; // No other type is a promotion.
  5682. }
  5683. break;
  5684. case AR_BASIC_MIN12INT:
  5685. switch (leftKind) {
  5686. case AR_BASIC_MIN16INT:
  5687. case AR_BASIC_INT32:
  5688. case AR_BASIC_INT64:
  5689. return true;
  5690. default:
  5691. return false; // No other type is a promotion.
  5692. }
  5693. break;
  5694. case AR_BASIC_MIN16INT:
  5695. switch (leftKind) {
  5696. case AR_BASIC_INT32:
  5697. case AR_BASIC_INT64:
  5698. return true;
  5699. default:
  5700. return false; // No other type is a promotion.
  5701. }
  5702. break;
  5703. case AR_BASIC_MIN16UINT:
  5704. switch (leftKind) {
  5705. case AR_BASIC_UINT32:
  5706. case AR_BASIC_UINT64:
  5707. return true;
  5708. default:
  5709. return false; // No other type is a promotion.
  5710. }
  5711. break;
  5712. }
  5713. return false;
  5714. }
  5715. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5716. // Eliminate exact matches first, then check for casts.
  5717. if (leftKind == rightKind) {
  5718. return false;
  5719. }
  5720. //
  5721. // All minimum-bits types are only considered matches of themselves
  5722. // and thus are not in this table.
  5723. //
  5724. switch (leftKind) {
  5725. case AR_BASIC_LITERAL_INT:
  5726. switch (rightKind) {
  5727. case AR_BASIC_INT8:
  5728. case AR_BASIC_INT16:
  5729. case AR_BASIC_INT32:
  5730. case AR_BASIC_INT64:
  5731. case AR_BASIC_UINT8:
  5732. case AR_BASIC_UINT16:
  5733. case AR_BASIC_UINT32:
  5734. case AR_BASIC_UINT64:
  5735. return false;
  5736. default:
  5737. break; // No other valid cast types
  5738. }
  5739. break;
  5740. case AR_BASIC_INT8:
  5741. switch (rightKind) {
  5742. // For backwards compat we consider signed/unsigned the same.
  5743. case AR_BASIC_LITERAL_INT:
  5744. case AR_BASIC_UINT8:
  5745. return false;
  5746. default:
  5747. break; // No other valid cast types
  5748. }
  5749. break;
  5750. case AR_BASIC_INT16:
  5751. switch (rightKind) {
  5752. // For backwards compat we consider signed/unsigned the same.
  5753. case AR_BASIC_LITERAL_INT:
  5754. case AR_BASIC_UINT16:
  5755. return false;
  5756. default:
  5757. break; // No other valid cast types
  5758. }
  5759. break;
  5760. case AR_BASIC_INT32:
  5761. switch (rightKind) {
  5762. // For backwards compat we consider signed/unsigned the same.
  5763. case AR_BASIC_LITERAL_INT:
  5764. case AR_BASIC_UINT32:
  5765. return false;
  5766. default:
  5767. break; // No other valid cast types.
  5768. }
  5769. break;
  5770. case AR_BASIC_INT64:
  5771. switch (rightKind) {
  5772. // For backwards compat we consider signed/unsigned the same.
  5773. case AR_BASIC_LITERAL_INT:
  5774. case AR_BASIC_UINT64:
  5775. return false;
  5776. default:
  5777. break; // No other valid cast types.
  5778. }
  5779. break;
  5780. case AR_BASIC_UINT8:
  5781. switch (rightKind) {
  5782. // For backwards compat we consider signed/unsigned the same.
  5783. case AR_BASIC_LITERAL_INT:
  5784. case AR_BASIC_INT8:
  5785. return false;
  5786. default:
  5787. break; // No other valid cast types.
  5788. }
  5789. break;
  5790. case AR_BASIC_UINT16:
  5791. switch (rightKind) {
  5792. // For backwards compat we consider signed/unsigned the same.
  5793. case AR_BASIC_LITERAL_INT:
  5794. case AR_BASIC_INT16:
  5795. return false;
  5796. default:
  5797. break; // No other valid cast types.
  5798. }
  5799. break;
  5800. case AR_BASIC_UINT32:
  5801. switch (rightKind) {
  5802. // For backwards compat we consider signed/unsigned the same.
  5803. case AR_BASIC_LITERAL_INT:
  5804. case AR_BASIC_INT32:
  5805. return false;
  5806. default:
  5807. break; // No other valid cast types.
  5808. }
  5809. break;
  5810. case AR_BASIC_UINT64:
  5811. switch (rightKind) {
  5812. // For backwards compat we consider signed/unsigned the same.
  5813. case AR_BASIC_LITERAL_INT:
  5814. case AR_BASIC_INT64:
  5815. return false;
  5816. default:
  5817. break; // No other valid cast types.
  5818. }
  5819. break;
  5820. case AR_BASIC_LITERAL_FLOAT:
  5821. switch (rightKind) {
  5822. case AR_BASIC_LITERAL_FLOAT:
  5823. case AR_BASIC_FLOAT16:
  5824. case AR_BASIC_FLOAT32:
  5825. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5826. case AR_BASIC_FLOAT64:
  5827. return false;
  5828. default:
  5829. break; // No other valid cast types.
  5830. }
  5831. break;
  5832. case AR_BASIC_FLOAT16:
  5833. switch (rightKind) {
  5834. case AR_BASIC_LITERAL_FLOAT:
  5835. return false;
  5836. default:
  5837. break; // No other valid cast types.
  5838. }
  5839. break;
  5840. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5841. switch (rightKind) {
  5842. case AR_BASIC_LITERAL_FLOAT:
  5843. return false;
  5844. default:
  5845. break; // No other valid cast types.
  5846. }
  5847. break;
  5848. case AR_BASIC_FLOAT32:
  5849. switch (rightKind) {
  5850. case AR_BASIC_LITERAL_FLOAT:
  5851. return false;
  5852. default:
  5853. break; // No other valid cast types.
  5854. }
  5855. break;
  5856. case AR_BASIC_FLOAT64:
  5857. switch (rightKind) {
  5858. case AR_BASIC_LITERAL_FLOAT:
  5859. return false;
  5860. default:
  5861. break; // No other valid cast types.
  5862. }
  5863. break;
  5864. default:
  5865. break; // No other relevant targets.
  5866. }
  5867. return true;
  5868. }
  5869. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5870. // Eliminate exact matches first, then check for casts.
  5871. if (leftKind == rightKind) {
  5872. return false;
  5873. }
  5874. //
  5875. // All minimum-bits types are only considered matches of themselves
  5876. // and thus are not in this table.
  5877. //
  5878. switch (leftKind) {
  5879. case AR_BASIC_LITERAL_INT:
  5880. switch (rightKind) {
  5881. case AR_BASIC_INT8:
  5882. case AR_BASIC_INT16:
  5883. case AR_BASIC_INT32:
  5884. case AR_BASIC_INT64:
  5885. case AR_BASIC_UINT8:
  5886. case AR_BASIC_UINT16:
  5887. case AR_BASIC_UINT32:
  5888. case AR_BASIC_UINT64:
  5889. return false;
  5890. default:
  5891. break; // No other valid conversions
  5892. }
  5893. break;
  5894. case AR_BASIC_INT8:
  5895. case AR_BASIC_INT16:
  5896. case AR_BASIC_INT32:
  5897. case AR_BASIC_INT64:
  5898. case AR_BASIC_UINT8:
  5899. case AR_BASIC_UINT16:
  5900. case AR_BASIC_UINT32:
  5901. case AR_BASIC_UINT64:
  5902. switch (rightKind) {
  5903. case AR_BASIC_LITERAL_INT:
  5904. return false;
  5905. default:
  5906. break; // No other valid conversions
  5907. }
  5908. break;
  5909. case AR_BASIC_LITERAL_FLOAT:
  5910. switch (rightKind) {
  5911. case AR_BASIC_LITERAL_FLOAT:
  5912. case AR_BASIC_FLOAT16:
  5913. case AR_BASIC_FLOAT32:
  5914. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5915. case AR_BASIC_FLOAT64:
  5916. return false;
  5917. default:
  5918. break; // No other valid conversions
  5919. }
  5920. break;
  5921. case AR_BASIC_FLOAT16:
  5922. case AR_BASIC_FLOAT32:
  5923. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5924. case AR_BASIC_FLOAT64:
  5925. switch (rightKind) {
  5926. case AR_BASIC_LITERAL_FLOAT:
  5927. return false;
  5928. default:
  5929. break; // No other valid conversions
  5930. }
  5931. break;
  5932. default:
  5933. // No other relevant targets
  5934. break;
  5935. }
  5936. return true;
  5937. }
  5938. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  5939. {
  5940. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  5941. return 0;
  5942. }
  5943. UINT64 uScore = 0;
  5944. UINT uLSize = GetNumElements(pLType);
  5945. UINT uRSize = GetNumElements(pRType);
  5946. UINT uCompareSize;
  5947. bool bLCast = false;
  5948. bool bRCast = false;
  5949. bool bLIntCast = false;
  5950. bool bRIntCast = false;
  5951. bool bLPromo = false;
  5952. bool bRPromo = false;
  5953. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  5954. if (uCompareSize > uRSize) {
  5955. uCompareSize = uRSize;
  5956. }
  5957. for (UINT i = 0; i < uCompareSize; i++) {
  5958. ArBasicKind LeftElementKind, RightElementKind;
  5959. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  5960. QualType leftSub = GetNthElementType(pLType, i);
  5961. QualType rightSub = GetNthElementType(pRType, i);
  5962. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  5963. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  5964. LeftElementKind = GetTypeElementKind(leftSub);
  5965. RightElementKind = GetTypeElementKind(rightSub);
  5966. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  5967. // information needed is the ShapeKind, EltKind and ObjKind.
  5968. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  5969. bool bCombine;
  5970. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  5971. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  5972. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  5973. ArBasicKind RightObjKind = RightElementKind;
  5974. LeftElementKind = LeftObjKind;
  5975. RightElementKind = RightObjKind;
  5976. if (leftKind != rightKind) {
  5977. bCombine = false;
  5978. }
  5979. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  5980. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  5981. }
  5982. }
  5983. else {
  5984. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  5985. }
  5986. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  5987. bLPromo = true;
  5988. }
  5989. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  5990. bLCast = true;
  5991. }
  5992. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  5993. bLIntCast = true;
  5994. }
  5995. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  5996. bRPromo = true;
  5997. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  5998. bRCast = true;
  5999. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  6000. bRIntCast = true;
  6001. }
  6002. } else {
  6003. bLCast = true;
  6004. bRCast = true;
  6005. }
  6006. }
  6007. #define SCORE_COND(shift, cond) { \
  6008. if (cond) uScore += 1ULL << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  6009. SCORE_COND(0, uRSize < uLSize);
  6010. SCORE_COND(1, bLPromo);
  6011. SCORE_COND(2, bRPromo);
  6012. SCORE_COND(3, bLIntCast);
  6013. SCORE_COND(4, bRIntCast);
  6014. SCORE_COND(5, bLCast);
  6015. SCORE_COND(6, bRCast);
  6016. SCORE_COND(7, uLSize < uRSize);
  6017. #undef SCORE_COND
  6018. // Make sure our scores fit in a UINT64.
  6019. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  6020. return uScore;
  6021. }
  6022. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  6023. DXASSERT(ics, "otherwise conversion has not been initialized");
  6024. if (!ics->isInitialized()) {
  6025. return 0;
  6026. }
  6027. if (!ics->isStandard()) {
  6028. return SCORE_MAX;
  6029. }
  6030. QualType fromType = ics->Standard.getFromType();
  6031. QualType toType = ics->Standard.getToType(2); // final type
  6032. return ScoreCast(toType, fromType);
  6033. }
  6034. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  6035. // Ignore target version mismatches.
  6036. // in/out considerations have been taken care of by viability.
  6037. // 'this' considerations don't matter without inheritance, other
  6038. // than lookup and viability.
  6039. UINT64 result = 0;
  6040. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  6041. UINT64 score;
  6042. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  6043. if (score == SCORE_MAX) {
  6044. return SCORE_MAX;
  6045. }
  6046. result += score;
  6047. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  6048. if (score == SCORE_MAX) {
  6049. return SCORE_MAX;
  6050. }
  6051. result += score;
  6052. }
  6053. return result;
  6054. }
  6055. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  6056. SourceLocation Loc,
  6057. OverloadCandidateSet& set,
  6058. OverloadCandidateSet::iterator& Best)
  6059. {
  6060. UINT64 bestScore = SCORE_MAX;
  6061. unsigned scoreMatch = 0;
  6062. Best = set.end();
  6063. if (set.size() == 1 && set.begin()->Viable) {
  6064. Best = set.begin();
  6065. return OR_Success;
  6066. }
  6067. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  6068. if (Cand->Viable) {
  6069. UINT64 score = ScoreFunction(Cand);
  6070. if (score != SCORE_MAX) {
  6071. if (score == bestScore) {
  6072. ++scoreMatch;
  6073. } else if (score < bestScore) {
  6074. Best = Cand;
  6075. scoreMatch = 1;
  6076. bestScore = score;
  6077. }
  6078. }
  6079. }
  6080. }
  6081. if (Best == set.end()) {
  6082. return OR_No_Viable_Function;
  6083. }
  6084. if (scoreMatch > 1) {
  6085. Best = set.end();
  6086. return OR_Ambiguous;
  6087. }
  6088. // No need to check for deleted functions to yield OR_Deleted.
  6089. return OR_Success;
  6090. }
  6091. /// <summary>
  6092. /// Initializes the specified <paramref name="initSequence" /> describing how
  6093. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  6094. /// </summary>
  6095. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  6096. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  6097. /// <param name="Args">Arguments to the initialization.</param>
  6098. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  6099. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  6100. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  6101. const InitializedEntity& Entity,
  6102. const InitializationKind& Kind,
  6103. MultiExprArg Args,
  6104. bool TopLevelOfInitList,
  6105. _Inout_ InitializationSequence* initSequence)
  6106. {
  6107. DXASSERT_NOMSG(initSequence != nullptr);
  6108. // In HLSL there are no default initializers, eg float4x4 m();
  6109. // Except for RayQuery constructor (also handle InitializationKind::IK_Value)
  6110. if (Kind.getKind() == InitializationKind::IK_Default ||
  6111. Kind.getKind() == InitializationKind::IK_Value) {
  6112. QualType destBaseType = m_context->getBaseElementType(Entity.getType());
  6113. ArTypeObjectKind destBaseShape = GetTypeObjectKind(destBaseType);
  6114. if (destBaseShape == AR_TOBJ_OBJECT) {
  6115. const CXXRecordDecl *typeRecordDecl = destBaseType->getAsCXXRecordDecl();
  6116. int index = FindObjectBasicKindIndex(GetRecordDeclForBuiltInOrStruct(typeRecordDecl));
  6117. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  6118. if (g_ArBasicKindsAsTypes[index] == AR_OBJECT_RAY_QUERY) {
  6119. CXXConstructorDecl *Constructor = *typeRecordDecl->ctor_begin();
  6120. initSequence->AddConstructorInitializationStep(
  6121. Constructor, AccessSpecifier::AS_public, destBaseType, false, false, false);
  6122. return;
  6123. }
  6124. }
  6125. // Value initializers occur for temporaries with empty parens or braces.
  6126. if (Kind.getKind() == InitializationKind::IK_Value) {
  6127. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  6128. SilenceSequenceDiagnostics(initSequence);
  6129. }
  6130. return;
  6131. }
  6132. // If we have a DirectList, we should have a single InitListExprClass argument.
  6133. DXASSERT(
  6134. Kind.getKind() != InitializationKind::IK_DirectList ||
  6135. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  6136. "otherwise caller is passing in incorrect initialization configuration");
  6137. bool isCast = Kind.isCStyleCast();
  6138. QualType destType = Entity.getType();
  6139. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  6140. // Direct initialization occurs for explicit constructor arguments.
  6141. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  6142. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  6143. !Kind.isCStyleOrFunctionalCast()) {
  6144. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  6145. SilenceSequenceDiagnostics(initSequence);
  6146. return;
  6147. }
  6148. bool flatten =
  6149. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  6150. Kind.getKind() == InitializationKind::IK_DirectList ||
  6151. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  6152. if (flatten) {
  6153. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  6154. // array types to adjust the value - we do calculate this as part of type analysis.
  6155. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  6156. FlattenedTypeIterator::ComparisonResult comparisonResult =
  6157. FlattenedTypeIterator::CompareTypesForInit(
  6158. *this, destType, Args,
  6159. Kind.getLocation(), Kind.getLocation());
  6160. if (comparisonResult.IsConvertibleAndEqualLength() ||
  6161. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  6162. {
  6163. initSequence->AddListInitializationStep(destType);
  6164. }
  6165. else
  6166. {
  6167. SourceLocation diagLocation;
  6168. if (Args.size() > 0)
  6169. {
  6170. diagLocation = Args.front()->getLocStart();
  6171. }
  6172. else
  6173. {
  6174. diagLocation = Entity.getDiagLoc();
  6175. }
  6176. if (comparisonResult.IsEqualLength()) {
  6177. m_sema->Diag(diagLocation, diag::err_hlsl_type_mismatch);
  6178. }
  6179. else {
  6180. m_sema->Diag(diagLocation,
  6181. diag::err_incorrect_num_initializers)
  6182. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  6183. << IsSubobjectType(destType)
  6184. << comparisonResult.LeftCount << comparisonResult.RightCount;
  6185. }
  6186. SilenceSequenceDiagnostics(initSequence);
  6187. }
  6188. }
  6189. else {
  6190. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  6191. Expr* firstArg = Args.front();
  6192. if (IsExpressionBinaryComma(firstArg)) {
  6193. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  6194. }
  6195. ExprResult expr = ExprResult(firstArg);
  6196. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  6197. Sema::CheckedConversionKind::CCK_CStyleCast :
  6198. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  6199. unsigned int msg = 0;
  6200. CastKind castKind;
  6201. CXXCastPath basePath;
  6202. SourceRange range = Kind.getRange();
  6203. ImplicitConversionSequence ics;
  6204. ics.setStandard();
  6205. bool castWorked = TryStaticCastForHLSL(
  6206. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  6207. if (castWorked) {
  6208. if (destType.getCanonicalType() ==
  6209. firstArg->getType().getCanonicalType() &&
  6210. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  6211. initSequence->AddCAssignmentStep(destType);
  6212. } else {
  6213. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  6214. }
  6215. }
  6216. else {
  6217. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  6218. }
  6219. }
  6220. }
  6221. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6222. const QualType& sourceType,
  6223. const QualType& targetType,
  6224. bool explicitConversion)
  6225. {
  6226. DXASSERT_NOMSG(!sourceType.isNull());
  6227. DXASSERT_NOMSG(!targetType.isNull());
  6228. ArTypeInfo sourceTypeInfo;
  6229. ArTypeInfo targetTypeInfo;
  6230. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  6231. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  6232. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  6233. {
  6234. return false;
  6235. }
  6236. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  6237. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  6238. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  6239. !isVecMatTrunc)
  6240. {
  6241. return false;
  6242. }
  6243. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  6244. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  6245. return true;
  6246. }
  6247. // Same struct is eqaul.
  6248. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  6249. sourceType.getCanonicalType().getUnqualifiedType() ==
  6250. targetType.getCanonicalType().getUnqualifiedType()) {
  6251. return true;
  6252. }
  6253. // DerivedFrom is less.
  6254. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  6255. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  6256. const RecordType *targetRT = targetType->getAsStructureType();
  6257. if (!targetRT)
  6258. targetRT = dyn_cast<RecordType>(targetType);
  6259. const RecordType *sourceRT = sourceType->getAsStructureType();
  6260. if (!sourceRT)
  6261. sourceRT = dyn_cast<RecordType>(sourceType);
  6262. if (targetRT && sourceRT) {
  6263. RecordDecl *targetRD = targetRT->getDecl();
  6264. RecordDecl *sourceRD = sourceRT->getDecl();
  6265. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6266. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6267. if (targetCXXRD && sourceCXXRD) {
  6268. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  6269. return true;
  6270. }
  6271. }
  6272. }
  6273. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  6274. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  6275. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  6276. {
  6277. return false;
  6278. }
  6279. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  6280. }
  6281. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6282. const ExprResult& sourceExpr,
  6283. const QualType& targetType,
  6284. bool explicitConversion)
  6285. {
  6286. if (sourceExpr.isInvalid() || targetType.isNull())
  6287. {
  6288. return false;
  6289. }
  6290. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  6291. }
  6292. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  6293. {
  6294. DXASSERT_NOMSG(!type.isNull());
  6295. DXASSERT_NOMSG(count != nullptr);
  6296. *count = 0;
  6297. UINT subCount = 0;
  6298. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  6299. switch (shapeKind)
  6300. {
  6301. case AR_TOBJ_ARRAY:
  6302. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  6303. {
  6304. *count = subCount * GetArraySize(type);
  6305. return true;
  6306. }
  6307. return false;
  6308. case AR_TOBJ_COMPOUND:
  6309. {
  6310. UINT maxCount = 0;
  6311. { // Determine maximum count to prevent infinite loop on incomplete array
  6312. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  6313. maxCount = itCount.countRemaining();
  6314. if (!maxCount) {
  6315. return false; // empty struct.
  6316. }
  6317. }
  6318. FlattenedTypeIterator it(SourceLocation(), type, *this);
  6319. while (it.hasCurrentElement()) {
  6320. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  6321. if (!isFieldNumeric) {
  6322. return false;
  6323. }
  6324. if (*count >= maxCount) {
  6325. // this element is an incomplete array at the end; iterator will not advance past this element.
  6326. // don't add to *count either, so *count will represent minimum size of the structure.
  6327. break;
  6328. }
  6329. *count += (subCount * it.getCurrentElementSize());
  6330. it.advanceCurrentElement(it.getCurrentElementSize());
  6331. }
  6332. return true;
  6333. }
  6334. default:
  6335. DXASSERT(false, "unreachable");
  6336. case AR_TOBJ_BASIC:
  6337. case AR_TOBJ_MATRIX:
  6338. case AR_TOBJ_VECTOR:
  6339. *count = GetElementCount(type);
  6340. return IsBasicKindNumeric(GetTypeElementKind(type));
  6341. case AR_TOBJ_OBJECT:
  6342. case AR_TOBJ_STRING:
  6343. return false;
  6344. }
  6345. }
  6346. enum MatrixMemberAccessError {
  6347. MatrixMemberAccessError_None, // No errors found.
  6348. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  6349. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  6350. MatrixMemberAccessError_Empty, // No members specified.
  6351. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  6352. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  6353. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6354. };
  6355. static
  6356. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  6357. {
  6358. DXASSERT_NOMSG(memberText != nullptr);
  6359. DXASSERT_NOMSG(value != nullptr);
  6360. if ('0' <= *memberText && *memberText <= '9')
  6361. {
  6362. *value = (*memberText) - '0';
  6363. }
  6364. else
  6365. {
  6366. return MatrixMemberAccessError_BadFormat;
  6367. }
  6368. memberText++;
  6369. return MatrixMemberAccessError_None;
  6370. }
  6371. static
  6372. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  6373. {
  6374. DXASSERT_NOMSG(memberText != nullptr);
  6375. DXASSERT_NOMSG(value != nullptr);
  6376. MatrixMemberAccessPositions result;
  6377. bool zeroBasedDecided = false;
  6378. bool zeroBased = false;
  6379. // Set the output value to invalid to allow early exits when errors are found.
  6380. value->IsValid = 0;
  6381. // Assume this is true until proven otherwise.
  6382. result.IsValid = 1;
  6383. result.Count = 0;
  6384. while (*memberText)
  6385. {
  6386. // Check for a leading underscore.
  6387. if (*memberText != '_')
  6388. {
  6389. return MatrixMemberAccessError_BadFormat;
  6390. }
  6391. ++memberText;
  6392. // Check whether we have an 'm' or a digit.
  6393. if (*memberText == 'm')
  6394. {
  6395. if (zeroBasedDecided && !zeroBased)
  6396. {
  6397. return MatrixMemberAccessError_MixingRefs;
  6398. }
  6399. zeroBased = true;
  6400. zeroBasedDecided = true;
  6401. ++memberText;
  6402. }
  6403. else if (!('0' <= *memberText && *memberText <= '9'))
  6404. {
  6405. return MatrixMemberAccessError_BadFormat;
  6406. }
  6407. else
  6408. {
  6409. if (zeroBasedDecided && zeroBased)
  6410. {
  6411. return MatrixMemberAccessError_MixingRefs;
  6412. }
  6413. zeroBased = false;
  6414. zeroBasedDecided = true;
  6415. }
  6416. // Consume two digits for the position.
  6417. uint32_t rowPosition;
  6418. uint32_t colPosition;
  6419. MatrixMemberAccessError digitError;
  6420. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  6421. {
  6422. return digitError;
  6423. }
  6424. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  6425. {
  6426. return digitError;
  6427. }
  6428. // Look for specific common errors (developer likely mixed up reference style).
  6429. if (zeroBased)
  6430. {
  6431. if (rowPosition == 4 || colPosition == 4)
  6432. {
  6433. return MatrixMemberAccessError_FourInZeroBased;
  6434. }
  6435. }
  6436. else
  6437. {
  6438. if (rowPosition == 0 || colPosition == 0)
  6439. {
  6440. return MatrixMemberAccessError_ZeroInOneBased;
  6441. }
  6442. // SetPosition will use zero-based indices.
  6443. --rowPosition;
  6444. --colPosition;
  6445. }
  6446. if (result.Count == 4)
  6447. {
  6448. return MatrixMemberAccessError_TooManyPositions;
  6449. }
  6450. result.SetPosition(result.Count, rowPosition, colPosition);
  6451. result.Count++;
  6452. }
  6453. if (result.Count == 0)
  6454. {
  6455. return MatrixMemberAccessError_Empty;
  6456. }
  6457. *value = result;
  6458. return MatrixMemberAccessError_None;
  6459. }
  6460. ExprResult HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  6461. Expr& BaseExpr,
  6462. DeclarationName MemberName,
  6463. bool IsArrow,
  6464. SourceLocation OpLoc,
  6465. SourceLocation MemberLoc)
  6466. {
  6467. QualType BaseType = BaseExpr.getType();
  6468. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6469. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_MATRIX, "Should only be called on known matrix types");
  6470. QualType elementType;
  6471. UINT rowCount, colCount;
  6472. GetRowsAndCols(BaseType, rowCount, colCount);
  6473. elementType = GetMatrixOrVectorElementType(BaseType);
  6474. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6475. const char *memberText = member->getNameStart();
  6476. MatrixMemberAccessPositions positions;
  6477. MatrixMemberAccessError memberAccessError;
  6478. unsigned msg = 0;
  6479. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  6480. switch (memberAccessError)
  6481. {
  6482. case MatrixMemberAccessError_BadFormat:
  6483. msg = diag::err_hlsl_matrix_member_bad_format;
  6484. break;
  6485. case MatrixMemberAccessError_Empty:
  6486. msg = diag::err_hlsl_matrix_member_empty;
  6487. break;
  6488. case MatrixMemberAccessError_FourInZeroBased:
  6489. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  6490. break;
  6491. case MatrixMemberAccessError_MixingRefs:
  6492. msg = diag::err_hlsl_matrix_member_mixing_refs;
  6493. break;
  6494. case MatrixMemberAccessError_None:
  6495. msg = 0;
  6496. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6497. // Check the position with the type now.
  6498. for (unsigned int i = 0; i < positions.Count; i++)
  6499. {
  6500. uint32_t rowPos, colPos;
  6501. positions.GetPosition(i, &rowPos, &colPos);
  6502. if (rowPos >= rowCount || colPos >= colCount)
  6503. {
  6504. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  6505. break;
  6506. }
  6507. }
  6508. break;
  6509. case MatrixMemberAccessError_TooManyPositions:
  6510. msg = diag::err_hlsl_matrix_member_too_many_positions;
  6511. break;
  6512. case MatrixMemberAccessError_ZeroInOneBased:
  6513. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  6514. break;
  6515. default:
  6516. llvm_unreachable("Unknown MatrixMemberAccessError value");
  6517. }
  6518. if (msg != 0)
  6519. {
  6520. m_sema->Diag(MemberLoc, msg) << memberText;
  6521. // It's possible that it's a simple out-of-bounds condition. In this case,
  6522. // generate the member access expression with the correct arity and continue
  6523. // processing.
  6524. if (!positions.IsValid)
  6525. {
  6526. return ExprError();
  6527. }
  6528. }
  6529. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6530. // Consume elements
  6531. QualType resultType;
  6532. if (positions.Count == 1)
  6533. resultType = elementType;
  6534. else
  6535. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6536. // Add qualifiers from BaseType.
  6537. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6538. ExprValueKind VK =
  6539. positions.ContainsDuplicateElements() ? VK_RValue :
  6540. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6541. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6542. return matrixExpr;
  6543. }
  6544. enum VectorMemberAccessError {
  6545. VectorMemberAccessError_None, // No errors found.
  6546. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  6547. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  6548. VectorMemberAccessError_Empty, // No members specified.
  6549. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6550. };
  6551. static
  6552. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  6553. DXASSERT_NOMSG(memberText != nullptr);
  6554. DXASSERT_NOMSG(value != nullptr);
  6555. rgbaStyle = false;
  6556. switch (*memberText) {
  6557. case 'r':
  6558. rgbaStyle = true;
  6559. case 'x':
  6560. *value = 0;
  6561. break;
  6562. case 'g':
  6563. rgbaStyle = true;
  6564. case 'y':
  6565. *value = 1;
  6566. break;
  6567. case 'b':
  6568. rgbaStyle = true;
  6569. case 'z':
  6570. *value = 2;
  6571. break;
  6572. case 'a':
  6573. rgbaStyle = true;
  6574. case 'w':
  6575. *value = 3;
  6576. break;
  6577. default:
  6578. return VectorMemberAccessError_BadFormat;
  6579. }
  6580. memberText++;
  6581. return VectorMemberAccessError_None;
  6582. }
  6583. static
  6584. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  6585. DXASSERT_NOMSG(memberText != nullptr);
  6586. DXASSERT_NOMSG(value != nullptr);
  6587. VectorMemberAccessPositions result;
  6588. bool rgbaStyleDecided = false;
  6589. bool rgbaStyle = false;
  6590. // Set the output value to invalid to allow early exits when errors are found.
  6591. value->IsValid = 0;
  6592. // Assume this is true until proven otherwise.
  6593. result.IsValid = 1;
  6594. result.Count = 0;
  6595. while (*memberText) {
  6596. // Consume one character for the swizzle.
  6597. uint32_t colPosition;
  6598. VectorMemberAccessError digitError;
  6599. bool rgbaStyleTmp = false;
  6600. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6601. return digitError;
  6602. }
  6603. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6604. return VectorMemberAccessError_MixingStyles;
  6605. }
  6606. else {
  6607. rgbaStyleDecided = true;
  6608. rgbaStyle = rgbaStyleTmp;
  6609. }
  6610. if (result.Count == 4) {
  6611. return VectorMemberAccessError_TooManyPositions;
  6612. }
  6613. result.SetPosition(result.Count, colPosition);
  6614. result.Count++;
  6615. }
  6616. if (result.Count == 0) {
  6617. return VectorMemberAccessError_Empty;
  6618. }
  6619. *value = result;
  6620. return VectorMemberAccessError_None;
  6621. }
  6622. bool IsExprAccessingOutIndicesArray(Expr* BaseExpr) {
  6623. switch(BaseExpr->getStmtClass()) {
  6624. case Stmt::ArraySubscriptExprClass: {
  6625. ArraySubscriptExpr* ase = cast<ArraySubscriptExpr>(BaseExpr);
  6626. return IsExprAccessingOutIndicesArray(ase->getBase());
  6627. }
  6628. case Stmt::ImplicitCastExprClass: {
  6629. ImplicitCastExpr* ice = cast<ImplicitCastExpr>(BaseExpr);
  6630. return IsExprAccessingOutIndicesArray(ice->getSubExpr());
  6631. }
  6632. case Stmt::DeclRefExprClass: {
  6633. DeclRefExpr* dre = cast<DeclRefExpr>(BaseExpr);
  6634. ValueDecl* vd = dre->getDecl();
  6635. if (vd->getAttr<HLSLIndicesAttr>() && vd->getAttr<HLSLOutAttr>()) {
  6636. return true;
  6637. }
  6638. return false;
  6639. }
  6640. default:
  6641. return false;
  6642. }
  6643. }
  6644. ExprResult HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6645. Expr& BaseExpr,
  6646. DeclarationName MemberName,
  6647. bool IsArrow,
  6648. SourceLocation OpLoc,
  6649. SourceLocation MemberLoc) {
  6650. QualType BaseType = BaseExpr.getType();
  6651. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6652. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_VECTOR, "Should only be called on known vector types");
  6653. QualType elementType;
  6654. UINT colCount = GetHLSLVecSize(BaseType);
  6655. elementType = GetMatrixOrVectorElementType(BaseType);
  6656. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6657. const char *memberText = member->getNameStart();
  6658. VectorMemberAccessPositions positions;
  6659. VectorMemberAccessError memberAccessError;
  6660. unsigned msg = 0;
  6661. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6662. switch (memberAccessError) {
  6663. case VectorMemberAccessError_BadFormat:
  6664. msg = diag::err_hlsl_vector_member_bad_format;
  6665. break;
  6666. case VectorMemberAccessError_Empty:
  6667. msg = diag::err_hlsl_vector_member_empty;
  6668. break;
  6669. case VectorMemberAccessError_MixingStyles:
  6670. msg = diag::err_ext_vector_component_name_mixedsets;
  6671. break;
  6672. case VectorMemberAccessError_None:
  6673. msg = 0;
  6674. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6675. // Check the position with the type now.
  6676. for (unsigned int i = 0; i < positions.Count; i++) {
  6677. uint32_t colPos;
  6678. positions.GetPosition(i, &colPos);
  6679. if (colPos >= colCount) {
  6680. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6681. break;
  6682. }
  6683. }
  6684. break;
  6685. case VectorMemberAccessError_TooManyPositions:
  6686. msg = diag::err_hlsl_vector_member_too_many_positions;
  6687. break;
  6688. default:
  6689. llvm_unreachable("Unknown VectorMemberAccessError value");
  6690. }
  6691. if (msg != 0) {
  6692. m_sema->Diag(MemberLoc, msg) << memberText;
  6693. // It's possible that it's a simple out-of-bounds condition. In this case,
  6694. // generate the member access expression with the correct arity and continue
  6695. // processing.
  6696. if (!positions.IsValid) {
  6697. return ExprError();
  6698. }
  6699. }
  6700. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6701. // Disallow component access for out indices for DXIL path. We still allow
  6702. // this in SPIR-V path.
  6703. if (!m_sema->getLangOpts().SPIRV &&
  6704. IsExprAccessingOutIndicesArray(&BaseExpr) && positions.Count < colCount) {
  6705. m_sema->Diag(MemberLoc, diag::err_hlsl_out_indices_array_incorrect_access);
  6706. return ExprError();
  6707. }
  6708. // Consume elements
  6709. QualType resultType;
  6710. if (positions.Count == 1)
  6711. resultType = elementType;
  6712. else
  6713. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6714. // Add qualifiers from BaseType.
  6715. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6716. ExprValueKind VK =
  6717. positions.ContainsDuplicateElements() ? VK_RValue :
  6718. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6719. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6720. return vectorExpr;
  6721. }
  6722. ExprResult HLSLExternalSource::LookupArrayMemberExprForHLSL(
  6723. Expr& BaseExpr,
  6724. DeclarationName MemberName,
  6725. bool IsArrow,
  6726. SourceLocation OpLoc,
  6727. SourceLocation MemberLoc) {
  6728. QualType BaseType = BaseExpr.getType();
  6729. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6730. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_ARRAY, "Should only be called on known array types");
  6731. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6732. const char *memberText = member->getNameStart();
  6733. // The only property available on arrays is Length; it is deprecated and available only on HLSL version <=2018
  6734. if (member->getLength() == 6 && 0 == strcmp(memberText, "Length")) {
  6735. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(BaseType)) {
  6736. // check version support
  6737. unsigned hlslVer = getSema()->getLangOpts().HLSLVersion;
  6738. if (hlslVer > 2016) {
  6739. m_sema->Diag(MemberLoc, diag::err_hlsl_unsupported_for_version_lower) << "Length" << "2016";
  6740. return ExprError();
  6741. }
  6742. if (hlslVer == 2016) {
  6743. m_sema->Diag(MemberLoc, diag::warn_deprecated) << "Length";
  6744. }
  6745. UnaryExprOrTypeTraitExpr *arrayLenExpr = new (m_context) UnaryExprOrTypeTraitExpr(
  6746. UETT_ArrayLength, &BaseExpr, m_context->getSizeType(), MemberLoc, BaseExpr.getSourceRange().getEnd());
  6747. return arrayLenExpr;
  6748. }
  6749. }
  6750. m_sema->Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
  6751. << BaseType << BaseExpr.getSourceRange() << MemberLoc;
  6752. return ExprError();
  6753. }
  6754. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  6755. DXASSERT_NOMSG(E != nullptr);
  6756. ArBasicKind basic = GetTypeElementKind(E->getType());
  6757. if (!IS_BASIC_PRIMITIVE(basic)) {
  6758. return E;
  6759. }
  6760. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  6761. if (kind != AR_TOBJ_SCALAR) {
  6762. return E;
  6763. }
  6764. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  6765. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  6766. }
  6767. static clang::CastKind ImplicitConversionKindToCastKind(
  6768. clang::ImplicitConversionKind ICK,
  6769. ArBasicKind FromKind,
  6770. ArBasicKind ToKind) {
  6771. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  6772. // based on from/to kinds in order to determine CastKind?
  6773. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  6774. // problem.
  6775. switch (ICK) {
  6776. case ICK_Integral_Promotion:
  6777. case ICK_Integral_Conversion:
  6778. return CK_IntegralCast;
  6779. case ICK_Floating_Promotion:
  6780. case ICK_Floating_Conversion:
  6781. return CK_FloatingCast;
  6782. case ICK_Floating_Integral:
  6783. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  6784. return CK_FloatingToIntegral;
  6785. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  6786. return CK_IntegralToFloating;
  6787. break;
  6788. case ICK_Boolean_Conversion:
  6789. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  6790. return CK_FloatingToBoolean;
  6791. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  6792. return CK_IntegralToBoolean;
  6793. break;
  6794. default:
  6795. // Only covers implicit conversions with cast kind equivalents.
  6796. return CK_Invalid;
  6797. }
  6798. return CK_Invalid;
  6799. }
  6800. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  6801. switch (CK) {
  6802. case CK_IntegralCast:
  6803. return CK_HLSLCC_IntegralCast;
  6804. case CK_FloatingCast:
  6805. return CK_HLSLCC_FloatingCast;
  6806. case CK_FloatingToIntegral:
  6807. return CK_HLSLCC_FloatingToIntegral;
  6808. case CK_IntegralToFloating:
  6809. return CK_HLSLCC_IntegralToFloating;
  6810. case CK_FloatingToBoolean:
  6811. return CK_HLSLCC_FloatingToBoolean;
  6812. case CK_IntegralToBoolean:
  6813. return CK_HLSLCC_IntegralToBoolean;
  6814. default:
  6815. // Only HLSLCC castkinds are relevant. Ignore the rest.
  6816. return CK_Invalid;
  6817. }
  6818. return CK_Invalid;
  6819. }
  6820. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  6821. _In_ clang::Sema* self,
  6822. _In_ clang::Expr* From,
  6823. ArTypeObjectKind FromShape,
  6824. ArBasicKind EltKind)
  6825. {
  6826. clang::CastKind CK = CK_Invalid;
  6827. if (AR_TOBJ_MATRIX == FromShape)
  6828. CK = CK_HLSLMatrixToScalarCast;
  6829. if (AR_TOBJ_VECTOR == FromShape)
  6830. CK = CK_HLSLVectorToScalarCast;
  6831. if (CK_Invalid != CK) {
  6832. return self->ImpCastExprToType(From,
  6833. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  6834. }
  6835. return From;
  6836. }
  6837. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  6838. _In_ clang::Expr* From,
  6839. _In_ clang::QualType targetType,
  6840. _In_ const clang::StandardConversionSequence &SCS,
  6841. _In_ clang::Sema::CheckedConversionKind CCK)
  6842. {
  6843. QualType sourceType = From->getType();
  6844. sourceType = GetStructuralForm(sourceType);
  6845. targetType = GetStructuralForm(targetType);
  6846. ArTypeInfo SourceInfo, TargetInfo;
  6847. CollectInfo(sourceType, &SourceInfo);
  6848. CollectInfo(targetType, &TargetInfo);
  6849. clang::CastKind CK = CK_Invalid;
  6850. QualType intermediateTarget;
  6851. // TODO: construct vector/matrix and component cast expressions
  6852. switch (SCS.Second) {
  6853. case ICK_Flat_Conversion: {
  6854. // TODO: determine how to handle individual component conversions:
  6855. // - have an array of conversions for ComponentConversion in SCS?
  6856. // convert that to an array of casts under a special kind of flat
  6857. // flat conversion node? What do component conversion casts cast
  6858. // from? We don't have a From expression for individiual components.
  6859. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6860. break;
  6861. }
  6862. case ICK_HLSL_Derived_To_Base: {
  6863. CXXCastPath BasePath;
  6864. if (m_sema->CheckDerivedToBaseConversion(
  6865. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  6866. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  6867. return ExprError();
  6868. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  6869. break;
  6870. }
  6871. case ICK_HLSLVector_Splat: {
  6872. // 1. optionally convert from vec1 or mat1x1 to scalar
  6873. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6874. // 2. optionally convert component type
  6875. if (ICK_Identity != SCS.ComponentConversion) {
  6876. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6877. if (CK_Invalid != CK) {
  6878. From = m_sema->ImpCastExprToType(From,
  6879. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6880. }
  6881. }
  6882. // 3. splat scalar to final vector or matrix
  6883. CK = CK_Invalid;
  6884. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  6885. CK = CK_HLSLVectorSplat;
  6886. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  6887. CK = CK_HLSLMatrixSplat;
  6888. if (CK_Invalid != CK) {
  6889. From = m_sema->ImpCastExprToType(From,
  6890. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6891. }
  6892. break;
  6893. }
  6894. case ICK_HLSLVector_Scalar: {
  6895. // 1. select vector or matrix component
  6896. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6897. // 2. optionally convert component type
  6898. if (ICK_Identity != SCS.ComponentConversion) {
  6899. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6900. if (CK_Invalid != CK) {
  6901. From = m_sema->ImpCastExprToType(From,
  6902. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6903. }
  6904. }
  6905. break;
  6906. }
  6907. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  6908. // can be done with case fall-through, since this is the order in which we want to
  6909. // do the conversion operations.
  6910. case ICK_HLSLVector_Truncation: {
  6911. // 1. dimension truncation
  6912. // vector truncation or matrix truncation?
  6913. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  6914. From = m_sema->ImpCastExprToType(From,
  6915. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  6916. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6917. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  6918. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  6919. // Handle the column to vector case
  6920. From = m_sema->ImpCastExprToType(From,
  6921. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  6922. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6923. } else {
  6924. From = m_sema->ImpCastExprToType(From,
  6925. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6926. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6927. }
  6928. } else {
  6929. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  6930. }
  6931. }
  6932. __fallthrough;
  6933. case ICK_HLSLVector_Conversion: {
  6934. // 2. Do ShapeKind conversion if necessary
  6935. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  6936. switch (TargetInfo.ShapeKind) {
  6937. case AR_TOBJ_VECTOR:
  6938. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6939. From = m_sema->ImpCastExprToType(From,
  6940. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6941. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6942. break;
  6943. case AR_TOBJ_MATRIX:
  6944. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6945. From = m_sema->ImpCastExprToType(From,
  6946. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6947. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6948. break;
  6949. case AR_TOBJ_BASIC:
  6950. // Truncation may be followed by cast to scalar
  6951. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6952. break;
  6953. default:
  6954. DXASSERT(false, "otherwise, invalid casting sequence");
  6955. break;
  6956. }
  6957. }
  6958. // 3. Do component type conversion
  6959. if (ICK_Identity != SCS.ComponentConversion) {
  6960. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6961. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  6962. CK = ConvertToComponentCastKind(CK);
  6963. if (CK_Invalid != CK) {
  6964. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6965. }
  6966. }
  6967. break;
  6968. }
  6969. case ICK_Identity:
  6970. // Nothing to do.
  6971. break;
  6972. default:
  6973. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  6974. }
  6975. return From;
  6976. }
  6977. void HLSLExternalSource::GetConversionForm(
  6978. QualType type,
  6979. bool explicitConversion,
  6980. ArTypeInfo* pTypeInfo)
  6981. {
  6982. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  6983. CollectInfo(type, pTypeInfo);
  6984. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  6985. // but that value is only used for pointer conversions.
  6986. // When explicitly converting types complex aggregates can be treated
  6987. // as vectors if they are entirely numeric.
  6988. switch (pTypeInfo->ShapeKind)
  6989. {
  6990. case AR_TOBJ_COMPOUND:
  6991. case AR_TOBJ_ARRAY:
  6992. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  6993. {
  6994. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  6995. }
  6996. else
  6997. {
  6998. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  6999. }
  7000. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  7001. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  7002. break;
  7003. case AR_TOBJ_VECTOR:
  7004. case AR_TOBJ_MATRIX:
  7005. // Convert 1x1 types to scalars.
  7006. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  7007. {
  7008. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  7009. }
  7010. break;
  7011. default:
  7012. // Only convertable shapekinds are relevant.
  7013. break;
  7014. }
  7015. }
  7016. static
  7017. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  7018. {
  7019. DXASSERT_NOMSG(allowed != nullptr);
  7020. bool applicable = true;
  7021. *allowed = true;
  7022. if (explicitConversion) {
  7023. // (void) non-void
  7024. if (target->isVoidType()) {
  7025. DXASSERT_NOMSG(*allowed);
  7026. }
  7027. // (non-void) void
  7028. else if (source->isVoidType()) {
  7029. *allowed = false;
  7030. }
  7031. else {
  7032. applicable = false;
  7033. }
  7034. }
  7035. else {
  7036. // (void) void
  7037. if (source->isVoidType() && target->isVoidType()) {
  7038. DXASSERT_NOMSG(*allowed);
  7039. }
  7040. // (void) non-void, (non-void) void
  7041. else if (source->isVoidType() || target->isVoidType()) {
  7042. *allowed = false;
  7043. }
  7044. else {
  7045. applicable = false;
  7046. }
  7047. }
  7048. return applicable;
  7049. }
  7050. static bool ConvertDimensions(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7051. ImplicitConversionKind &Second,
  7052. TYPE_CONVERSION_REMARKS &Remarks) {
  7053. // The rules for aggregate conversions are:
  7054. // 1. A scalar can be replicated to any layout.
  7055. // 2. Any type may be truncated to anything else with one component.
  7056. // 3. A vector may be truncated to a smaller vector.
  7057. // 4. A matrix may be truncated to a smaller matrix.
  7058. // 5. The result of a vector and a matrix is:
  7059. // a. If the matrix has one row it's a vector-sized
  7060. // piece of the row.
  7061. // b. If the matrix has one column it's a vector-sized
  7062. // piece of the column.
  7063. // c. Otherwise the number of elements in the vector
  7064. // and matrix must match and the result is the vector.
  7065. // 6. The result of a matrix and a vector is similar to #5.
  7066. switch (TargetInfo.ShapeKind) {
  7067. case AR_TOBJ_BASIC:
  7068. switch (SourceInfo.ShapeKind)
  7069. {
  7070. case AR_TOBJ_BASIC:
  7071. Second = ICK_Identity;
  7072. break;
  7073. case AR_TOBJ_VECTOR:
  7074. if (1 < SourceInfo.uCols)
  7075. Second = ICK_HLSLVector_Truncation;
  7076. else
  7077. Second = ICK_HLSLVector_Scalar;
  7078. break;
  7079. case AR_TOBJ_MATRIX:
  7080. if (1 < SourceInfo.uRows * SourceInfo.uCols)
  7081. Second = ICK_HLSLVector_Truncation;
  7082. else
  7083. Second = ICK_HLSLVector_Scalar;
  7084. break;
  7085. default:
  7086. return false;
  7087. }
  7088. break;
  7089. case AR_TOBJ_VECTOR:
  7090. switch (SourceInfo.ShapeKind)
  7091. {
  7092. case AR_TOBJ_BASIC:
  7093. // Conversions between scalars and aggregates are always supported.
  7094. Second = ICK_HLSLVector_Splat;
  7095. break;
  7096. case AR_TOBJ_VECTOR:
  7097. if (TargetInfo.uCols > SourceInfo.uCols) {
  7098. if (SourceInfo.uCols == 1) {
  7099. Second = ICK_HLSLVector_Splat;
  7100. }
  7101. else {
  7102. return false;
  7103. }
  7104. }
  7105. else if (TargetInfo.uCols < SourceInfo.uCols) {
  7106. Second = ICK_HLSLVector_Truncation;
  7107. }
  7108. else {
  7109. Second = ICK_Identity;
  7110. }
  7111. break;
  7112. case AR_TOBJ_MATRIX: {
  7113. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7114. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  7115. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  7116. Second = ICK_HLSLVector_Splat;
  7117. }
  7118. else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  7119. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  7120. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  7121. return false;
  7122. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  7123. Second = ICK_HLSLVector_Truncation;
  7124. else // equalivalent: O == N*M
  7125. Second = ICK_HLSLVector_Conversion;
  7126. }
  7127. else if (TargetInfo.uCols == 1 && SourceComponents > 1) {
  7128. Second = ICK_HLSLVector_Truncation;
  7129. }
  7130. else if (TargetInfo.uCols != SourceComponents) {
  7131. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  7132. return false;
  7133. }
  7134. else {
  7135. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  7136. Second = ICK_HLSLVector_Conversion;
  7137. }
  7138. break;
  7139. }
  7140. default:
  7141. return false;
  7142. }
  7143. break;
  7144. case AR_TOBJ_MATRIX: {
  7145. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  7146. switch (SourceInfo.ShapeKind)
  7147. {
  7148. case AR_TOBJ_BASIC:
  7149. // Conversions between scalars and aggregates are always supported.
  7150. Second = ICK_HLSLVector_Splat;
  7151. break;
  7152. case AR_TOBJ_VECTOR: {
  7153. // We can only convert vector to matrix in following cases:
  7154. // - splat from vector<...,1>
  7155. // - same number of components
  7156. // - one target component (truncate to scalar)
  7157. // - matrix has one row or one column, and fewer components (truncation)
  7158. // Other cases disallowed even if implicitly convertable in two steps (truncation+conversion).
  7159. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  7160. // splat: vector<[..], 1> -> matrix<[..], M, N>
  7161. Second = ICK_HLSLVector_Splat;
  7162. }
  7163. else if (TargetComponents == SourceInfo.uCols) {
  7164. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  7165. Second = ICK_HLSLVector_Conversion;
  7166. }
  7167. else if (1 == TargetComponents) {
  7168. // truncate to scalar: matrix<[..], 1, 1>
  7169. Second = ICK_HLSLVector_Truncation;
  7170. }
  7171. else if ((1 == TargetInfo.uRows || 1 == TargetInfo.uCols) &&
  7172. TargetComponents < SourceInfo.uCols) {
  7173. Second = ICK_HLSLVector_Truncation;
  7174. }
  7175. else {
  7176. // illegal: change in components without going to or from scalar equivalent
  7177. return false;
  7178. }
  7179. break;
  7180. }
  7181. case AR_TOBJ_MATRIX: {
  7182. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7183. if (1 == SourceComponents && TargetComponents != 1) {
  7184. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  7185. Second = ICK_HLSLVector_Splat;
  7186. }
  7187. else if (TargetComponents == 1) {
  7188. Second = ICK_HLSLVector_Truncation;
  7189. }
  7190. else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  7191. return false;
  7192. }
  7193. else if (TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  7194. Second = ICK_HLSLVector_Truncation;
  7195. }
  7196. else {
  7197. Second = ICK_Identity;
  7198. }
  7199. break;
  7200. }
  7201. default:
  7202. return false;
  7203. }
  7204. break;
  7205. }
  7206. case AR_TOBJ_STRING:
  7207. if (SourceInfo.ShapeKind == AR_TOBJ_STRING) {
  7208. Second = ICK_Identity;
  7209. break;
  7210. }
  7211. else {
  7212. return false;
  7213. }
  7214. default:
  7215. return false;
  7216. }
  7217. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  7218. {
  7219. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  7220. }
  7221. return true;
  7222. }
  7223. static bool ConvertComponent(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7224. ImplicitConversionKind &ComponentConversion,
  7225. TYPE_CONVERSION_REMARKS &Remarks) {
  7226. // Conversion to/from unknown types not supported.
  7227. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  7228. SourceInfo.EltKind == AR_BASIC_UNKNOWN) {
  7229. return false;
  7230. }
  7231. bool precisionLoss = false;
  7232. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  7233. GET_BASIC_BITS(TargetInfo.EltKind) <
  7234. GET_BASIC_BITS(SourceInfo.EltKind))
  7235. {
  7236. precisionLoss = true;
  7237. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  7238. }
  7239. // enum -> enum not allowed
  7240. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  7241. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  7242. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  7243. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  7244. return false;
  7245. }
  7246. if (SourceInfo.EltKind != TargetInfo.EltKind)
  7247. {
  7248. if (IS_BASIC_BOOL(TargetInfo.EltKind))
  7249. {
  7250. ComponentConversion = ICK_Boolean_Conversion;
  7251. }
  7252. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  7253. {
  7254. // conversion to enum type not allowed
  7255. return false;
  7256. }
  7257. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  7258. {
  7259. // enum -> int/float
  7260. ComponentConversion = ICK_Integral_Conversion;
  7261. }
  7262. else if (TargetInfo.EltKind == AR_OBJECT_STRING)
  7263. {
  7264. if (SourceInfo.EltKind == AR_OBJECT_STRING_LITERAL) {
  7265. ComponentConversion = ICK_Array_To_Pointer;
  7266. }
  7267. else
  7268. {
  7269. return false;
  7270. }
  7271. }
  7272. else
  7273. {
  7274. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  7275. if (IS_BASIC_AINT(SourceInfo.EltKind))
  7276. {
  7277. if (targetIsInt)
  7278. {
  7279. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  7280. }
  7281. else
  7282. {
  7283. ComponentConversion = ICK_Floating_Integral;
  7284. }
  7285. }
  7286. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  7287. {
  7288. if (targetIsInt)
  7289. {
  7290. ComponentConversion = ICK_Floating_Integral;
  7291. }
  7292. else
  7293. {
  7294. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  7295. }
  7296. }
  7297. else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  7298. if (targetIsInt)
  7299. ComponentConversion = ICK_Integral_Conversion;
  7300. else
  7301. ComponentConversion = ICK_Floating_Integral;
  7302. }
  7303. }
  7304. }
  7305. return true;
  7306. }
  7307. _Use_decl_annotations_
  7308. bool HLSLExternalSource::CanConvert(
  7309. SourceLocation loc,
  7310. Expr* sourceExpr,
  7311. QualType target,
  7312. bool explicitConversion,
  7313. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  7314. _Inout_opt_ StandardConversionSequence* standard)
  7315. {
  7316. UINT uTSize, uSSize;
  7317. bool SourceIsAggregate, TargetIsAggregate; // Early declarations due to gotos below
  7318. DXASSERT_NOMSG(sourceExpr != nullptr);
  7319. DXASSERT_NOMSG(!target.isNull());
  7320. // Implements the semantics of ArType::CanConvertTo.
  7321. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  7322. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  7323. QualType source = sourceExpr->getType();
  7324. // Cannot cast function type.
  7325. if (source->isFunctionType())
  7326. return false;
  7327. // Convert to an r-value to begin with, with an exception for strings
  7328. // since they are not first-class values and we want to preserve them as literals.
  7329. bool needsLValueToRValue = sourceExpr->isLValue() && !target->isLValueReferenceType()
  7330. && sourceExpr->getStmtClass() != Expr::StringLiteralClass;
  7331. bool targetRef = target->isReferenceType();
  7332. // Initialize the output standard sequence if available.
  7333. if (standard != nullptr) {
  7334. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  7335. standard->setAsIdentityConversion();
  7336. if (needsLValueToRValue) {
  7337. standard->First = ICK_Lvalue_To_Rvalue;
  7338. }
  7339. standard->setFromType(source);
  7340. standard->setAllToTypes(target);
  7341. }
  7342. source = GetStructuralForm(source);
  7343. target = GetStructuralForm(target);
  7344. // Temporary conversion kind tracking which will be used/fixed up at the end
  7345. ImplicitConversionKind Second = ICK_Identity;
  7346. ImplicitConversionKind ComponentConversion = ICK_Identity;
  7347. // Identical types require no conversion.
  7348. if (source == target) {
  7349. Remarks = TYPE_CONVERSION_IDENTICAL;
  7350. goto lSuccess;
  7351. }
  7352. // Trivial cases for void.
  7353. bool allowed;
  7354. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  7355. if (allowed) {
  7356. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  7357. goto lSuccess;
  7358. }
  7359. else {
  7360. return false;
  7361. }
  7362. }
  7363. ArTypeInfo TargetInfo, SourceInfo;
  7364. CollectInfo(target, &TargetInfo);
  7365. CollectInfo(source, &SourceInfo);
  7366. uTSize = TargetInfo.uTotalElts;
  7367. uSSize = SourceInfo.uTotalElts;
  7368. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  7369. // are we missing cases?
  7370. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  7371. return false;
  7372. }
  7373. // Structure cast.
  7374. SourceIsAggregate = SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY;
  7375. TargetIsAggregate = TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY;
  7376. if (SourceIsAggregate || TargetIsAggregate) {
  7377. // For implicit conversions, FXC treats arrays the same as structures
  7378. // and rejects conversions between them and numeric types
  7379. if (!explicitConversion && SourceIsAggregate != TargetIsAggregate)
  7380. {
  7381. return false;
  7382. }
  7383. // Structure to structure cases
  7384. const RecordType *targetRT = dyn_cast<RecordType>(target);
  7385. const RecordType *sourceRT = dyn_cast<RecordType>(source);
  7386. if (targetRT && sourceRT) {
  7387. RecordDecl *targetRD = targetRT->getDecl();
  7388. RecordDecl *sourceRD = sourceRT->getDecl();
  7389. if (sourceRT && targetRT) {
  7390. if (targetRD == sourceRD) {
  7391. Second = ICK_Flat_Conversion;
  7392. goto lSuccess;
  7393. }
  7394. const CXXRecordDecl* targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  7395. const CXXRecordDecl* sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  7396. if (targetCXXRD && sourceCXXRD && sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  7397. Second = ICK_HLSL_Derived_To_Base;
  7398. goto lSuccess;
  7399. }
  7400. }
  7401. }
  7402. // Handle explicit splats from single element numerical types (scalars, vector1s and matrix1x1s) to aggregate types.
  7403. if (explicitConversion) {
  7404. const BuiltinType *sourceSingleElementBuiltinType = source->getAs<BuiltinType>();
  7405. if (sourceSingleElementBuiltinType == nullptr
  7406. && hlsl::IsHLSLVecMatType(source)
  7407. && hlsl::GetElementCount(source) == 1) {
  7408. sourceSingleElementBuiltinType = hlsl::GetElementTypeOrType(source)->getAs<BuiltinType>();
  7409. }
  7410. // We can only splat to target types that do not contain object/resource types
  7411. if (sourceSingleElementBuiltinType != nullptr && hlsl::IsHLSLNumericOrAggregateOfNumericType(target)) {
  7412. BuiltinType::Kind kind = sourceSingleElementBuiltinType->getKind();
  7413. switch (kind) {
  7414. case BuiltinType::Kind::UInt:
  7415. case BuiltinType::Kind::Int:
  7416. case BuiltinType::Kind::Float:
  7417. case BuiltinType::Kind::LitFloat:
  7418. case BuiltinType::Kind::LitInt:
  7419. Second = ICK_Flat_Conversion;
  7420. goto lSuccess;
  7421. default:
  7422. // Only flat conversion kinds are relevant.
  7423. break;
  7424. }
  7425. }
  7426. }
  7427. FlattenedTypeIterator::ComparisonResult result =
  7428. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  7429. if (!result.CanConvertElements) {
  7430. return false;
  7431. }
  7432. // Only allow scalar to compound or array with explicit cast
  7433. if (result.IsConvertibleAndLeftLonger()) {
  7434. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  7435. return false;
  7436. }
  7437. }
  7438. // Assignment is valid if elements are exactly the same in type and size; if
  7439. // an explicit conversion is being done, we accept converted elements and a
  7440. // longer right-hand sequence.
  7441. if (!explicitConversion &&
  7442. (!result.AreElementsEqual || result.IsRightLonger()))
  7443. {
  7444. return false;
  7445. }
  7446. Second = ICK_Flat_Conversion;
  7447. goto lSuccess;
  7448. }
  7449. // Cast from Resource to Object types.
  7450. if (SourceInfo.EltKind == AR_OBJECT_RESOURCE) {
  7451. if (TargetInfo.ShapeKind == AR_TOBJ_OBJECT) {
  7452. Second = ICK_Flat_Conversion;
  7453. goto lSuccess;
  7454. }
  7455. }
  7456. // Convert scalar/vector/matrix dimensions
  7457. if (!ConvertDimensions(TargetInfo, SourceInfo, Second, Remarks))
  7458. return false;
  7459. // Convert component type
  7460. if (!ConvertComponent(TargetInfo, SourceInfo, ComponentConversion, Remarks))
  7461. return false;
  7462. lSuccess:
  7463. if (standard)
  7464. {
  7465. if (sourceExpr->isLValue())
  7466. {
  7467. if (needsLValueToRValue) {
  7468. // We don't need LValueToRValue cast before casting a derived object
  7469. // to its base.
  7470. if (Second == ICK_HLSL_Derived_To_Base) {
  7471. standard->First = ICK_Identity;
  7472. } else {
  7473. standard->First = ICK_Lvalue_To_Rvalue;
  7474. }
  7475. } else {
  7476. switch (Second)
  7477. {
  7478. case ICK_NoReturn_Adjustment:
  7479. case ICK_Vector_Conversion:
  7480. case ICK_Vector_Splat:
  7481. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  7482. case ICK_Flat_Conversion:
  7483. case ICK_HLSLVector_Splat:
  7484. standard->First = ICK_Lvalue_To_Rvalue;
  7485. break;
  7486. default:
  7487. // Only flat and splat conversions handled.
  7488. break;
  7489. }
  7490. switch (ComponentConversion)
  7491. {
  7492. case ICK_Integral_Promotion:
  7493. case ICK_Integral_Conversion:
  7494. case ICK_Floating_Promotion:
  7495. case ICK_Floating_Conversion:
  7496. case ICK_Floating_Integral:
  7497. case ICK_Boolean_Conversion:
  7498. standard->First = ICK_Lvalue_To_Rvalue;
  7499. break;
  7500. case ICK_Array_To_Pointer:
  7501. standard->First = ICK_Array_To_Pointer;
  7502. break;
  7503. default:
  7504. // Only potential assignments above covered.
  7505. break;
  7506. }
  7507. }
  7508. }
  7509. // Finally fix up the cases for scalar->scalar component conversion, and
  7510. // identity vector/matrix component conversion
  7511. if (ICK_Identity != ComponentConversion) {
  7512. if (Second == ICK_Identity) {
  7513. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  7514. // Scalar to scalar type conversion, use normal mechanism (Second)
  7515. Second = ComponentConversion;
  7516. ComponentConversion = ICK_Identity;
  7517. }
  7518. else if (TargetInfo.ShapeKind != AR_TOBJ_STRING) {
  7519. // vector or matrix dimensions are not being changed, but component type
  7520. // is being converted, so change Second to signal the conversion
  7521. Second = ICK_HLSLVector_Conversion;
  7522. }
  7523. }
  7524. }
  7525. standard->Second = Second;
  7526. standard->ComponentConversion = ComponentConversion;
  7527. // For conversion which change to RValue but targeting reference type
  7528. // Hold the conversion to codeGen
  7529. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  7530. standard->First = ICK_Identity;
  7531. standard->Second = ICK_Identity;
  7532. }
  7533. }
  7534. AssignOpt(Remarks, remarks);
  7535. return true;
  7536. }
  7537. bool HLSLExternalSource::ValidateTypeRequirements(
  7538. SourceLocation loc,
  7539. ArBasicKind elementKind,
  7540. ArTypeObjectKind objectKind,
  7541. bool requiresIntegrals,
  7542. bool requiresNumerics)
  7543. {
  7544. if (requiresIntegrals || requiresNumerics)
  7545. {
  7546. if (!IsObjectKindPrimitiveAggregate(objectKind))
  7547. {
  7548. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  7549. return false;
  7550. }
  7551. }
  7552. if (requiresIntegrals)
  7553. {
  7554. if (!IsBasicKindIntegral(elementKind))
  7555. {
  7556. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  7557. return false;
  7558. }
  7559. }
  7560. else if (requiresNumerics)
  7561. {
  7562. if (!IsBasicKindNumeric(elementKind))
  7563. {
  7564. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  7565. return false;
  7566. }
  7567. }
  7568. return true;
  7569. }
  7570. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  7571. {
  7572. bool isValid = true;
  7573. if (IsBuiltInObjectType(type)) {
  7574. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  7575. isValid = false;
  7576. }
  7577. if (kind == AR_TOBJ_COMPOUND) {
  7578. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  7579. isValid = false;
  7580. }
  7581. return isValid;
  7582. }
  7583. HRESULT HLSLExternalSource::CombineDimensions(
  7584. QualType leftType, QualType rightType, QualType *resultType,
  7585. ImplicitConversionKind &convKind, TYPE_CONVERSION_REMARKS &Remarks)
  7586. {
  7587. ArTypeInfo leftInfo, rightInfo;
  7588. CollectInfo(leftType, &leftInfo);
  7589. CollectInfo(rightType, &rightInfo);
  7590. // Prefer larger, or left if same.
  7591. if (leftInfo.uTotalElts >= rightInfo.uTotalElts) {
  7592. if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7593. *resultType = leftType;
  7594. else if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7595. *resultType = rightType;
  7596. else
  7597. return E_FAIL;
  7598. } else {
  7599. if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7600. *resultType = rightType;
  7601. else if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7602. *resultType = leftType;
  7603. else
  7604. return E_FAIL;
  7605. }
  7606. return S_OK;
  7607. }
  7608. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  7609. /// <param name="OpLoc">Source location for operator.</param>
  7610. /// <param name="Opc">Kind of binary operator.</param>
  7611. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  7612. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  7613. /// <param name="ResultTy">Result type for operator expression.</param>
  7614. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  7615. /// <param name="CompResultTy">Type of computation result.</param>
  7616. void HLSLExternalSource::CheckBinOpForHLSL(
  7617. SourceLocation OpLoc,
  7618. BinaryOperatorKind Opc,
  7619. ExprResult& LHS,
  7620. ExprResult& RHS,
  7621. QualType& ResultTy,
  7622. QualType& CompLHSTy,
  7623. QualType& CompResultTy)
  7624. {
  7625. // At the start, none of the output types should be valid.
  7626. DXASSERT_NOMSG(ResultTy.isNull());
  7627. DXASSERT_NOMSG(CompLHSTy.isNull());
  7628. DXASSERT_NOMSG(CompResultTy.isNull());
  7629. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7630. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7631. // If either expression is invalid to begin with, propagate that.
  7632. if (LHS.isInvalid() || RHS.isInvalid()) {
  7633. return;
  7634. }
  7635. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  7636. // Handle Assign and Comma operators and return
  7637. switch (Opc)
  7638. {
  7639. case BO_AddAssign:
  7640. case BO_AndAssign:
  7641. case BO_DivAssign:
  7642. case BO_MulAssign:
  7643. case BO_RemAssign:
  7644. case BO_ShlAssign:
  7645. case BO_ShrAssign:
  7646. case BO_SubAssign:
  7647. case BO_OrAssign:
  7648. case BO_XorAssign: {
  7649. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  7650. Sema & S);
  7651. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7652. return;
  7653. }
  7654. } break;
  7655. case BO_Assign: {
  7656. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7657. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7658. return;
  7659. }
  7660. bool complained = false;
  7661. ResultTy = LHS.get()->getType();
  7662. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  7663. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  7664. Sema::AssignmentAction::AA_Assigning, &complained)) {
  7665. return;
  7666. }
  7667. StandardConversionSequence standard;
  7668. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  7669. ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7670. return;
  7671. }
  7672. if (RHS.get()->isLValue()) {
  7673. standard.First = ICK_Lvalue_To_Rvalue;
  7674. }
  7675. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  7676. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  7677. return;
  7678. }
  7679. break;
  7680. case BO_Comma:
  7681. // C performs conversions, C++ doesn't but still checks for type completeness.
  7682. // There are also diagnostics for improper comma use.
  7683. // In the HLSL case these cases don't apply or simply aren't surfaced.
  7684. ResultTy = RHS.get()->getType();
  7685. return;
  7686. default:
  7687. // Only assign and comma operations handled.
  7688. break;
  7689. }
  7690. // Leave this diagnostic for last to emulate fxc behavior.
  7691. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  7692. bool unsupportedBoolLvalue = isCompoundAssignment &&
  7693. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7694. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7695. // Turn operand inputs into r-values.
  7696. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7697. if (!isCompoundAssignment) {
  7698. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7699. }
  7700. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7701. if (LHS.isInvalid() || RHS.isInvalid()) {
  7702. return;
  7703. }
  7704. // Gather type info
  7705. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7706. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7707. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7708. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7709. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7710. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7711. // Validate type requirements
  7712. {
  7713. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  7714. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  7715. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  7716. return;
  7717. }
  7718. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  7719. return;
  7720. }
  7721. }
  7722. if (unsupportedBoolLvalue) {
  7723. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7724. return;
  7725. }
  7726. // We don't support binary operators on built-in object types other than assignment or commas.
  7727. {
  7728. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  7729. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  7730. bool isValid;
  7731. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  7732. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  7733. isValid = false;
  7734. }
  7735. if (!isValid) {
  7736. return;
  7737. }
  7738. }
  7739. // We don't support equality comparisons on arrays.
  7740. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  7741. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  7742. return;
  7743. }
  7744. // Combine element types for computation.
  7745. ArBasicKind resultElementKind = leftElementKind;
  7746. {
  7747. if (BinaryOperatorKindIsLogical(Opc)) {
  7748. resultElementKind = AR_BASIC_BOOL;
  7749. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  7750. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  7751. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7752. return;
  7753. }
  7754. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  7755. (resultElementKind == AR_BASIC_LITERAL_INT ||
  7756. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  7757. rightElementKind != AR_BASIC_LITERAL_INT &&
  7758. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  7759. // For case like 1<<x.
  7760. resultElementKind = AR_BASIC_UINT32;
  7761. } else if (resultElementKind == AR_BASIC_BOOL &&
  7762. BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7763. resultElementKind = AR_BASIC_INT32;
  7764. }
  7765. // The following combines the selected/combined element kind above with
  7766. // the dimensions that are legal to implicitly cast. This means that
  7767. // element kind may be taken from one side and the dimensions from the
  7768. // other.
  7769. if (!isCompoundAssignment) {
  7770. // Legal dimension combinations are identical, splat, and truncation.
  7771. // ResultTy will be set to whichever type can be converted to, if legal,
  7772. // with preference for leftType if both are possible.
  7773. if (FAILED(CombineDimensions(LHS.get()->getType(), RHS.get()->getType(), &ResultTy))) {
  7774. // Just choose leftType, and allow ValidateCast to catch this later
  7775. ResultTy = LHS.get()->getType();
  7776. }
  7777. } else {
  7778. ResultTy = LHS.get()->getType();
  7779. }
  7780. // Here, element kind is combined with dimensions for computation type, if different.
  7781. if (resultElementKind != GetTypeElementKind(ResultTy)) {
  7782. UINT rowCount, colCount;
  7783. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7784. ResultTy = NewSimpleAggregateType(GetTypeObjectKind(ResultTy), resultElementKind, 0, rowCount, colCount);
  7785. }
  7786. }
  7787. bool bFailedFirstRHSCast = false;
  7788. // Perform necessary conversion sequences for LHS and RHS
  7789. if (RHS.get()->getType() != ResultTy) {
  7790. StandardConversionSequence standard;
  7791. // Suppress type narrowing or truncation warnings for RHS on bitwise shift, since we only care about the LHS type.
  7792. bool bSuppressWarnings = BinaryOperatorKindIsBitwiseShift(Opc);
  7793. // Suppress errors on compound assignment, since we will vaildate the cast to the final type later.
  7794. bool bSuppressErrors = isCompoundAssignment;
  7795. // If compound assignment, suppress errors until later, but report warning (vector truncation/type narrowing) here.
  7796. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, bSuppressWarnings, bSuppressErrors, &standard)) {
  7797. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7798. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7799. } else if (!isCompoundAssignment) {
  7800. // If compound assignment, validate cast from RHS directly to LHS later, otherwise, fail here.
  7801. ResultTy = QualType();
  7802. return;
  7803. } else {
  7804. bFailedFirstRHSCast = true;
  7805. }
  7806. }
  7807. if (isCompoundAssignment) {
  7808. CompResultTy = ResultTy;
  7809. CompLHSTy = CompResultTy;
  7810. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  7811. // then converts to the result type and then assigns.
  7812. //
  7813. // So int + float promotes the int to float, does a floating-point addition,
  7814. // then the result becomes and int and is assigned.
  7815. ResultTy = LHSTypeAsPossibleLValue;
  7816. // Validate remainder of cast from computation type to final result type
  7817. StandardConversionSequence standard;
  7818. if (!ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7819. ResultTy = QualType();
  7820. return;
  7821. }
  7822. DXASSERT_LOCALVAR(bFailedFirstRHSCast, !bFailedFirstRHSCast,
  7823. "otherwise, hit compound assign case that failed RHS -> CompResultTy cast, but succeeded RHS -> LHS cast.");
  7824. } else if (LHS.get()->getType() != ResultTy) {
  7825. StandardConversionSequence standard;
  7826. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7827. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7828. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7829. } else {
  7830. ResultTy = QualType();
  7831. return;
  7832. }
  7833. }
  7834. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  7835. {
  7836. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  7837. // Return bool vector for vector types.
  7838. if (IsVectorType(m_sema, ResultTy)) {
  7839. UINT rowCount, colCount;
  7840. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7841. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  7842. } else if (IsMatrixType(m_sema, ResultTy)) {
  7843. UINT rowCount, colCount;
  7844. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7845. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  7846. } else
  7847. ResultTy = m_context->BoolTy.withConst();
  7848. }
  7849. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  7850. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  7851. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  7852. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  7853. return;
  7854. }
  7855. }
  7856. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  7857. if (resultElementKind == AR_BASIC_FLOAT64) {
  7858. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  7859. return;
  7860. }
  7861. }
  7862. }
  7863. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  7864. /// <param name="OpLoc">Source location for operator.</param>
  7865. /// <param name="Opc">Kind of operator.</param>
  7866. /// <param name="InputExpr">Input expression to the operator.</param>
  7867. /// <param name="VK">Value kind for resulting expression.</param>
  7868. /// <param name="OK">Object kind for resulting expression.</param>
  7869. /// <returns>The result type for the expression.</returns>
  7870. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  7871. SourceLocation OpLoc,
  7872. UnaryOperatorKind Opc,
  7873. ExprResult& InputExpr,
  7874. ExprValueKind& VK,
  7875. ExprObjectKind& OK)
  7876. {
  7877. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  7878. if (InputExpr.isInvalid())
  7879. return QualType();
  7880. // Reject unsupported operators * and &
  7881. switch (Opc) {
  7882. case UO_AddrOf:
  7883. case UO_Deref:
  7884. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  7885. return QualType();
  7886. default:
  7887. // Only * and & covered.
  7888. break;
  7889. }
  7890. Expr* expr = InputExpr.get();
  7891. if (expr->isTypeDependent())
  7892. return m_context->DependentTy;
  7893. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  7894. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  7895. if (elementKind == AR_BASIC_ENUM) {
  7896. bool isInc = IsIncrementOp(Opc);
  7897. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  7898. return QualType();
  7899. }
  7900. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7901. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  7902. return QualType();
  7903. } else {
  7904. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  7905. if (InputExpr.isInvalid()) return QualType();
  7906. }
  7907. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  7908. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7909. return QualType();
  7910. }
  7911. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7912. InputExpr = PromoteToIntIfBool(InputExpr);
  7913. expr = InputExpr.get();
  7914. elementKind = GetTypeElementKind(expr->getType());
  7915. }
  7916. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  7917. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  7918. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  7919. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  7920. return QualType();
  7921. }
  7922. if (Opc == UnaryOperatorKind::UO_Minus) {
  7923. if (IS_BASIC_UINT(Opc)) {
  7924. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  7925. }
  7926. }
  7927. // By default, the result type is the operand type.
  7928. // Logical not however should cast to a bool.
  7929. QualType resultType = expr->getType();
  7930. if (Opc == UnaryOperatorKind::UO_LNot) {
  7931. UINT rowCount, colCount;
  7932. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  7933. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  7934. StandardConversionSequence standard;
  7935. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  7936. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  7937. return QualType();
  7938. }
  7939. // Cast argument.
  7940. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7941. if (result.isUsable()) {
  7942. InputExpr = result.get();
  7943. }
  7944. }
  7945. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  7946. if (isPrefix) {
  7947. VK = VK_LValue;
  7948. return resultType;
  7949. }
  7950. else {
  7951. VK = VK_RValue;
  7952. return resultType.getUnqualifiedType();
  7953. }
  7954. }
  7955. clang::QualType HLSLExternalSource::CheckVectorConditional(
  7956. _In_ ExprResult &Cond,
  7957. _In_ ExprResult &LHS,
  7958. _In_ ExprResult &RHS,
  7959. _In_ SourceLocation QuestionLoc)
  7960. {
  7961. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  7962. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7963. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7964. // If either expression is invalid to begin with, propagate that.
  7965. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  7966. return QualType();
  7967. }
  7968. // Gather type info
  7969. QualType condType = GetStructuralForm(Cond.get()->getType());
  7970. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7971. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7972. ArBasicKind condElementKind = GetTypeElementKind(condType);
  7973. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7974. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7975. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  7976. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7977. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7978. QualType ResultTy = leftType;
  7979. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  7980. if (!condIsSimple) {
  7981. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  7982. return QualType();
  7983. }
  7984. UINT rowCountCond, colCountCond;
  7985. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  7986. bool leftIsSimple =
  7987. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  7988. leftObjectKind == AR_TOBJ_MATRIX;
  7989. bool rightIsSimple =
  7990. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  7991. rightObjectKind == AR_TOBJ_MATRIX;
  7992. if (!leftIsSimple || !rightIsSimple) {
  7993. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  7994. if (leftType == rightType) {
  7995. return leftType;
  7996. }
  7997. }
  7998. // NOTE: Limiting this operator to working only on basic numeric types.
  7999. // This is due to extremely limited (and even broken) support for any other case.
  8000. // In the future we may decide to support more cases.
  8001. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  8002. return QualType();
  8003. }
  8004. // Types should be only scalar, vector, or matrix after this point.
  8005. ArBasicKind resultElementKind = leftElementKind;
  8006. // Combine LHS and RHS element types for computation.
  8007. if (leftElementKind != rightElementKind) {
  8008. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  8009. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  8010. return QualType();
  8011. }
  8012. }
  8013. // Restore left/right type to original to avoid stripping attributed type or typedef type
  8014. leftType = LHS.get()->getType();
  8015. rightType = RHS.get()->getType();
  8016. // Combine LHS and RHS dimensions
  8017. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  8018. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  8019. return QualType();
  8020. }
  8021. UINT rowCount, colCount;
  8022. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8023. // If result is scalar, use condition dimensions.
  8024. // Otherwise, condition must either match or is scalar, then use result dimensions
  8025. if (rowCount * colCount == 1) {
  8026. rowCount = rowCountCond;
  8027. colCount = colCountCond;
  8028. }
  8029. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  8030. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  8031. return QualType();
  8032. }
  8033. // Here, element kind is combined with dimensions for result type.
  8034. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8035. // Cast condition to RValue
  8036. if (Cond.get()->isLValue())
  8037. Cond.set(CreateLValueToRValueCast(Cond.get()));
  8038. // Convert condition component type to bool, using result component dimensions
  8039. if (condElementKind != AR_BASIC_BOOL) {
  8040. QualType boolType = NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8041. StandardConversionSequence standard;
  8042. if (ValidateCast(SourceLocation(), Cond.get(), boolType, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8043. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8044. Cond = m_sema->PerformImplicitConversion(Cond.get(), boolType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8045. }
  8046. else {
  8047. return QualType();
  8048. }
  8049. }
  8050. // TODO: Is this correct? Does fxc support lvalue return here?
  8051. // Cast LHS/RHS to RValue
  8052. if (LHS.get()->isLValue())
  8053. LHS.set(CreateLValueToRValueCast(LHS.get()));
  8054. if (RHS.get()->isLValue())
  8055. RHS.set(CreateLValueToRValueCast(RHS.get()));
  8056. if (leftType != ResultTy) {
  8057. StandardConversionSequence standard;
  8058. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8059. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8060. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8061. }
  8062. else {
  8063. return QualType();
  8064. }
  8065. }
  8066. if (rightType != ResultTy) {
  8067. StandardConversionSequence standard;
  8068. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8069. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8070. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8071. }
  8072. else {
  8073. return QualType();
  8074. }
  8075. }
  8076. return ResultTy;
  8077. }
  8078. // Apply type specifier sign to the given QualType.
  8079. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  8080. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  8081. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  8082. _In_ clang::SourceLocation Loc) {
  8083. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  8084. return type;
  8085. }
  8086. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  8087. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  8088. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  8089. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  8090. return type;
  8091. }
  8092. // check if element type is unsigned and check if such vector exists
  8093. // If not create a new one, Make a QualType of the new kind
  8094. ArBasicKind elementKind = GetTypeElementKind(type);
  8095. // Only ints can have signed/unsigend ty
  8096. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  8097. return type;
  8098. }
  8099. else {
  8100. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  8101. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  8102. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  8103. // Get new vector types for a given TypeSpecifierSign.
  8104. if (objKind == AR_TOBJ_VECTOR) {
  8105. UINT colCount = GetHLSLVecSize(type);
  8106. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  8107. return m_context->getTypeDeclType(qts);
  8108. } else if (objKind == AR_TOBJ_MATRIX) {
  8109. UINT rowCount, colCount;
  8110. GetRowsAndCols(type, rowCount, colCount);
  8111. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  8112. return m_context->getTypeDeclType(qts);
  8113. } else {
  8114. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  8115. return m_scalarTypes[newScalarType];
  8116. }
  8117. }
  8118. }
  8119. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  8120. FunctionTemplateDecl *FunctionTemplate,
  8121. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8122. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8123. {
  8124. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  8125. // Get information about the function we have.
  8126. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  8127. DXASSERT(functionMethod != nullptr,
  8128. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  8129. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  8130. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  8131. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  8132. QualType functionTemplateTypeArg {};
  8133. if (ExplicitTemplateArgs != nullptr && ExplicitTemplateArgs->size() == 1) {
  8134. const TemplateArgument &firstTemplateArg = (*ExplicitTemplateArgs)[0].getArgument();
  8135. if (firstTemplateArg.getKind() == TemplateArgument::ArgKind::Type)
  8136. functionTemplateTypeArg = firstTemplateArg.getAsType();
  8137. }
  8138. // Handle subscript overloads.
  8139. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  8140. {
  8141. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  8142. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  8143. if (!findResult.Found())
  8144. {
  8145. // This might be a nested type. Do a lookup on the parent.
  8146. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  8147. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  8148. {
  8149. return Sema::TemplateDeductionResult::TDK_Invalid;
  8150. }
  8151. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  8152. if (!findResult.Found())
  8153. {
  8154. return Sema::TemplateDeductionResult::TDK_Invalid;
  8155. }
  8156. DXASSERT(
  8157. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  8158. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  8159. "otherwise FindStructBasicType should have failed - no other types are allowed");
  8160. objectElement = GetFirstElementTypeFromDecl(
  8161. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  8162. }
  8163. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  8164. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8165. FunctionTemplate->getCanonicalDecl());
  8166. return Sema::TemplateDeductionResult::TDK_Success;
  8167. }
  8168. // Reject overload lookups that aren't identifier-based.
  8169. if (!FunctionTemplate->getDeclName().isIdentifier())
  8170. {
  8171. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8172. }
  8173. // Find the table of intrinsics based on the object type.
  8174. const HLSL_INTRINSIC* intrinsics = nullptr;
  8175. size_t intrinsicCount = 0;
  8176. const char* objectName = nullptr;
  8177. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  8178. DXASSERT(objectName != nullptr &&
  8179. (intrinsics != nullptr || m_intrinsicTables.size() > 0),
  8180. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  8181. "or the parser let a user-defined template object through");
  8182. // Look for an intrinsic for which we can match arguments.
  8183. std::vector<QualType> argTypes;
  8184. StringRef nameIdentifier = FunctionTemplate->getName();
  8185. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  8186. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  8187. while (cursor != end)
  8188. {
  8189. if (!MatchArguments(*cursor, objectElement, functionTemplateTypeArg, Args, &argTypes))
  8190. {
  8191. ++cursor;
  8192. continue;
  8193. }
  8194. // Currently only intrinsic we allow for explicit template arguments are
  8195. // for Load/Store for ByteAddressBuffer/RWByteAddressBuffer
  8196. // TODO: handle template arguments for future intrinsics in a more natural way
  8197. // Check Explicit template arguments
  8198. UINT intrinsicOp = (*cursor)->Op;
  8199. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  8200. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  8201. bool IsBAB =
  8202. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  8203. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  8204. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  8205. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  8206. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  8207. bool isLegalTemplate = false;
  8208. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  8209. auto TemplateDiag = diag::err_hlsl_intrinsic_template_arg_unsupported;
  8210. if (ExplicitTemplateArgs->size() >= 1 && (IsBABLoad || IsBABStore)) {
  8211. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_requires_2018;
  8212. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  8213. if (Is2018) {
  8214. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_numeric;
  8215. if (ExplicitTemplateArgs->size() == 1
  8216. && !functionTemplateTypeArg.isNull()
  8217. && hlsl::IsHLSLNumericOrAggregateOfNumericType(functionTemplateTypeArg)) {
  8218. isLegalTemplate = true;
  8219. argTypes[0] = functionTemplateTypeArg;
  8220. }
  8221. }
  8222. }
  8223. if (!isLegalTemplate) {
  8224. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  8225. return Sema::TemplateDeductionResult::TDK_Invalid;
  8226. }
  8227. } else if (IsBABStore) {
  8228. // Prior to HLSL 2018, Store operation only stored scalar uint.
  8229. if (!Is2018) {
  8230. if (GetNumElements(argTypes[2]) != 1) {
  8231. getSema()->Diag(Args[1]->getLocStart(),
  8232. diag::err_ovl_no_viable_member_function_in_call)
  8233. << intrinsicName;
  8234. return Sema::TemplateDeductionResult::TDK_Invalid;
  8235. }
  8236. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  8237. 32, /*signed*/ false);
  8238. }
  8239. }
  8240. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes.data(), argTypes.size());
  8241. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8242. FunctionTemplate->getCanonicalDecl());
  8243. if (!IsValidateObjectElement(*cursor, objectElement)) {
  8244. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  8245. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  8246. }
  8247. return Sema::TemplateDeductionResult::TDK_Success;
  8248. }
  8249. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8250. }
  8251. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  8252. {
  8253. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  8254. }
  8255. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  8256. QualType DestType,
  8257. Sema::CheckedConversionKind CCK,
  8258. const SourceRange &OpRange, unsigned &msg,
  8259. CastKind &Kind, CXXCastPath &BasePath,
  8260. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  8261. _Inout_opt_ StandardConversionSequence* standard)
  8262. {
  8263. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  8264. bool explicitConversion
  8265. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  8266. bool suppressWarnings = explicitConversion || SuppressWarnings;
  8267. SourceLocation loc = OpRange.getBegin();
  8268. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  8269. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  8270. // so do this here until we figure out why this is needed.
  8271. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  8272. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  8273. }
  8274. return true;
  8275. }
  8276. // ValidateCast includes its own error messages.
  8277. msg = 0;
  8278. return false;
  8279. }
  8280. /// <summary>
  8281. /// Checks if a subscript index argument can be initialized from the given expression.
  8282. /// </summary>
  8283. /// <param name="SrcExpr">Source expression used as argument.</param>
  8284. /// <param name="DestType">Parameter type to initialize.</param>
  8285. /// <remarks>
  8286. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  8287. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  8288. /// </remarks>
  8289. ImplicitConversionSequence
  8290. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  8291. clang::QualType DestType) {
  8292. DXASSERT_NOMSG(SrcExpr != nullptr);
  8293. DXASSERT_NOMSG(!DestType.isNull());
  8294. unsigned int msg = 0;
  8295. CastKind kind;
  8296. CXXCastPath path;
  8297. ImplicitConversionSequence sequence;
  8298. sequence.setStandard();
  8299. ExprResult sourceExpr(SrcExpr);
  8300. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  8301. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8302. SrcExpr->getType(), DestType);
  8303. } else if (!TryStaticCastForHLSL(
  8304. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  8305. msg, kind, path, ListInitializationFalse,
  8306. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  8307. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8308. SrcExpr->getType(), DestType);
  8309. }
  8310. return sequence;
  8311. }
  8312. template <typename T>
  8313. static
  8314. bool IsValueInRange(T value, T minValue, T maxValue) {
  8315. return minValue <= value && value <= maxValue;
  8316. }
  8317. #define D3DX_16F_MAX 6.550400e+004 // max value
  8318. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  8319. static
  8320. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  8321. {
  8322. DXASSERT_NOMSG(minValue != nullptr);
  8323. DXASSERT_NOMSG(maxValue != nullptr);
  8324. switch (basicKind) {
  8325. case AR_BASIC_MIN10FLOAT:
  8326. case AR_BASIC_MIN16FLOAT:
  8327. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  8328. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8329. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  8330. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  8331. default:
  8332. // No other float types.
  8333. break;
  8334. }
  8335. DXASSERT(false, "unreachable");
  8336. *minValue = 0; *maxValue = 0;
  8337. return;
  8338. }
  8339. static
  8340. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  8341. {
  8342. DXASSERT_NOMSG(maxValue != nullptr);
  8343. switch (basicKind) {
  8344. case AR_BASIC_BOOL: *maxValue = 1; return;
  8345. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  8346. case AR_BASIC_MIN16UINT:
  8347. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  8348. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  8349. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  8350. default:
  8351. // No other unsigned int types.
  8352. break;
  8353. }
  8354. DXASSERT(false, "unreachable");
  8355. *maxValue = 0;
  8356. return;
  8357. }
  8358. static
  8359. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  8360. {
  8361. DXASSERT_NOMSG(minValue != nullptr);
  8362. DXASSERT_NOMSG(maxValue != nullptr);
  8363. switch (basicKind) {
  8364. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  8365. case AR_BASIC_MIN12INT:
  8366. case AR_BASIC_MIN16INT:
  8367. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  8368. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  8369. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  8370. default:
  8371. // No other signed int types.
  8372. break;
  8373. }
  8374. DXASSERT(false, "unreachable");
  8375. *minValue = 0; *maxValue = 0;
  8376. return;
  8377. }
  8378. static
  8379. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  8380. {
  8381. if (IS_BASIC_FLOAT(basicKind)) {
  8382. double val;
  8383. if (value.isInt()) {
  8384. val = value.getInt().getLimitedValue();
  8385. } else if (value.isFloat()) {
  8386. llvm::APFloat floatValue = value.getFloat();
  8387. if (!floatValue.isFinite()) {
  8388. return false;
  8389. }
  8390. llvm::APFloat valueFloat = value.getFloat();
  8391. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  8392. val = value.getFloat().convertToFloat();
  8393. }
  8394. else {
  8395. val = value.getFloat().convertToDouble();
  8396. }
  8397. } else {
  8398. return false;
  8399. }
  8400. double minValue, maxValue;
  8401. GetFloatLimits(basicKind, &minValue, &maxValue);
  8402. return IsValueInRange(val, minValue, maxValue);
  8403. }
  8404. else if (IS_BASIC_SINT(basicKind)) {
  8405. if (!value.isInt()) {
  8406. return false;
  8407. }
  8408. int64_t val = value.getInt().getSExtValue();
  8409. int64_t minValue, maxValue;
  8410. GetSignedLimits(basicKind, &minValue, &maxValue);
  8411. return IsValueInRange(val, minValue, maxValue);
  8412. }
  8413. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  8414. if (!value.isInt()) {
  8415. return false;
  8416. }
  8417. uint64_t val = value.getInt().getLimitedValue();
  8418. uint64_t maxValue;
  8419. GetUnsignedLimit(basicKind, &maxValue);
  8420. return IsValueInRange(val, (uint64_t)0, maxValue);
  8421. }
  8422. else {
  8423. return false;
  8424. }
  8425. }
  8426. static
  8427. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  8428. {
  8429. DXASSERT_NOMSG(!targetType.isNull());
  8430. DXASSERT_NOMSG(sourceExpr != nullptr);
  8431. Expr::EvalResult evalResult;
  8432. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  8433. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  8434. return IsValueInBasicRange(targetKind, evalResult.Val);
  8435. }
  8436. }
  8437. return false;
  8438. }
  8439. bool HLSLExternalSource::ValidateCast(
  8440. SourceLocation OpLoc,
  8441. _In_ Expr* sourceExpr,
  8442. QualType target,
  8443. bool explicitConversion,
  8444. bool suppressWarnings,
  8445. bool suppressErrors,
  8446. _Inout_opt_ StandardConversionSequence* standard)
  8447. {
  8448. DXASSERT_NOMSG(sourceExpr != nullptr);
  8449. if (OpLoc.isInvalid())
  8450. OpLoc = sourceExpr->getExprLoc();
  8451. QualType source = sourceExpr->getType();
  8452. TYPE_CONVERSION_REMARKS remarks;
  8453. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  8454. {
  8455. const bool IsOutputParameter = false;
  8456. //
  8457. // Check whether the lack of explicit-ness matters.
  8458. //
  8459. // Setting explicitForDiagnostics to true in that case will avoid the message
  8460. // saying anything about the implicit nature of the cast, when adding the
  8461. // explicit cast won't make a difference.
  8462. //
  8463. bool explicitForDiagnostics = explicitConversion;
  8464. if (explicitConversion == false)
  8465. {
  8466. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  8467. {
  8468. // Can't convert either way - implicit/explicit doesn't matter.
  8469. explicitForDiagnostics = true;
  8470. }
  8471. }
  8472. if (!suppressErrors)
  8473. {
  8474. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  8475. << explicitForDiagnostics << IsOutputParameter << source << target;
  8476. }
  8477. return false;
  8478. }
  8479. if (!suppressWarnings)
  8480. {
  8481. if (!explicitConversion)
  8482. {
  8483. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  8484. {
  8485. // This is a much more restricted version of the analysis does
  8486. // StandardConversionSequence::getNarrowingKind
  8487. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  8488. {
  8489. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  8490. }
  8491. }
  8492. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  8493. {
  8494. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  8495. }
  8496. }
  8497. }
  8498. return true;
  8499. }
  8500. ////////////////////////////////////////////////////////////////////////////////
  8501. // Functions exported from this translation unit. //
  8502. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  8503. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  8504. SourceLocation OpLoc,
  8505. UnaryOperatorKind Opc,
  8506. ExprResult& InputExpr,
  8507. ExprValueKind& VK,
  8508. ExprObjectKind& OK)
  8509. {
  8510. ExternalSemaSource* externalSource = self.getExternalSource();
  8511. if (externalSource == nullptr) {
  8512. return QualType();
  8513. }
  8514. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8515. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  8516. }
  8517. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  8518. void hlsl::CheckBinOpForHLSL(Sema& self,
  8519. SourceLocation OpLoc,
  8520. BinaryOperatorKind Opc,
  8521. ExprResult& LHS,
  8522. ExprResult& RHS,
  8523. QualType& ResultTy,
  8524. QualType& CompLHSTy,
  8525. QualType& CompResultTy)
  8526. {
  8527. ExternalSemaSource* externalSource = self.getExternalSource();
  8528. if (externalSource == nullptr) {
  8529. return;
  8530. }
  8531. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8532. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  8533. }
  8534. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  8535. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  8536. {
  8537. DXASSERT_NOMSG(Template != nullptr);
  8538. ExternalSemaSource* externalSource = self.getExternalSource();
  8539. if (externalSource == nullptr) {
  8540. return false;
  8541. }
  8542. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8543. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  8544. }
  8545. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  8546. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  8547. FunctionTemplateDecl *FunctionTemplate,
  8548. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8549. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8550. {
  8551. return HLSLExternalSource::FromSema(self)
  8552. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  8553. }
  8554. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  8555. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  8556. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  8557. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  8558. self->Diag(condExpr->getLocStart(),
  8559. diag::err_hlsl_control_flow_cond_not_scalar)
  8560. << StmtName;
  8561. return;
  8562. }
  8563. condExpr = IC->getSubExpr();
  8564. }
  8565. }
  8566. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  8567. {
  8568. // TODO: handle shorthand cases.
  8569. return left.size() == 0 || right.size() == 0 || left.equals(right);
  8570. }
  8571. void hlsl::DiagnosePackingOffset(
  8572. clang::Sema* self,
  8573. SourceLocation loc,
  8574. clang::QualType type,
  8575. int componentOffset)
  8576. {
  8577. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  8578. if (componentOffset > 0) {
  8579. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8580. ArBasicKind element = source->GetTypeElementKind(type);
  8581. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  8582. // Only perform some simple validation for now.
  8583. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  8584. int count = GetElementCount(type);
  8585. if (count > (4 - componentOffset)) {
  8586. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  8587. }
  8588. }
  8589. }
  8590. }
  8591. void hlsl::DiagnoseRegisterType(
  8592. clang::Sema* self,
  8593. clang::SourceLocation loc,
  8594. clang::QualType type,
  8595. char registerType)
  8596. {
  8597. // Register type can be zero if only a register space was provided.
  8598. if (registerType == 0)
  8599. return;
  8600. if (registerType >= 'A' && registerType <= 'Z')
  8601. registerType = registerType + ('a' - 'A');
  8602. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8603. ArBasicKind element = source->GetTypeElementKind(type);
  8604. StringRef expected("none");
  8605. bool isValid = true;
  8606. bool isWarning = false;
  8607. switch (element)
  8608. {
  8609. case AR_BASIC_BOOL:
  8610. case AR_BASIC_LITERAL_FLOAT:
  8611. case AR_BASIC_FLOAT16:
  8612. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8613. case AR_BASIC_FLOAT32:
  8614. case AR_BASIC_FLOAT64:
  8615. case AR_BASIC_LITERAL_INT:
  8616. case AR_BASIC_INT8:
  8617. case AR_BASIC_UINT8:
  8618. case AR_BASIC_INT16:
  8619. case AR_BASIC_UINT16:
  8620. case AR_BASIC_INT32:
  8621. case AR_BASIC_UINT32:
  8622. case AR_BASIC_INT64:
  8623. case AR_BASIC_UINT64:
  8624. case AR_BASIC_MIN10FLOAT:
  8625. case AR_BASIC_MIN16FLOAT:
  8626. case AR_BASIC_MIN12INT:
  8627. case AR_BASIC_MIN16INT:
  8628. case AR_BASIC_MIN16UINT:
  8629. expected = "'b', 'c', or 'i'";
  8630. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i';
  8631. break;
  8632. case AR_OBJECT_TEXTURE1D:
  8633. case AR_OBJECT_TEXTURE1D_ARRAY:
  8634. case AR_OBJECT_TEXTURE2D:
  8635. case AR_OBJECT_TEXTURE2D_ARRAY:
  8636. case AR_OBJECT_TEXTURE3D:
  8637. case AR_OBJECT_TEXTURECUBE:
  8638. case AR_OBJECT_TEXTURECUBE_ARRAY:
  8639. case AR_OBJECT_TEXTURE2DMS:
  8640. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  8641. expected = "'t' or 's'";
  8642. isValid = registerType == 't' || registerType == 's';
  8643. break;
  8644. case AR_OBJECT_SAMPLER:
  8645. case AR_OBJECT_SAMPLER1D:
  8646. case AR_OBJECT_SAMPLER2D:
  8647. case AR_OBJECT_SAMPLER3D:
  8648. case AR_OBJECT_SAMPLERCUBE:
  8649. case AR_OBJECT_SAMPLERCOMPARISON:
  8650. expected = "'s' or 't'";
  8651. isValid = registerType == 's' || registerType == 't';
  8652. break;
  8653. case AR_OBJECT_BUFFER:
  8654. expected = "'t'";
  8655. isValid = registerType == 't';
  8656. break;
  8657. case AR_OBJECT_POINTSTREAM:
  8658. case AR_OBJECT_LINESTREAM:
  8659. case AR_OBJECT_TRIANGLESTREAM:
  8660. isValid = false;
  8661. isWarning = true;
  8662. break;
  8663. case AR_OBJECT_INPUTPATCH:
  8664. case AR_OBJECT_OUTPUTPATCH:
  8665. isValid = false;
  8666. isWarning = true;
  8667. break;
  8668. case AR_OBJECT_RWTEXTURE1D:
  8669. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  8670. case AR_OBJECT_RWTEXTURE2D:
  8671. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  8672. case AR_OBJECT_RWTEXTURE3D:
  8673. case AR_OBJECT_RWBUFFER:
  8674. expected = "'u'";
  8675. isValid = registerType == 'u';
  8676. break;
  8677. case AR_OBJECT_BYTEADDRESS_BUFFER:
  8678. case AR_OBJECT_STRUCTURED_BUFFER:
  8679. expected = "'t'";
  8680. isValid = registerType == 't';
  8681. break;
  8682. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  8683. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  8684. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  8685. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8686. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8687. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8688. expected = "'u'";
  8689. isValid = registerType == 'u';
  8690. break;
  8691. case AR_OBJECT_CONSTANT_BUFFER:
  8692. expected = "'b'";
  8693. isValid = registerType == 'b';
  8694. break;
  8695. case AR_OBJECT_TEXTURE_BUFFER:
  8696. expected = "'t'";
  8697. isValid = registerType == 't';
  8698. break;
  8699. case AR_OBJECT_ROVBUFFER:
  8700. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  8701. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  8702. case AR_OBJECT_ROVTEXTURE1D:
  8703. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  8704. case AR_OBJECT_ROVTEXTURE2D:
  8705. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  8706. case AR_OBJECT_ROVTEXTURE3D:
  8707. case AR_OBJECT_FEEDBACKTEXTURE2D:
  8708. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  8709. expected = "'u'";
  8710. isValid = registerType == 'u';
  8711. break;
  8712. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  8713. isWarning = true;
  8714. break; // So we don't care what you tried to bind it to
  8715. default: // Other types have no associated registers.
  8716. break;
  8717. }
  8718. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  8719. // a warning instead.
  8720. if (!isValid) {
  8721. unsigned DiagID = isWarning ? diag::warn_hlsl_incorrect_bind_semantic : diag::err_hlsl_incorrect_bind_semantic;
  8722. self->Diag(loc, DiagID) << expected;
  8723. }
  8724. }
  8725. struct NameLookup {
  8726. FunctionDecl *Found;
  8727. FunctionDecl *Other;
  8728. };
  8729. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  8730. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  8731. FunctionDecl *pFoundDecl = nullptr;
  8732. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  8733. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  8734. if (!pFnDecl) continue;
  8735. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  8736. if (pFoundDecl) {
  8737. return NameLookup{ pFoundDecl, pFnDecl };
  8738. }
  8739. pFoundDecl = pFnDecl;
  8740. }
  8741. return NameLookup{ pFoundDecl, nullptr };
  8742. }
  8743. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  8744. DXASSERT_NOMSG(self != nullptr);
  8745. // Don't bother with global validation if compilation has already failed.
  8746. if (self->getDiagnostics().hasErrorOccurred()) {
  8747. return;
  8748. }
  8749. // Don't check entry function for library.
  8750. if (self->getLangOpts().IsHLSLLibrary) {
  8751. // TODO: validate no recursion start from every function.
  8752. return;
  8753. }
  8754. // TODO: make these error 'real' errors rather than on-the-fly things
  8755. // Validate that the entry point is available.
  8756. DiagnosticsEngine &Diags = self->getDiagnostics();
  8757. FunctionDecl *pEntryPointDecl = nullptr;
  8758. FunctionDecl *pPatchFnDecl = nullptr;
  8759. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  8760. if (!EntryPointName.empty()) {
  8761. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  8762. if (NL.Found && NL.Other) {
  8763. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  8764. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  8765. // string, and so ambiguous points will produce an error earlier on.
  8766. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8767. "ambiguous entry point function");
  8768. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  8769. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  8770. return;
  8771. }
  8772. pEntryPointDecl = NL.Found;
  8773. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  8774. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8775. "missing entry point definition");
  8776. Diags.Report(id);
  8777. return;
  8778. }
  8779. }
  8780. // Validate that there is no recursion; start with the entry function.
  8781. // NOTE: the information gathered here could be used to bypass code generation
  8782. // on functions that are unreachable (as an early form of dead code elimination).
  8783. if (pEntryPointDecl) {
  8784. const auto *shaderModel =
  8785. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  8786. if (shaderModel->IsGS()) {
  8787. // Validate that GS has the maxvertexcount attribute
  8788. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  8789. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8790. << "GS"
  8791. << "maxvertexcount";
  8792. return;
  8793. }
  8794. } else if (shaderModel->IsHS()) {
  8795. if (const HLSLPatchConstantFuncAttr *Attr =
  8796. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8797. NameLookup NL = GetSingleFunctionDeclByName(
  8798. self, Attr->getFunctionName(), /*checkPatch*/ true);
  8799. if (!NL.Found || !NL.Found->hasBody()) {
  8800. unsigned id =
  8801. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8802. "missing patch function definition");
  8803. Diags.Report(id);
  8804. return;
  8805. }
  8806. pPatchFnDecl = NL.Found;
  8807. } else {
  8808. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8809. << "HS"
  8810. << "patchconstantfunc";
  8811. return;
  8812. }
  8813. } else if (shaderModel->IsMS()) {
  8814. // Validate that MS has the numthreads attribute
  8815. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  8816. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8817. << "MS"
  8818. << "numthreads";
  8819. return;
  8820. }
  8821. // Validate that MS has the outputtopology attribute
  8822. if (!pEntryPointDecl->hasAttr<HLSLOutputTopologyAttr>()) {
  8823. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8824. << "MS"
  8825. << "outputtopology";
  8826. return;
  8827. }
  8828. } else if (shaderModel->IsAS()) {
  8829. // Validate that AS has the numthreads attribute
  8830. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  8831. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8832. << "AS"
  8833. << "numthreads";
  8834. return;
  8835. }
  8836. }
  8837. hlsl::CallGraphWithRecurseGuard CG;
  8838. CG.BuildForEntry(pEntryPointDecl);
  8839. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  8840. if (pResult) {
  8841. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8842. "recursive functions not allowed");
  8843. Diags.Report(pResult->getSourceRange().getBegin(), id);
  8844. }
  8845. if (pPatchFnDecl) {
  8846. CG.BuildForEntry(pPatchFnDecl);
  8847. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  8848. if (pPatchFnDecl) {
  8849. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8850. "recursive functions not allowed (via patch function)");
  8851. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  8852. }
  8853. }
  8854. }
  8855. }
  8856. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  8857. Sema& S,
  8858. std::vector<hlsl::UnusualAnnotation *>& annotations)
  8859. {
  8860. bool packoffsetOverriddenReported = false;
  8861. auto && iter = annotations.begin();
  8862. auto && end = annotations.end();
  8863. for (; iter != end; ++iter) {
  8864. switch ((*iter)->getKind()) {
  8865. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8866. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  8867. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  8868. if (!packoffsetOverriddenReported) {
  8869. auto newIter = iter;
  8870. ++newIter;
  8871. while (newIter != end) {
  8872. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  8873. if (other != nullptr &&
  8874. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  8875. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  8876. packoffsetOverriddenReported = true;
  8877. break;
  8878. }
  8879. ++newIter;
  8880. }
  8881. }
  8882. break;
  8883. }
  8884. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8885. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  8886. // Check whether this will conflict with other register assignments of the same type.
  8887. auto newIter = iter;
  8888. ++newIter;
  8889. while (newIter != end) {
  8890. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  8891. // Same register bank and profile, but different number.
  8892. if (other != nullptr &&
  8893. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  8894. other->RegisterType == registerAssignment->RegisterType &&
  8895. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  8896. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  8897. // Obvious conflict - report it up front.
  8898. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  8899. }
  8900. ++newIter;
  8901. }
  8902. break;
  8903. }
  8904. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8905. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  8906. // No common validation to be performed.
  8907. break;
  8908. }
  8909. }
  8910. }
  8911. }
  8912. clang::OverloadingResult
  8913. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  8914. clang::OverloadCandidateSet &set,
  8915. clang::OverloadCandidateSet::iterator &Best) {
  8916. return HLSLExternalSource::FromSema(&S)
  8917. ->GetBestViableFunction(Loc, set, Best);
  8918. }
  8919. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  8920. const InitializedEntity &Entity,
  8921. const InitializationKind &Kind,
  8922. MultiExprArg Args,
  8923. bool TopLevelOfInitList,
  8924. InitializationSequence *initSequence) {
  8925. return HLSLExternalSource::FromSema(self)
  8926. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  8927. }
  8928. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  8929. const clang::InitListExpr *InitList) {
  8930. unsigned totalSize = 0;
  8931. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  8932. const clang::Expr *EltInit = InitList->getInit(i);
  8933. QualType EltInitTy = EltInit->getType();
  8934. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  8935. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  8936. } else {
  8937. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  8938. }
  8939. }
  8940. return totalSize;
  8941. }
  8942. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  8943. _In_ clang::Sema* sema,
  8944. _In_ const clang::InitListExpr *InitList,
  8945. _In_ const clang::QualType EltTy) {
  8946. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  8947. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  8948. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  8949. if (totalSize > 0 && (totalSize % eltSize)==0) {
  8950. return totalSize / eltSize;
  8951. } else {
  8952. return 0;
  8953. }
  8954. }
  8955. bool hlsl::IsConversionToLessOrEqualElements(
  8956. _In_ clang::Sema* self,
  8957. const clang::ExprResult& sourceExpr,
  8958. const clang::QualType& targetType,
  8959. bool explicitConversion)
  8960. {
  8961. return HLSLExternalSource::FromSema(self)
  8962. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  8963. }
  8964. ExprResult hlsl::LookupMatrixMemberExprForHLSL(
  8965. Sema* self,
  8966. Expr& BaseExpr,
  8967. DeclarationName MemberName,
  8968. bool IsArrow,
  8969. SourceLocation OpLoc,
  8970. SourceLocation MemberLoc)
  8971. {
  8972. return HLSLExternalSource::FromSema(self)
  8973. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  8974. }
  8975. ExprResult hlsl::LookupVectorMemberExprForHLSL(
  8976. Sema* self,
  8977. Expr& BaseExpr,
  8978. DeclarationName MemberName,
  8979. bool IsArrow,
  8980. SourceLocation OpLoc,
  8981. SourceLocation MemberLoc)
  8982. {
  8983. return HLSLExternalSource::FromSema(self)
  8984. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  8985. }
  8986. ExprResult hlsl::LookupArrayMemberExprForHLSL(
  8987. Sema* self,
  8988. Expr& BaseExpr,
  8989. DeclarationName MemberName,
  8990. bool IsArrow,
  8991. SourceLocation OpLoc,
  8992. SourceLocation MemberLoc)
  8993. {
  8994. return HLSLExternalSource::FromSema(self)
  8995. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  8996. }
  8997. bool hlsl::LookupRecordMemberExprForHLSL(
  8998. Sema* self,
  8999. Expr& BaseExpr,
  9000. DeclarationName MemberName,
  9001. bool IsArrow,
  9002. SourceLocation OpLoc,
  9003. SourceLocation MemberLoc,
  9004. ExprResult &result)
  9005. {
  9006. HLSLExternalSource *source = HLSLExternalSource::FromSema(self);
  9007. switch (source->GetTypeObjectKind(BaseExpr.getType())) {
  9008. case AR_TOBJ_MATRIX:
  9009. result = source->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9010. return true;
  9011. case AR_TOBJ_VECTOR:
  9012. result = source->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9013. return true;
  9014. case AR_TOBJ_ARRAY:
  9015. result = source->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9016. return true;
  9017. default:
  9018. return false;
  9019. }
  9020. return false;
  9021. }
  9022. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  9023. _In_ clang::Sema* self,
  9024. _In_ clang::Expr* E)
  9025. {
  9026. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  9027. }
  9028. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  9029. QualType DestType,
  9030. Sema::CheckedConversionKind CCK,
  9031. const SourceRange &OpRange, unsigned &msg,
  9032. CastKind &Kind, CXXCastPath &BasePath,
  9033. bool ListInitialization,
  9034. bool SuppressDiagnostics,
  9035. _Inout_opt_ StandardConversionSequence* standard)
  9036. {
  9037. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  9038. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  9039. SuppressDiagnostics, SuppressDiagnostics, standard);
  9040. }
  9041. clang::ExprResult hlsl::PerformHLSLConversion(
  9042. _In_ clang::Sema* self,
  9043. _In_ clang::Expr* From,
  9044. _In_ clang::QualType targetType,
  9045. _In_ const clang::StandardConversionSequence &SCS,
  9046. _In_ clang::Sema::CheckedConversionKind CCK)
  9047. {
  9048. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  9049. }
  9050. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  9051. _In_ clang::Sema* self,
  9052. _In_ clang::Expr* SrcExpr,
  9053. clang::QualType DestType)
  9054. {
  9055. return HLSLExternalSource::FromSema(self)
  9056. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  9057. }
  9058. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  9059. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  9060. {
  9061. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  9062. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  9063. if (hlslSource->Initialize(context)) {
  9064. context.setExternalSource(externalSource);
  9065. }
  9066. }
  9067. ////////////////////////////////////////////////////////////////////////////////
  9068. // FlattenedTypeIterator implementation //
  9069. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  9070. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  9071. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9072. {
  9073. if (pushTrackerForType(type, nullptr)) {
  9074. while (!m_typeTrackers.empty() && !considerLeaf())
  9075. consumeLeaf();
  9076. }
  9077. }
  9078. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  9079. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  9080. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9081. {
  9082. if (!args.empty()) {
  9083. MultiExprArg::iterator ii = args.begin();
  9084. MultiExprArg::iterator ie = args.end();
  9085. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  9086. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9087. if (!considerLeaf()) {
  9088. m_typeTrackers.clear();
  9089. }
  9090. }
  9091. }
  9092. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  9093. QualType FlattenedTypeIterator::getCurrentElement() const
  9094. {
  9095. return m_typeTrackers.back().Type;
  9096. }
  9097. /// <summary>Get the number of repeated current elements.</summary>
  9098. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  9099. {
  9100. const FlattenedTypeTracker& back = m_typeTrackers.back();
  9101. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  9102. }
  9103. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  9104. bool FlattenedTypeIterator::hasCurrentElement() const
  9105. {
  9106. return m_typeTrackers.size() > 0;
  9107. }
  9108. /// <summary>Consumes count elements on this iterator.</summary>
  9109. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  9110. {
  9111. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9112. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  9113. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9114. if (tracker.IterKind == FK_IncompleteArray)
  9115. {
  9116. tracker.Count += count;
  9117. m_springLoaded = true;
  9118. }
  9119. else
  9120. {
  9121. tracker.Count -= count;
  9122. m_springLoaded = false;
  9123. if (m_typeTrackers.back().Count == 0)
  9124. {
  9125. advanceLeafTracker();
  9126. }
  9127. }
  9128. }
  9129. unsigned int FlattenedTypeIterator::countRemaining()
  9130. {
  9131. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  9132. size_t result = 0;
  9133. while (hasCurrentElement() && !m_springLoaded)
  9134. {
  9135. size_t pending = getCurrentElementSize();
  9136. result += pending;
  9137. advanceCurrentElement(pending);
  9138. }
  9139. return result;
  9140. }
  9141. void FlattenedTypeIterator::advanceLeafTracker()
  9142. {
  9143. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9144. for (;;)
  9145. {
  9146. consumeLeaf();
  9147. if (m_typeTrackers.empty()) {
  9148. return;
  9149. }
  9150. if (considerLeaf()) {
  9151. return;
  9152. }
  9153. }
  9154. }
  9155. bool FlattenedTypeIterator::considerLeaf()
  9156. {
  9157. if (m_typeTrackers.empty()) {
  9158. return false;
  9159. }
  9160. m_typeDepth++;
  9161. if (m_typeDepth > MaxTypeDepth) {
  9162. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  9163. m_typeTrackers.clear();
  9164. m_typeDepth--;
  9165. return false;
  9166. }
  9167. bool result = false;
  9168. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9169. tracker.IsConsidered = true;
  9170. switch (tracker.IterKind) {
  9171. case FlattenedIterKind::FK_Expressions:
  9172. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  9173. result = considerLeaf();
  9174. }
  9175. break;
  9176. case FlattenedIterKind::FK_Fields:
  9177. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  9178. result = considerLeaf();
  9179. }
  9180. break;
  9181. case FlattenedIterKind::FK_Bases:
  9182. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  9183. result = considerLeaf();
  9184. }
  9185. break;
  9186. case FlattenedIterKind::FK_IncompleteArray:
  9187. m_springLoaded = true; // fall through.
  9188. default:
  9189. case FlattenedIterKind::FK_Simple: {
  9190. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  9191. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  9192. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT &&
  9193. objectKind != ArTypeObjectKind::AR_TOBJ_STRING) {
  9194. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  9195. result = considerLeaf();
  9196. }
  9197. } else {
  9198. result = true;
  9199. }
  9200. }
  9201. }
  9202. m_typeDepth--;
  9203. return result;
  9204. }
  9205. void FlattenedTypeIterator::consumeLeaf()
  9206. {
  9207. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  9208. for (;;) {
  9209. if (m_typeTrackers.empty()) {
  9210. return;
  9211. }
  9212. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9213. // Reach a leaf which is not considered before.
  9214. // Stop here.
  9215. if (!tracker.IsConsidered) {
  9216. break;
  9217. }
  9218. switch (tracker.IterKind) {
  9219. case FlattenedIterKind::FK_Expressions:
  9220. ++tracker.CurrentExpr;
  9221. if (tracker.CurrentExpr == tracker.EndExpr) {
  9222. m_typeTrackers.pop_back();
  9223. topConsumed = false;
  9224. } else {
  9225. return;
  9226. }
  9227. break;
  9228. case FlattenedIterKind::FK_Fields:
  9229. ++tracker.CurrentField;
  9230. if (tracker.CurrentField == tracker.EndField) {
  9231. m_typeTrackers.pop_back();
  9232. topConsumed = false;
  9233. } else {
  9234. return;
  9235. }
  9236. break;
  9237. case FlattenedIterKind::FK_Bases:
  9238. ++tracker.CurrentBase;
  9239. if (tracker.CurrentBase == tracker.EndBase) {
  9240. m_typeTrackers.pop_back();
  9241. topConsumed = false;
  9242. } else {
  9243. return;
  9244. }
  9245. break;
  9246. case FlattenedIterKind::FK_IncompleteArray:
  9247. if (m_draining) {
  9248. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  9249. m_incompleteCount = tracker.Count;
  9250. m_typeTrackers.pop_back();
  9251. }
  9252. return;
  9253. default:
  9254. case FlattenedIterKind::FK_Simple: {
  9255. m_springLoaded = false;
  9256. if (!topConsumed) {
  9257. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  9258. --tracker.Count;
  9259. }
  9260. else {
  9261. topConsumed = false;
  9262. }
  9263. if (tracker.Count == 0) {
  9264. m_typeTrackers.pop_back();
  9265. } else {
  9266. return;
  9267. }
  9268. }
  9269. }
  9270. }
  9271. }
  9272. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  9273. {
  9274. Expr* e = *expression;
  9275. Stmt::StmtClass expressionClass = e->getStmtClass();
  9276. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  9277. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  9278. if (initExpr->getNumInits() == 0) {
  9279. return false;
  9280. }
  9281. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  9282. MultiExprArg::iterator ii = inits.begin();
  9283. MultiExprArg::iterator ie = inits.end();
  9284. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  9285. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9286. return true;
  9287. }
  9288. return pushTrackerForType(e->getType(), expression);
  9289. }
  9290. // TODO: improve this to provide a 'peek' at intermediate types,
  9291. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  9292. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  9293. {
  9294. if (type->isVoidType()) {
  9295. return false;
  9296. }
  9297. if (type->isFunctionType()) {
  9298. return false;
  9299. }
  9300. if (m_firstType.isNull()) {
  9301. m_firstType = type;
  9302. }
  9303. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  9304. QualType elementType;
  9305. unsigned int elementCount;
  9306. const RecordType* recordType;
  9307. RecordDecl::field_iterator fi, fe;
  9308. switch (objectKind)
  9309. {
  9310. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  9311. // TODO: handle multi-dimensional arrays
  9312. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  9313. elementCount = GetArraySize(type);
  9314. if (elementCount == 0) {
  9315. if (type->isIncompleteArrayType()) {
  9316. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  9317. return true;
  9318. }
  9319. return false;
  9320. }
  9321. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9322. elementType, elementCount, nullptr));
  9323. return true;
  9324. case ArTypeObjectKind::AR_TOBJ_BASIC:
  9325. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  9326. return true;
  9327. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  9328. recordType = type->getAsStructureType();
  9329. if (recordType == nullptr)
  9330. recordType = dyn_cast<RecordType>(type.getTypePtr());
  9331. fi = recordType->getDecl()->field_begin();
  9332. fe = recordType->getDecl()->field_end();
  9333. bool bAddTracker = false;
  9334. // Skip empty struct.
  9335. if (fi != fe) {
  9336. m_typeTrackers.push_back(
  9337. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9338. type = (*fi)->getType();
  9339. bAddTracker = true;
  9340. }
  9341. if (CXXRecordDecl *cxxRecordDecl =
  9342. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  9343. // We'll error elsewhere if the record has no definition,
  9344. // just don't attempt to use it.
  9345. if (cxxRecordDecl->hasDefinition()) {
  9346. CXXRecordDecl::base_class_iterator bi, be;
  9347. bi = cxxRecordDecl->bases_begin();
  9348. be = cxxRecordDecl->bases_end();
  9349. if (bi != be) {
  9350. // Add type tracker for base.
  9351. // Add base after child to make sure base considered first.
  9352. m_typeTrackers.push_back(
  9353. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  9354. bAddTracker = true;
  9355. }
  9356. }
  9357. }
  9358. return bAddTracker;
  9359. }
  9360. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  9361. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9362. m_source.GetMatrixOrVectorElementType(type),
  9363. GetElementCount(type), nullptr));
  9364. return true;
  9365. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  9366. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9367. m_source.GetMatrixOrVectorElementType(type),
  9368. GetHLSLVecSize(type), nullptr));
  9369. return true;
  9370. case ArTypeObjectKind::AR_TOBJ_OBJECT: {
  9371. if (m_source.IsSubobjectType(type)) {
  9372. // subobjects are initialized with initialization lists
  9373. recordType = type->getAsStructureType();
  9374. fi = recordType->getDecl()->field_begin();
  9375. fe = recordType->getDecl()->field_end();
  9376. m_typeTrackers.push_back(
  9377. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9378. return true;
  9379. }
  9380. else {
  9381. // Object have no sub-types.
  9382. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9383. type.getCanonicalType(), 1, expression));
  9384. return true;
  9385. }
  9386. }
  9387. case ArTypeObjectKind::AR_TOBJ_STRING: {
  9388. // Strings have no sub-types.
  9389. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9390. type.getCanonicalType(), 1, expression));
  9391. return true;
  9392. }
  9393. default:
  9394. DXASSERT(false, "unreachable");
  9395. return false;
  9396. }
  9397. }
  9398. FlattenedTypeIterator::ComparisonResult
  9399. FlattenedTypeIterator::CompareIterators(
  9400. HLSLExternalSource& source,
  9401. SourceLocation loc,
  9402. FlattenedTypeIterator& leftIter,
  9403. FlattenedTypeIterator& rightIter)
  9404. {
  9405. FlattenedTypeIterator::ComparisonResult result;
  9406. result.LeftCount = 0;
  9407. result.RightCount = 0;
  9408. result.AreElementsEqual = true; // Until proven otherwise.
  9409. result.CanConvertElements = true; // Until proven otherwise.
  9410. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  9411. {
  9412. Expr* actualExpr = rightIter.getExprOrNull();
  9413. bool hasExpr = actualExpr != nullptr;
  9414. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  9415. StandardConversionSequence standard;
  9416. ExprResult convertedExpr;
  9417. if (!source.CanConvert(loc,
  9418. hasExpr ? actualExpr : &scratchExpr,
  9419. leftIter.getCurrentElement(),
  9420. ExplicitConversionFalse,
  9421. nullptr,
  9422. &standard)) {
  9423. result.AreElementsEqual = false;
  9424. result.CanConvertElements = false;
  9425. break;
  9426. }
  9427. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  9428. {
  9429. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  9430. leftIter.getCurrentElement(),
  9431. standard,
  9432. Sema::AA_Casting,
  9433. Sema::CCK_ImplicitConversion);
  9434. }
  9435. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  9436. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  9437. {
  9438. result.AreElementsEqual = false;
  9439. }
  9440. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  9441. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  9442. // If we need to apply conversions to the expressions, then advance a single element.
  9443. if (hasExpr && convertedExpr.isUsable()) {
  9444. rightIter.replaceExpr(convertedExpr.get());
  9445. advance = 1;
  9446. }
  9447. leftIter.advanceCurrentElement(advance);
  9448. rightIter.advanceCurrentElement(advance);
  9449. result.LeftCount += advance;
  9450. result.RightCount += advance;
  9451. }
  9452. result.LeftCount += leftIter.countRemaining();
  9453. result.RightCount += rightIter.countRemaining();
  9454. return result;
  9455. }
  9456. FlattenedTypeIterator::ComparisonResult
  9457. FlattenedTypeIterator::CompareTypes(
  9458. HLSLExternalSource& source,
  9459. SourceLocation leftLoc, SourceLocation rightLoc,
  9460. QualType left, QualType right)
  9461. {
  9462. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9463. FlattenedTypeIterator rightIter(rightLoc, right, source);
  9464. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9465. }
  9466. FlattenedTypeIterator::ComparisonResult
  9467. FlattenedTypeIterator::CompareTypesForInit(
  9468. HLSLExternalSource& source, QualType left, MultiExprArg args,
  9469. SourceLocation leftLoc, SourceLocation rightLoc)
  9470. {
  9471. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9472. FlattenedTypeIterator rightIter(rightLoc, args, source);
  9473. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9474. }
  9475. ////////////////////////////////////////////////////////////////////////////////
  9476. // Attribute processing support. //
  9477. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  9478. {
  9479. int64_t value = 0;
  9480. if (Attr.getNumArgs() > index)
  9481. {
  9482. Expr *E = nullptr;
  9483. if (!Attr.isArgExpr(index)) {
  9484. // For case arg is constant variable.
  9485. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  9486. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  9487. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  9488. Sema::LookupNameKind::LookupOrdinaryName));
  9489. if (!decl) {
  9490. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9491. return value;
  9492. }
  9493. Expr *init = decl->getInit();
  9494. if (!init) {
  9495. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9496. return value;
  9497. }
  9498. E = init;
  9499. } else
  9500. E = Attr.getArgAsExpr(index);
  9501. clang::APValue ArgNum;
  9502. bool displayError = false;
  9503. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  9504. {
  9505. displayError = true;
  9506. }
  9507. else
  9508. {
  9509. if (ArgNum.isInt())
  9510. {
  9511. value = ArgNum.getInt().getSExtValue();
  9512. }
  9513. else if (ArgNum.isFloat())
  9514. {
  9515. llvm::APSInt floatInt;
  9516. bool isPrecise;
  9517. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  9518. {
  9519. value = floatInt.getSExtValue();
  9520. }
  9521. else
  9522. {
  9523. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9524. }
  9525. }
  9526. else
  9527. {
  9528. displayError = true;
  9529. }
  9530. if (value < 0)
  9531. {
  9532. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9533. }
  9534. }
  9535. if (displayError)
  9536. {
  9537. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  9538. << Attr.getName() << AANT_ArgumentIntegerConstant
  9539. << E->getSourceRange();
  9540. }
  9541. }
  9542. return (int)value;
  9543. }
  9544. // TODO: support float arg directly.
  9545. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  9546. unsigned index = 0) {
  9547. int value = 0;
  9548. if (Attr.getNumArgs() > index) {
  9549. Expr *E = Attr.getArgAsExpr(index);
  9550. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  9551. llvm::APFloat flV = FL->getValue();
  9552. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  9553. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  9554. value = intV.getLimitedValue();
  9555. } else {
  9556. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  9557. value = intV.getLimitedValue();
  9558. }
  9559. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  9560. llvm::APInt intV =
  9561. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  9562. value = intV.getLimitedValue();
  9563. } else {
  9564. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  9565. << Attr.getName();
  9566. }
  9567. }
  9568. return value;
  9569. }
  9570. static Stmt* IgnoreParensAndDecay(Stmt* S)
  9571. {
  9572. for (;;)
  9573. {
  9574. switch (S->getStmtClass())
  9575. {
  9576. case Stmt::ParenExprClass:
  9577. S = cast<ParenExpr>(S)->getSubExpr();
  9578. break;
  9579. case Stmt::ImplicitCastExprClass:
  9580. {
  9581. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  9582. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  9583. castExpr->getCastKind() != CK_NoOp &&
  9584. castExpr->getCastKind() != CK_LValueToRValue)
  9585. {
  9586. return S;
  9587. }
  9588. S = castExpr->getSubExpr();
  9589. }
  9590. break;
  9591. default:
  9592. return S;
  9593. }
  9594. }
  9595. }
  9596. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  9597. {
  9598. DXASSERT_NOMSG(E != nullptr);
  9599. Expr* subscriptExpr = E->getIdx();
  9600. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  9601. if (subscriptExpr == nullptr ||
  9602. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  9603. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  9604. {
  9605. S.Diag(
  9606. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  9607. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  9608. return nullptr;
  9609. }
  9610. return E->getBase();
  9611. }
  9612. static bool IsValidClipPlaneDecl(Decl* D)
  9613. {
  9614. Decl::Kind kind = D->getKind();
  9615. if (kind == Decl::Var)
  9616. {
  9617. VarDecl* varDecl = cast<VarDecl>(D);
  9618. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  9619. varDecl->getType().isConstQualified())
  9620. {
  9621. return false;
  9622. }
  9623. return true;
  9624. }
  9625. else if (kind == Decl::Field)
  9626. {
  9627. return true;
  9628. }
  9629. return false;
  9630. }
  9631. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  9632. {
  9633. Stmt* cursor = E;
  9634. // clip plane expressions are a linear path, so no need to traverse the tree here.
  9635. while (cursor != nullptr)
  9636. {
  9637. bool supported = true;
  9638. cursor = IgnoreParensAndDecay(cursor);
  9639. switch (cursor->getStmtClass())
  9640. {
  9641. case Stmt::ArraySubscriptExprClass:
  9642. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  9643. if (cursor == nullptr)
  9644. {
  9645. // nullptr indicates failure, and the error message has already been printed out
  9646. return nullptr;
  9647. }
  9648. break;
  9649. case Stmt::DeclRefExprClass:
  9650. {
  9651. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  9652. Decl* decl = declRef->getDecl();
  9653. supported = IsValidClipPlaneDecl(decl);
  9654. cursor = supported ? nullptr : cursor;
  9655. }
  9656. break;
  9657. case Stmt::MemberExprClass:
  9658. {
  9659. MemberExpr* member = cast<MemberExpr>(cursor);
  9660. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  9661. cursor = supported ? member->getBase() : cursor;
  9662. }
  9663. break;
  9664. default:
  9665. supported = false;
  9666. break;
  9667. }
  9668. if (!supported)
  9669. {
  9670. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  9671. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  9672. return nullptr;
  9673. }
  9674. }
  9675. // Validate that the type is a float4.
  9676. QualType expressionType = E->getType();
  9677. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  9678. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  9679. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  9680. {
  9681. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  9682. return nullptr;
  9683. }
  9684. return E;
  9685. }
  9686. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  9687. {
  9688. Expr* clipExprs[6];
  9689. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  9690. {
  9691. if (A.getNumArgs() <= index)
  9692. {
  9693. clipExprs[index] = nullptr;
  9694. continue;
  9695. }
  9696. Expr *E = A.getArgAsExpr(index);
  9697. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  9698. }
  9699. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  9700. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  9701. A.getAttributeSpellingListIndex());
  9702. }
  9703. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  9704. {
  9705. int argValue = ValidateAttributeIntArg(S, Attr);
  9706. // Default value is 0 (full unroll).
  9707. if (Attr.getNumArgs() == 0) argValue = 0;
  9708. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  9709. argValue, Attr.getAttributeSpellingListIndex());
  9710. }
  9711. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  9712. {
  9713. Stmt::StmtClass stClass = St->getStmtClass();
  9714. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  9715. {
  9716. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9717. << Attr.getName();
  9718. }
  9719. }
  9720. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  9721. {
  9722. Stmt::StmtClass stClass = St->getStmtClass();
  9723. if (stClass != Stmt::SwitchStmtClass)
  9724. {
  9725. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9726. << Attr.getName();
  9727. }
  9728. }
  9729. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  9730. {
  9731. Stmt::StmtClass stClass = St->getStmtClass();
  9732. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  9733. {
  9734. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9735. << Attr.getName();
  9736. }
  9737. }
  9738. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  9739. {
  9740. // values is an optional comma-separated list of potential values.
  9741. if (A.getNumArgs() <= index)
  9742. return StringRef();
  9743. Expr* E = A.getArgAsExpr(index);
  9744. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  9745. {
  9746. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  9747. << A.getName();
  9748. return StringRef();
  9749. }
  9750. StringLiteral* sl = cast<StringLiteral>(E);
  9751. StringRef result = sl->getString();
  9752. // Return result with no additional validation.
  9753. if (values == nullptr)
  9754. {
  9755. return result;
  9756. }
  9757. const char* value = values;
  9758. while (*value != '\0')
  9759. {
  9760. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  9761. // Look for a match.
  9762. const char* argData = result.data();
  9763. size_t argDataLen = result.size();
  9764. while (argDataLen != 0 && *argData == *value && *value)
  9765. {
  9766. ++argData;
  9767. ++value;
  9768. --argDataLen;
  9769. }
  9770. // Match found if every input character matched.
  9771. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  9772. {
  9773. return result;
  9774. }
  9775. // Move to next separator.
  9776. while (*value != '\0' && *value != ',')
  9777. {
  9778. ++value;
  9779. }
  9780. // Move to the start of the next item if any.
  9781. if (*value == ',') value++;
  9782. }
  9783. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  9784. // No match found.
  9785. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  9786. << A.getName() << values;
  9787. return StringRef();
  9788. }
  9789. static
  9790. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  9791. {
  9792. if (D->isFunctionOrFunctionTemplate())
  9793. {
  9794. return true;
  9795. }
  9796. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  9797. return false;
  9798. }
  9799. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  9800. {
  9801. DXASSERT_NOMSG(D != nullptr);
  9802. DXASSERT_NOMSG(!A.isInvalid());
  9803. Attr* declAttr = nullptr;
  9804. Handled = true;
  9805. switch (A.getKind())
  9806. {
  9807. case AttributeList::AT_HLSLIn:
  9808. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  9809. A.getAttributeSpellingListIndex());
  9810. break;
  9811. case AttributeList::AT_HLSLOut:
  9812. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  9813. A.getAttributeSpellingListIndex());
  9814. break;
  9815. case AttributeList::AT_HLSLInOut:
  9816. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  9817. A.getAttributeSpellingListIndex());
  9818. break;
  9819. case AttributeList::AT_HLSLNoInterpolation:
  9820. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  9821. A.getAttributeSpellingListIndex());
  9822. break;
  9823. case AttributeList::AT_HLSLLinear:
  9824. case AttributeList::AT_HLSLCenter:
  9825. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  9826. A.getAttributeSpellingListIndex());
  9827. break;
  9828. case AttributeList::AT_HLSLNoPerspective:
  9829. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  9830. A.getAttributeSpellingListIndex());
  9831. break;
  9832. case AttributeList::AT_HLSLSample:
  9833. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  9834. A.getAttributeSpellingListIndex());
  9835. break;
  9836. case AttributeList::AT_HLSLCentroid:
  9837. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  9838. A.getAttributeSpellingListIndex());
  9839. break;
  9840. case AttributeList::AT_HLSLPrecise:
  9841. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  9842. A.getAttributeSpellingListIndex());
  9843. break;
  9844. case AttributeList::AT_HLSLShared:
  9845. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  9846. A.getAttributeSpellingListIndex());
  9847. break;
  9848. case AttributeList::AT_HLSLGroupShared:
  9849. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  9850. A.getAttributeSpellingListIndex());
  9851. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  9852. VD->setType(S.Context.getAddrSpaceQualType(VD->getType(), DXIL::kTGSMAddrSpace));
  9853. }
  9854. break;
  9855. case AttributeList::AT_HLSLUniform:
  9856. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  9857. A.getAttributeSpellingListIndex());
  9858. break;
  9859. case AttributeList::AT_HLSLColumnMajor:
  9860. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  9861. A.getAttributeSpellingListIndex());
  9862. break;
  9863. case AttributeList::AT_HLSLRowMajor:
  9864. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  9865. A.getAttributeSpellingListIndex());
  9866. break;
  9867. case AttributeList::AT_HLSLUnorm:
  9868. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  9869. A.getAttributeSpellingListIndex());
  9870. break;
  9871. case AttributeList::AT_HLSLSnorm:
  9872. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  9873. A.getAttributeSpellingListIndex());
  9874. break;
  9875. case AttributeList::AT_HLSLPoint:
  9876. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  9877. A.getAttributeSpellingListIndex());
  9878. break;
  9879. case AttributeList::AT_HLSLLine:
  9880. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  9881. A.getAttributeSpellingListIndex());
  9882. break;
  9883. case AttributeList::AT_HLSLLineAdj:
  9884. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  9885. A.getAttributeSpellingListIndex());
  9886. break;
  9887. case AttributeList::AT_HLSLTriangle:
  9888. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  9889. A.getAttributeSpellingListIndex());
  9890. break;
  9891. case AttributeList::AT_HLSLTriangleAdj:
  9892. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  9893. A.getAttributeSpellingListIndex());
  9894. break;
  9895. case AttributeList::AT_HLSLGloballyCoherent:
  9896. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  9897. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9898. break;
  9899. case AttributeList::AT_HLSLIndices:
  9900. declAttr = ::new (S.Context) HLSLIndicesAttr(
  9901. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9902. break;
  9903. case AttributeList::AT_HLSLVertices:
  9904. declAttr = ::new (S.Context) HLSLVerticesAttr(
  9905. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9906. break;
  9907. case AttributeList::AT_HLSLPrimitives:
  9908. declAttr = ::new (S.Context) HLSLPrimitivesAttr(
  9909. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9910. break;
  9911. case AttributeList::AT_HLSLPayload:
  9912. declAttr = ::new (S.Context) HLSLPayloadAttr(
  9913. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9914. break;
  9915. default:
  9916. Handled = false;
  9917. break;
  9918. }
  9919. if (declAttr != nullptr)
  9920. {
  9921. DXASSERT_NOMSG(Handled);
  9922. D->addAttr(declAttr);
  9923. return;
  9924. }
  9925. Handled = true;
  9926. switch (A.getKind())
  9927. {
  9928. // These apply to statements, not declarations. The warning messages clarify this properly.
  9929. case AttributeList::AT_HLSLUnroll:
  9930. case AttributeList::AT_HLSLAllowUAVCondition:
  9931. case AttributeList::AT_HLSLLoop:
  9932. case AttributeList::AT_HLSLFastOpt:
  9933. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9934. << A.getName();
  9935. return;
  9936. case AttributeList::AT_HLSLBranch:
  9937. case AttributeList::AT_HLSLFlatten:
  9938. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9939. << A.getName();
  9940. return;
  9941. case AttributeList::AT_HLSLForceCase:
  9942. case AttributeList::AT_HLSLCall:
  9943. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9944. << A.getName();
  9945. return;
  9946. // These are the cases that actually apply to declarations.
  9947. case AttributeList::AT_HLSLClipPlanes:
  9948. declAttr = HandleClipPlanes(S, A);
  9949. break;
  9950. case AttributeList::AT_HLSLDomain:
  9951. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  9952. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  9953. break;
  9954. case AttributeList::AT_HLSLEarlyDepthStencil:
  9955. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9956. break;
  9957. case AttributeList::AT_HLSLInstance:
  9958. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  9959. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9960. break;
  9961. case AttributeList::AT_HLSLMaxTessFactor:
  9962. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  9963. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  9964. break;
  9965. case AttributeList::AT_HLSLNumThreads:
  9966. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  9967. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  9968. A.getAttributeSpellingListIndex());
  9969. break;
  9970. case AttributeList::AT_HLSLRootSignature:
  9971. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  9972. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  9973. A.getAttributeSpellingListIndex());
  9974. break;
  9975. case AttributeList::AT_HLSLOutputControlPoints:
  9976. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  9977. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9978. break;
  9979. case AttributeList::AT_HLSLOutputTopology:
  9980. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  9981. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  9982. break;
  9983. case AttributeList::AT_HLSLPartitioning:
  9984. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  9985. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  9986. break;
  9987. case AttributeList::AT_HLSLPatchConstantFunc:
  9988. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  9989. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  9990. break;
  9991. case AttributeList::AT_HLSLShader:
  9992. declAttr = ::new (S.Context) HLSLShaderAttr(
  9993. A.getRange(), S.Context,
  9994. ValidateAttributeStringArg(
  9995. S, A,
  9996. "compute,vertex,pixel,hull,domain,geometry,raygeneration,"
  9997. "intersection,anyhit,closesthit,miss,callable,mesh,amplification"),
  9998. A.getAttributeSpellingListIndex());
  9999. break;
  10000. case AttributeList::AT_HLSLMaxVertexCount:
  10001. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  10002. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10003. break;
  10004. case AttributeList::AT_HLSLExperimental:
  10005. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  10006. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  10007. A.getAttributeSpellingListIndex());
  10008. break;
  10009. case AttributeList::AT_NoInline:
  10010. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10011. break;
  10012. case AttributeList::AT_HLSLExport:
  10013. declAttr = ::new (S.Context) HLSLExportAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10014. break;
  10015. case AttributeList::AT_HLSLWaveSensitive:
  10016. declAttr = ::new (S.Context) HLSLWaveSensitiveAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10017. break;
  10018. default:
  10019. Handled = false;
  10020. break; // SPIRV Change: was return;
  10021. }
  10022. if (declAttr != nullptr)
  10023. {
  10024. DXASSERT_NOMSG(Handled);
  10025. D->addAttr(declAttr);
  10026. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  10027. // and prevent code generation.
  10028. ValidateAttributeTargetIsFunction(S, D, A);
  10029. return; // SPIRV Change
  10030. }
  10031. // SPIRV Change Starts
  10032. Handled = true;
  10033. switch (A.getKind())
  10034. {
  10035. case AttributeList::AT_VKBuiltIn:
  10036. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  10037. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation,BaseVertex,BaseInstance,DrawIndex,DeviceIndex,ViewportMaskNV"),
  10038. A.getAttributeSpellingListIndex());
  10039. break;
  10040. case AttributeList::AT_VKLocation:
  10041. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  10042. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10043. break;
  10044. case AttributeList::AT_VKIndex:
  10045. declAttr = ::new (S.Context) VKIndexAttr(A.getRange(), S.Context,
  10046. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10047. break;
  10048. case AttributeList::AT_VKBinding:
  10049. declAttr = ::new (S.Context) VKBindingAttr(
  10050. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10051. A.getNumArgs() < 2 ? INT_MIN : ValidateAttributeIntArg(S, A, 1),
  10052. A.getAttributeSpellingListIndex());
  10053. break;
  10054. case AttributeList::AT_VKCounterBinding:
  10055. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  10056. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10057. break;
  10058. case AttributeList::AT_VKPushConstant:
  10059. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  10060. A.getAttributeSpellingListIndex());
  10061. break;
  10062. case AttributeList::AT_VKOffset:
  10063. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  10064. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10065. break;
  10066. case AttributeList::AT_VKInputAttachmentIndex:
  10067. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  10068. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10069. A.getAttributeSpellingListIndex());
  10070. break;
  10071. case AttributeList::AT_VKConstantId:
  10072. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  10073. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10074. break;
  10075. case AttributeList::AT_VKPostDepthCoverage:
  10076. declAttr = ::new (S.Context) VKPostDepthCoverageAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10077. break;
  10078. case AttributeList::AT_VKShaderRecordNV:
  10079. declAttr = ::new (S.Context) VKShaderRecordNVAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10080. break;
  10081. default:
  10082. Handled = false;
  10083. return;
  10084. }
  10085. if (declAttr != nullptr)
  10086. {
  10087. DXASSERT_NOMSG(Handled);
  10088. D->addAttr(declAttr);
  10089. }
  10090. // SPIRV Change Ends
  10091. }
  10092. /// <summary>Processes an attribute for a statement.</summary>
  10093. /// <param name="S">Sema with context.</param>
  10094. /// <param name="St">Statement annotated.</param>
  10095. /// <param name="A">Single parsed attribute to process.</param>
  10096. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  10097. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  10098. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  10099. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  10100. {
  10101. // | Construct | Allowed Attributes |
  10102. // +------------------+--------------------------------------------+
  10103. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  10104. // | if | branch, flatten |
  10105. // | switch | branch, flatten, forcecase, call |
  10106. Attr * result = nullptr;
  10107. Handled = true;
  10108. switch (A.getKind())
  10109. {
  10110. case AttributeList::AT_HLSLUnroll:
  10111. ValidateAttributeOnLoop(S, St, A);
  10112. result = HandleUnrollAttribute(S, A);
  10113. break;
  10114. case AttributeList::AT_HLSLAllowUAVCondition:
  10115. ValidateAttributeOnLoop(S, St, A);
  10116. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  10117. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10118. break;
  10119. case AttributeList::AT_HLSLLoop:
  10120. ValidateAttributeOnLoop(S, St, A);
  10121. result = ::new (S.Context) HLSLLoopAttr(
  10122. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10123. break;
  10124. case AttributeList::AT_HLSLFastOpt:
  10125. ValidateAttributeOnLoop(S, St, A);
  10126. result = ::new (S.Context) HLSLFastOptAttr(
  10127. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10128. break;
  10129. case AttributeList::AT_HLSLBranch:
  10130. ValidateAttributeOnSwitchOrIf(S, St, A);
  10131. result = ::new (S.Context) HLSLBranchAttr(
  10132. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10133. break;
  10134. case AttributeList::AT_HLSLFlatten:
  10135. ValidateAttributeOnSwitchOrIf(S, St, A);
  10136. result = ::new (S.Context) HLSLFlattenAttr(
  10137. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10138. break;
  10139. case AttributeList::AT_HLSLForceCase:
  10140. ValidateAttributeOnSwitch(S, St, A);
  10141. result = ::new (S.Context) HLSLForceCaseAttr(
  10142. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10143. break;
  10144. case AttributeList::AT_HLSLCall:
  10145. ValidateAttributeOnSwitch(S, St, A);
  10146. result = ::new (S.Context) HLSLCallAttr(
  10147. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10148. break;
  10149. default:
  10150. Handled = false;
  10151. break;
  10152. }
  10153. return result;
  10154. }
  10155. ////////////////////////////////////////////////////////////////////////////////
  10156. // Implementation of Sema members. //
  10157. Decl* Sema::ActOnStartHLSLBuffer(
  10158. Scope* bufferScope,
  10159. bool cbuffer, SourceLocation KwLoc,
  10160. IdentifierInfo *Ident, SourceLocation IdentLoc,
  10161. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  10162. SourceLocation LBrace)
  10163. {
  10164. // For anonymous namespace, take the location of the left brace.
  10165. DeclContext* lexicalParent = getCurLexicalContext();
  10166. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10167. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  10168. Ident, IdentLoc, BufferAttributes, LBrace);
  10169. // Keep track of the currently active buffer.
  10170. HLSLBuffers.push_back(result);
  10171. // Validate unusual annotations and emit diagnostics.
  10172. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  10173. auto && unusualIter = BufferAttributes.begin();
  10174. auto && unusualEnd = BufferAttributes.end();
  10175. char expectedRegisterType = cbuffer ? 'b' : 't';
  10176. for (; unusualIter != unusualEnd; ++unusualIter) {
  10177. switch ((*unusualIter)->getKind()) {
  10178. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10179. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  10180. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  10181. break;
  10182. }
  10183. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10184. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  10185. if (registerAssignment->isSpaceOnly())
  10186. continue;
  10187. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  10188. Diag(registerAssignment->Loc, diag::err_hlsl_incorrect_bind_semantic) << (cbuffer ? "'b'" : "'t'");
  10189. } else if (registerAssignment->ShaderProfile.size() > 0) {
  10190. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  10191. }
  10192. break;
  10193. }
  10194. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10195. // Ignore semantic declarations.
  10196. break;
  10197. }
  10198. }
  10199. }
  10200. PushOnScopeChains(result, bufferScope);
  10201. PushDeclContext(bufferScope, result);
  10202. ActOnDocumentableDecl(result);
  10203. return result;
  10204. }
  10205. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  10206. {
  10207. DXASSERT_NOMSG(Dcl != nullptr);
  10208. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10209. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  10210. HLSLBuffers.pop_back();
  10211. PopDeclContext();
  10212. }
  10213. Decl* Sema::getActiveHLSLBuffer() const
  10214. {
  10215. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  10216. }
  10217. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  10218. DeclGroupPtrTy &dcl, bool iscbuf) {
  10219. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10220. HLSLBuffers.pop_back();
  10221. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10222. Decl *decl = dcl.get().getSingleDecl();
  10223. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  10224. IdentifierInfo *Ident = namedDecl->getIdentifier();
  10225. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  10226. SourceLocation Loc = decl->getLocation();
  10227. // Prevent array type in template. The only way to specify an array in the template type
  10228. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  10229. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  10230. QualType declType = cast<VarDecl>(namedDecl)->getType();
  10231. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  10232. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  10233. declType = arrayType->getElementType();
  10234. }
  10235. // Check to make that sure only structs are allowed as parameter types for
  10236. // ConstantBuffer and TextureBuffer.
  10237. if (!declType->isStructureType()) {
  10238. Diag(decl->getLocStart(),
  10239. diag::err_hlsl_typeintemplateargument_requires_struct)
  10240. << declType;
  10241. return nullptr;
  10242. }
  10243. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  10244. DeclContext *lexicalParent = getCurLexicalContext();
  10245. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10246. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  10247. KwLoc, Ident, Loc, hlslAttrs, Loc);
  10248. // set relation
  10249. namedDecl->setDeclContext(result);
  10250. result->addDecl(namedDecl);
  10251. // move attribute from constant to constant buffer
  10252. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  10253. namedDecl->setUnusualAnnotations(hlslAttrs);
  10254. return result;
  10255. }
  10256. bool Sema::IsOnHLSLBufferView() {
  10257. // nullptr will not pushed for cbuffer.
  10258. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  10259. }
  10260. void Sema::ActOnStartHLSLBufferView() {
  10261. // Push nullptr to mark HLSLBufferView.
  10262. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10263. HLSLBuffers.emplace_back(nullptr);
  10264. }
  10265. HLSLBufferDecl::HLSLBufferDecl(
  10266. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  10267. IdentifierInfo *Id, SourceLocation IdLoc,
  10268. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10269. SourceLocation LBrace)
  10270. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  10271. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  10272. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  10273. if (!BufferAttributes.empty()) {
  10274. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10275. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  10276. }
  10277. }
  10278. HLSLBufferDecl *
  10279. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  10280. bool constantbuffer, SourceLocation KwLoc,
  10281. IdentifierInfo *Id, SourceLocation IdLoc,
  10282. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10283. SourceLocation LBrace) {
  10284. DeclContext *DC = C.getTranslationUnitDecl();
  10285. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  10286. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  10287. if (DC != lexicalParent) {
  10288. result->setLexicalDeclContext(lexicalParent);
  10289. }
  10290. return result;
  10291. }
  10292. const char *HLSLBufferDecl::getDeclKindName() const {
  10293. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  10294. "ConstantBuffer"};
  10295. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  10296. return HLSLBufferNames[index];
  10297. }
  10298. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  10299. assert(NewDecl != nullptr);
  10300. if (!getLangOpts().HLSL) {
  10301. return;
  10302. }
  10303. if (!D.UnusualAnnotations.empty()) {
  10304. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10305. getASTContext(), D.UnusualAnnotations.data(),
  10306. D.UnusualAnnotations.size()));
  10307. D.UnusualAnnotations.clear();
  10308. }
  10309. }
  10310. /// Checks whether a usage attribute is compatible with those seen so far and
  10311. /// maintains history.
  10312. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  10313. bool &usageOut) {
  10314. switch (kind) {
  10315. case AttributeList::AT_HLSLIn:
  10316. if (usageIn)
  10317. return false;
  10318. usageIn = true;
  10319. break;
  10320. case AttributeList::AT_HLSLOut:
  10321. if (usageOut)
  10322. return false;
  10323. usageOut = true;
  10324. break;
  10325. default:
  10326. assert(kind == AttributeList::AT_HLSLInOut);
  10327. if (usageOut || usageIn)
  10328. return false;
  10329. usageIn = usageOut = true;
  10330. break;
  10331. }
  10332. return true;
  10333. }
  10334. // Diagnose valid/invalid modifiers for HLSL.
  10335. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC, Expr *BitWidth,
  10336. TypeSourceInfo *TInfo, bool isParameter) {
  10337. assert(getLangOpts().HLSL &&
  10338. "otherwise this is called without checking language first");
  10339. // NOTE: some tests may declare templates.
  10340. if (DC->isNamespace() || DC->isDependentContext()) return true;
  10341. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  10342. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  10343. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  10344. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  10345. bool result = true;
  10346. bool isTypedef = storage == DeclSpec::SCS_typedef;
  10347. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  10348. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  10349. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  10350. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  10351. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  10352. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  10353. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  10354. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  10355. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  10356. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  10357. // Function declarations are not allowed in parameter declaration
  10358. // TODO : Remove this check once we support function declarations/pointers in HLSL
  10359. if (isParameter && isFunction) {
  10360. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  10361. D.setInvalidType();
  10362. return false;
  10363. }
  10364. assert(
  10365. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  10366. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  10367. (isParameter ? 1 : 0))
  10368. && "exactly one type of declarator is being processed");
  10369. // qt/pType captures either the type being modified, or the return type in the
  10370. // case of a function (or method).
  10371. QualType qt = TInfo->getType();
  10372. const Type* pType = qt.getTypePtrOrNull();
  10373. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  10374. // Early checks - these are not simple attribution errors, but constructs that
  10375. // are fundamentally unsupported,
  10376. // and so we avoid errors that might indicate they can be repaired.
  10377. if (DC->isRecord()) {
  10378. unsigned int nestedDiagId = 0;
  10379. if (isTypedef) {
  10380. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  10381. }
  10382. if (isField && pType && pType->isIncompleteArrayType()) {
  10383. nestedDiagId = diag::err_hlsl_unsupported_incomplete_array;
  10384. }
  10385. if (nestedDiagId) {
  10386. Diag(D.getLocStart(), nestedDiagId);
  10387. D.setInvalidType();
  10388. return false;
  10389. }
  10390. }
  10391. // String and subobject declarations are supported only as top level global variables.
  10392. // Const and static modifiers are implied - add them if missing.
  10393. if ((hlsl::IsStringType(qt) || hlslSource->IsSubobjectType(qt)) && !D.isInvalidType()) {
  10394. // string are supported only as top level global variables
  10395. if (!DC->isTranslationUnit()) {
  10396. Diag(D.getLocStart(), diag::err_hlsl_object_not_global) << (int)hlsl::IsStringType(qt);
  10397. result = false;
  10398. }
  10399. if (isExtern) {
  10400. Diag(D.getLocStart(), diag::err_hlsl_object_extern_not_supported) << (int)hlsl::IsStringType(qt);
  10401. result = false;
  10402. }
  10403. const char *PrevSpec = nullptr;
  10404. unsigned DiagID = 0;
  10405. if (!isStatic) {
  10406. D.getMutableDeclSpec().SetStorageClassSpec(*this, DeclSpec::SCS_static, D.getLocStart(), PrevSpec, DiagID, Context.getPrintingPolicy());
  10407. isStatic = true;
  10408. }
  10409. if (!isConst) {
  10410. D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, D.getLocStart(), PrevSpec, DiagID, getLangOpts());
  10411. isConst = true;
  10412. }
  10413. }
  10414. const char* declarationType =
  10415. (isLocalVar) ? "local variable" :
  10416. (isTypedef) ? "typedef" :
  10417. (isFunction) ? "function" :
  10418. (isMethod) ? "method" :
  10419. (isGlobal) ? "global variable" :
  10420. (isParameter) ? "parameter" :
  10421. (isField) ? "field" : "<unknown>";
  10422. if (pType && D.isFunctionDeclarator()) {
  10423. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  10424. if (pFP) {
  10425. qt = pFP->getReturnType();
  10426. pType = qt.getTypePtrOrNull();
  10427. // prohibit string as a return type
  10428. if (hlsl::IsStringType(qt)) {
  10429. static const unsigned selectReturnValueIdx = 2;
  10430. Diag(D.getLocStart(), diag::err_hlsl_unsupported_string_decl) << selectReturnValueIdx;
  10431. D.setInvalidType();
  10432. }
  10433. }
  10434. }
  10435. // Check for deprecated effect object type here, warn, and invalidate decl
  10436. bool bDeprecatedEffectObject = false;
  10437. bool bIsObject = false;
  10438. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  10439. bIsObject = true;
  10440. if (bDeprecatedEffectObject) {
  10441. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  10442. D.setInvalidType();
  10443. return false;
  10444. }
  10445. // Add methods if not ready.
  10446. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  10447. } else if (qt->isArrayType()) {
  10448. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  10449. while (eltQt->isArrayType())
  10450. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  10451. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  10452. // Add methods if not ready.
  10453. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  10454. bIsObject = true;
  10455. }
  10456. }
  10457. if (isExtern) {
  10458. if (!(isFunction || isGlobal)) {
  10459. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  10460. << declarationType;
  10461. result = false;
  10462. }
  10463. }
  10464. if (isStatic) {
  10465. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  10466. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  10467. << declarationType;
  10468. result = false;
  10469. }
  10470. }
  10471. if (isVolatile) {
  10472. if (!(isLocalVar || isTypedef)) {
  10473. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  10474. << declarationType;
  10475. result = false;
  10476. }
  10477. }
  10478. if (isConst) {
  10479. if (isField && !isStatic) {
  10480. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  10481. << declarationType;
  10482. result = false;
  10483. }
  10484. }
  10485. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  10486. if (hasSignSpec) {
  10487. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  10488. // vectors or matrices can only have unsigned integer types.
  10489. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  10490. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  10491. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  10492. << g_ArBasicTypeNames[basicKind];
  10493. result = false;
  10494. }
  10495. }
  10496. else {
  10497. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  10498. result = false;
  10499. }
  10500. }
  10501. // Validate attributes
  10502. clang::AttributeList
  10503. *pUniform = nullptr,
  10504. *pUsage = nullptr,
  10505. *pNoInterpolation = nullptr,
  10506. *pLinear = nullptr,
  10507. *pNoPerspective = nullptr,
  10508. *pSample = nullptr,
  10509. *pCentroid = nullptr,
  10510. *pCenter = nullptr,
  10511. *pAnyLinear = nullptr, // first linear attribute found
  10512. *pTopology = nullptr,
  10513. *pMeshModifier = nullptr;
  10514. bool usageIn = false;
  10515. bool usageOut = false;
  10516. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  10517. pAttr != NULL; pAttr = pAttr->getNext()) {
  10518. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  10519. continue;
  10520. switch (pAttr->getKind()) {
  10521. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  10522. break;
  10523. case AttributeList::AT_HLSLShared:
  10524. if (!isGlobal) {
  10525. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10526. << pAttr->getName() << declarationType << pAttr->getRange();
  10527. result = false;
  10528. }
  10529. if (isStatic) {
  10530. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10531. << "'static'" << pAttr->getName() << declarationType
  10532. << pAttr->getRange();
  10533. result = false;
  10534. }
  10535. break;
  10536. case AttributeList::AT_HLSLGroupShared:
  10537. if (!isGlobal) {
  10538. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10539. << pAttr->getName() << declarationType << pAttr->getRange();
  10540. result = false;
  10541. }
  10542. if (isExtern) {
  10543. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10544. << "'extern'" << pAttr->getName() << declarationType
  10545. << pAttr->getRange();
  10546. result = false;
  10547. }
  10548. break;
  10549. case AttributeList::AT_HLSLGloballyCoherent:
  10550. if (!bIsObject) {
  10551. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10552. << pAttr->getName() << "non-UAV type";
  10553. result = false;
  10554. }
  10555. break;
  10556. case AttributeList::AT_HLSLUniform:
  10557. if (!(isGlobal || isParameter)) {
  10558. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10559. << pAttr->getName() << declarationType << pAttr->getRange();
  10560. result = false;
  10561. }
  10562. if (isStatic) {
  10563. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10564. << "'static'" << pAttr->getName() << declarationType
  10565. << pAttr->getRange();
  10566. result = false;
  10567. }
  10568. pUniform = pAttr;
  10569. break;
  10570. case AttributeList::AT_HLSLIn:
  10571. case AttributeList::AT_HLSLOut:
  10572. case AttributeList::AT_HLSLInOut:
  10573. if (!isParameter) {
  10574. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  10575. << pAttr->getName() << pAttr->getRange();
  10576. result = false;
  10577. }
  10578. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  10579. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  10580. << pAttr->getName() << pAttr->getRange();
  10581. result = false;
  10582. }
  10583. pUsage = pAttr;
  10584. break;
  10585. case AttributeList::AT_HLSLNoInterpolation:
  10586. if (!(isParameter || isField || isFunction)) {
  10587. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10588. << pAttr->getName() << declarationType << pAttr->getRange();
  10589. result = false;
  10590. }
  10591. if (pNoInterpolation) {
  10592. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10593. << pAttr->getName() << pAttr->getRange();
  10594. }
  10595. pNoInterpolation = pAttr;
  10596. break;
  10597. case AttributeList::AT_HLSLLinear:
  10598. case AttributeList::AT_HLSLCenter:
  10599. case AttributeList::AT_HLSLNoPerspective:
  10600. case AttributeList::AT_HLSLSample:
  10601. case AttributeList::AT_HLSLCentroid:
  10602. if (!(isParameter || isField || isFunction)) {
  10603. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10604. << pAttr->getName() << declarationType << pAttr->getRange();
  10605. result = false;
  10606. }
  10607. if (nullptr == pAnyLinear)
  10608. pAnyLinear = pAttr;
  10609. switch (pAttr->getKind()) {
  10610. case AttributeList::AT_HLSLLinear:
  10611. if (pLinear) {
  10612. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10613. << pAttr->getName() << pAttr->getRange();
  10614. }
  10615. pLinear = pAttr;
  10616. break;
  10617. case AttributeList::AT_HLSLCenter:
  10618. if (pCenter) {
  10619. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10620. << pAttr->getName() << pAttr->getRange();
  10621. }
  10622. pCenter = pAttr;
  10623. break;
  10624. case AttributeList::AT_HLSLNoPerspective:
  10625. if (pNoPerspective) {
  10626. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10627. << pAttr->getName() << pAttr->getRange();
  10628. }
  10629. pNoPerspective = pAttr;
  10630. break;
  10631. case AttributeList::AT_HLSLSample:
  10632. if (pSample) {
  10633. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10634. << pAttr->getName() << pAttr->getRange();
  10635. }
  10636. pSample = pAttr;
  10637. break;
  10638. case AttributeList::AT_HLSLCentroid:
  10639. if (pCentroid) {
  10640. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10641. << pAttr->getName() << pAttr->getRange();
  10642. }
  10643. pCentroid = pAttr;
  10644. break;
  10645. default:
  10646. // Only relevant to the four attribs included in this block.
  10647. break;
  10648. }
  10649. break;
  10650. case AttributeList::AT_HLSLPoint:
  10651. case AttributeList::AT_HLSLLine:
  10652. case AttributeList::AT_HLSLLineAdj:
  10653. case AttributeList::AT_HLSLTriangle:
  10654. case AttributeList::AT_HLSLTriangleAdj:
  10655. if (!(isParameter)) {
  10656. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10657. << pAttr->getName() << declarationType << pAttr->getRange();
  10658. result = false;
  10659. }
  10660. if (pTopology) {
  10661. if (pTopology->getKind() == pAttr->getKind()) {
  10662. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10663. << pAttr->getName() << pAttr->getRange();
  10664. } else {
  10665. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10666. << pAttr->getName() << pTopology->getName()
  10667. << declarationType << pAttr->getRange();
  10668. result = false;
  10669. }
  10670. }
  10671. pTopology = pAttr;
  10672. break;
  10673. case AttributeList::AT_HLSLExport:
  10674. if (!isFunction) {
  10675. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10676. << pAttr->getName() << declarationType << pAttr->getRange();
  10677. result = false;
  10678. }
  10679. if (isStatic) {
  10680. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10681. << "'static'" << pAttr->getName() << declarationType
  10682. << pAttr->getRange();
  10683. result = false;
  10684. }
  10685. break;
  10686. case AttributeList::AT_HLSLIndices:
  10687. case AttributeList::AT_HLSLVertices:
  10688. case AttributeList::AT_HLSLPrimitives:
  10689. case AttributeList::AT_HLSLPayload:
  10690. if (!(isParameter)) {
  10691. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10692. << pAttr->getName() << declarationType << pAttr->getRange();
  10693. result = false;
  10694. }
  10695. if (pMeshModifier) {
  10696. if (pMeshModifier->getKind() == pAttr->getKind()) {
  10697. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10698. << pAttr->getName() << pAttr->getRange();
  10699. } else {
  10700. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10701. << pAttr->getName() << pMeshModifier->getName()
  10702. << declarationType << pAttr->getRange();
  10703. result = false;
  10704. }
  10705. }
  10706. pMeshModifier = pAttr;
  10707. break;
  10708. default:
  10709. break;
  10710. }
  10711. }
  10712. if (pNoInterpolation && pAnyLinear) {
  10713. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10714. << pNoInterpolation->getName() << pAnyLinear->getName()
  10715. << declarationType << pNoInterpolation->getRange();
  10716. result = false;
  10717. }
  10718. if (pSample && pCentroid) {
  10719. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  10720. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  10721. }
  10722. if (pCenter && pCentroid) {
  10723. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  10724. << pCenter->getName() << pCentroid->getName() << pCenter->getRange();
  10725. }
  10726. if (pSample && pCenter) {
  10727. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  10728. << pCenter->getName() << pSample->getName() << pCenter->getRange();
  10729. }
  10730. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  10731. pNoInterpolation ? pNoInterpolation : pTopology);
  10732. if (pUniform && pNonUniformAttr) {
  10733. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10734. << pNonUniformAttr->getName()
  10735. << pUniform->getName() << declarationType << pUniform->getRange();
  10736. result = false;
  10737. }
  10738. if (pAnyLinear && pTopology) {
  10739. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  10740. << pTopology->getName()
  10741. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  10742. result = false;
  10743. }
  10744. if (pNoInterpolation && pTopology) {
  10745. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10746. << pTopology->getName()
  10747. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  10748. result = false;
  10749. }
  10750. if (pUniform && pUsage) {
  10751. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  10752. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10753. << pUsage->getName() << pUniform->getName() << declarationType
  10754. << pUniform->getRange();
  10755. result = false;
  10756. }
  10757. }
  10758. if (pMeshModifier) {
  10759. if (pMeshModifier->getKind() == AttributeList::Kind::AT_HLSLPayload) {
  10760. if (!usageIn) {
  10761. Diag(D.getLocStart(), diag::err_hlsl_missing_in_attr)
  10762. << pMeshModifier->getName();
  10763. result = false;
  10764. }
  10765. } else {
  10766. if (!usageOut) {
  10767. Diag(D.getLocStart(), diag::err_hlsl_missing_out_attr)
  10768. << pMeshModifier->getName();
  10769. result = false;
  10770. }
  10771. }
  10772. }
  10773. // Validate that stream-ouput objects are marked as inout
  10774. if (isParameter && !(usageIn && usageOut) &&
  10775. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  10776. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  10777. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  10778. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  10779. result = false;
  10780. }
  10781. // SPIRV change starts
  10782. #ifdef ENABLE_SPIRV_CODEGEN
  10783. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  10784. if (!getLangOpts().SPIRV) {
  10785. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  10786. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  10787. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  10788. << g_ArBasicTypeNames[basicKind];
  10789. result = false;
  10790. }
  10791. }
  10792. #endif // ENABLE_SPIRV_CODEGEN
  10793. // SPIRV change ends
  10794. // Disallow bitfields
  10795. if (BitWidth) {
  10796. Diag(BitWidth->getExprLoc(), diag::err_hlsl_bitfields);
  10797. result = false;
  10798. }
  10799. // Validate unusual annotations.
  10800. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  10801. auto && unusualIter = D.UnusualAnnotations.begin();
  10802. auto && unusualEnd = D.UnusualAnnotations.end();
  10803. for (; unusualIter != unusualEnd; ++unusualIter) {
  10804. switch ((*unusualIter)->getKind()) {
  10805. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10806. hlsl::ConstantPacking *constantPacking =
  10807. cast<hlsl::ConstantPacking>(*unusualIter);
  10808. if (!isGlobal || HLSLBuffers.size() == 0) {
  10809. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  10810. continue;
  10811. }
  10812. if (constantPacking->ComponentOffset > 0) {
  10813. // Validate that this will fit.
  10814. if (!qt.isNull()) {
  10815. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  10816. constantPacking->ComponentOffset);
  10817. }
  10818. }
  10819. break;
  10820. }
  10821. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10822. hlsl::RegisterAssignment *registerAssignment =
  10823. cast<hlsl::RegisterAssignment>(*unusualIter);
  10824. if (registerAssignment->IsValid) {
  10825. if (!qt.isNull()) {
  10826. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  10827. registerAssignment->RegisterType);
  10828. }
  10829. }
  10830. break;
  10831. }
  10832. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10833. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  10834. if (isTypedef || isLocalVar) {
  10835. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  10836. << "semantic" << declarationType;
  10837. }
  10838. break;
  10839. }
  10840. }
  10841. }
  10842. if (!result) {
  10843. D.setInvalidType();
  10844. }
  10845. return result;
  10846. }
  10847. // Diagnose HLSL types on lookup
  10848. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  10849. const DeclarationNameInfo declName = R.getLookupNameInfo();
  10850. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  10851. if (idInfo) {
  10852. StringRef nameIdentifier = idInfo->getName();
  10853. HLSLScalarType parsedType;
  10854. int rowCount, colCount;
  10855. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  10856. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  10857. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  10858. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  10859. }
  10860. }
  10861. return true;
  10862. }
  10863. static QualType getUnderlyingType(QualType Type)
  10864. {
  10865. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  10866. {
  10867. if (const TypedefNameDecl* pDecl = TD->getDecl())
  10868. Type = pDecl->getUnderlyingType();
  10869. else
  10870. break;
  10871. }
  10872. return Type;
  10873. }
  10874. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  10875. /// <param name="self">Sema with context.</param>
  10876. /// <param name="type">QualType to inspect.</param>
  10877. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  10878. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  10879. void hlsl::GetHLSLAttributedTypes(
  10880. _In_ clang::Sema *self, clang::QualType type,
  10881. _Inout_opt_ const clang::AttributedType **ppMatrixOrientation,
  10882. _Inout_opt_ const clang::AttributedType **ppNorm,
  10883. _Inout_opt_ const clang::AttributedType **ppGLC) {
  10884. AssignOpt<const clang::AttributedType *>(nullptr, ppMatrixOrientation);
  10885. AssignOpt<const clang::AttributedType *>(nullptr, ppNorm);
  10886. AssignOpt<const clang::AttributedType *>(nullptr, ppGLC);
  10887. // Note: we clear output pointers once set so we can stop searching
  10888. QualType Desugared = getUnderlyingType(type);
  10889. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  10890. while (AT && (ppMatrixOrientation || ppNorm || ppGLC)) {
  10891. AttributedType::Kind Kind = AT->getAttrKind();
  10892. if (Kind == AttributedType::attr_hlsl_row_major ||
  10893. Kind == AttributedType::attr_hlsl_column_major)
  10894. {
  10895. if (ppMatrixOrientation)
  10896. {
  10897. *ppMatrixOrientation = AT;
  10898. ppMatrixOrientation = nullptr;
  10899. }
  10900. }
  10901. else if (Kind == AttributedType::attr_hlsl_unorm ||
  10902. Kind == AttributedType::attr_hlsl_snorm)
  10903. {
  10904. if (ppNorm)
  10905. {
  10906. *ppNorm = AT;
  10907. ppNorm = nullptr;
  10908. }
  10909. }
  10910. else if (Kind == AttributedType::attr_hlsl_globallycoherent) {
  10911. if (ppGLC) {
  10912. *ppGLC = AT;
  10913. ppGLC = nullptr;
  10914. }
  10915. }
  10916. Desugared = getUnderlyingType(AT->getEquivalentType());
  10917. AT = dyn_cast<AttributedType>(Desugared);
  10918. }
  10919. // Unwrap component type on vector or matrix and check snorm/unorm
  10920. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  10921. AT = dyn_cast<AttributedType>(Desugared);
  10922. while (AT && ppNorm) {
  10923. AttributedType::Kind Kind = AT->getAttrKind();
  10924. if (Kind == AttributedType::attr_hlsl_unorm ||
  10925. Kind == AttributedType::attr_hlsl_snorm)
  10926. {
  10927. *ppNorm = AT;
  10928. ppNorm = nullptr;
  10929. }
  10930. Desugared = getUnderlyingType(AT->getEquivalentType());
  10931. AT = dyn_cast<AttributedType>(Desugared);
  10932. }
  10933. }
  10934. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  10935. /// <param name="self">Sema with context.</param>
  10936. /// <param name="type">QualType to check.</param>
  10937. bool hlsl::IsMatrixType(
  10938. _In_ clang::Sema* self,
  10939. _In_ clang::QualType type)
  10940. {
  10941. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  10942. }
  10943. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  10944. /// <param name="self">Sema with context.</param>
  10945. /// <param name="type">QualType to check.</param>
  10946. bool hlsl::IsVectorType(
  10947. _In_ clang::Sema* self,
  10948. _In_ clang::QualType type)
  10949. {
  10950. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  10951. }
  10952. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  10953. /// <param name="self">Sema with context.</param>
  10954. /// <param name="type">Matrix or Vector type.</param>
  10955. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  10956. _In_ clang::QualType type)
  10957. {
  10958. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  10959. // without losing the AttributedType on the template parameter
  10960. if (const Type* pType = type.getTypePtrOrNull()) {
  10961. // A non-dependent template specialization type is always "sugar",
  10962. // typically for a RecordType. For example, a class template
  10963. // specialization type of @c vector<int> will refer to a tag type for
  10964. // the instantiation @c std::vector<int, std::allocator<int>>.
  10965. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  10966. // If we have enough arguments, pull them from the template directly, rather than doing
  10967. // the extra lookups.
  10968. if (pTemplate->getNumArgs() > 0)
  10969. return pTemplate->getArg(0).getAsType();
  10970. QualType templateRecord = pTemplate->desugar();
  10971. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  10972. if (pTemplateRecordType) {
  10973. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  10974. if (pTemplateTagType) {
  10975. const ClassTemplateSpecializationDecl *specializationDecl =
  10976. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  10977. pTemplateTagType->getDecl());
  10978. if (specializationDecl) {
  10979. return specializationDecl->getTemplateArgs()[0].getAsType();
  10980. }
  10981. }
  10982. }
  10983. }
  10984. }
  10985. return QualType();
  10986. }
  10987. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  10988. /// <param name="self">Sema with context.</param>
  10989. /// <param name="type">Input type.</param>
  10990. clang::QualType hlsl::GetOriginalElementType(
  10991. _In_ clang::Sema* self,
  10992. _In_ clang::QualType type)
  10993. {
  10994. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  10995. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  10996. return GetOriginalMatrixOrVectorElementType(type);
  10997. }
  10998. return type;
  10999. }
  11000. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  11001. switch (A->getKind()) {
  11002. // Parameter modifiers
  11003. case clang::attr::HLSLIn:
  11004. Out << "in ";
  11005. break;
  11006. case clang::attr::HLSLInOut:
  11007. Out << "inout ";
  11008. break;
  11009. case clang::attr::HLSLOut:
  11010. Out << "out ";
  11011. break;
  11012. // Interpolation modifiers
  11013. case clang::attr::HLSLLinear:
  11014. Out << "linear ";
  11015. break;
  11016. case clang::attr::HLSLCenter:
  11017. Out << "center ";
  11018. break;
  11019. case clang::attr::HLSLCentroid:
  11020. Out << "centroid ";
  11021. break;
  11022. case clang::attr::HLSLNoInterpolation:
  11023. Out << "nointerpolation ";
  11024. break;
  11025. case clang::attr::HLSLNoPerspective:
  11026. Out << "noperspective ";
  11027. break;
  11028. case clang::attr::HLSLSample:
  11029. Out << "sample ";
  11030. break;
  11031. // Function attributes
  11032. case clang::attr::HLSLClipPlanes:
  11033. {
  11034. Attr * noconst = const_cast<Attr*>(A);
  11035. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  11036. if (!ACast->getClipPlane1())
  11037. break;
  11038. Indent(Indentation, Out);
  11039. Out << "[clipplanes(";
  11040. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  11041. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  11042. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  11043. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  11044. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  11045. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  11046. Out << ")]\n";
  11047. break;
  11048. }
  11049. case clang::attr::HLSLDomain:
  11050. {
  11051. Attr * noconst = const_cast<Attr*>(A);
  11052. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  11053. Indent(Indentation, Out);
  11054. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  11055. break;
  11056. }
  11057. case clang::attr::HLSLEarlyDepthStencil:
  11058. Indent(Indentation, Out);
  11059. Out << "[earlydepthstencil]\n";
  11060. break;
  11061. case clang::attr::HLSLInstance: //TODO - test
  11062. {
  11063. Attr * noconst = const_cast<Attr*>(A);
  11064. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  11065. Indent(Indentation, Out);
  11066. Out << "[instance(" << ACast->getCount() << ")]\n";
  11067. break;
  11068. }
  11069. case clang::attr::HLSLMaxTessFactor: //TODO - test
  11070. {
  11071. Attr * noconst = const_cast<Attr*>(A);
  11072. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  11073. Indent(Indentation, Out);
  11074. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  11075. break;
  11076. }
  11077. case clang::attr::HLSLNumThreads: //TODO - test
  11078. {
  11079. Attr * noconst = const_cast<Attr*>(A);
  11080. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  11081. Indent(Indentation, Out);
  11082. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  11083. break;
  11084. }
  11085. case clang::attr::HLSLRootSignature:
  11086. {
  11087. Attr * noconst = const_cast<Attr*>(A);
  11088. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  11089. Indent(Indentation, Out);
  11090. Out << "[RootSignature(\"" << ACast->getSignatureName() << "\")]\n";
  11091. break;
  11092. }
  11093. case clang::attr::HLSLOutputControlPoints:
  11094. {
  11095. Attr * noconst = const_cast<Attr*>(A);
  11096. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  11097. Indent(Indentation, Out);
  11098. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  11099. break;
  11100. }
  11101. case clang::attr::HLSLOutputTopology:
  11102. {
  11103. Attr * noconst = const_cast<Attr*>(A);
  11104. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  11105. Indent(Indentation, Out);
  11106. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  11107. break;
  11108. }
  11109. case clang::attr::HLSLPartitioning:
  11110. {
  11111. Attr * noconst = const_cast<Attr*>(A);
  11112. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  11113. Indent(Indentation, Out);
  11114. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  11115. break;
  11116. }
  11117. case clang::attr::HLSLPatchConstantFunc:
  11118. {
  11119. Attr * noconst = const_cast<Attr*>(A);
  11120. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  11121. Indent(Indentation, Out);
  11122. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  11123. break;
  11124. }
  11125. case clang::attr::HLSLShader:
  11126. {
  11127. Attr * noconst = const_cast<Attr*>(A);
  11128. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  11129. Indent(Indentation, Out);
  11130. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  11131. break;
  11132. }
  11133. case clang::attr::HLSLExperimental:
  11134. {
  11135. Attr * noconst = const_cast<Attr*>(A);
  11136. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  11137. Indent(Indentation, Out);
  11138. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  11139. break;
  11140. }
  11141. case clang::attr::HLSLMaxVertexCount:
  11142. {
  11143. Attr * noconst = const_cast<Attr*>(A);
  11144. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  11145. Indent(Indentation, Out);
  11146. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  11147. break;
  11148. }
  11149. case clang::attr::NoInline:
  11150. Indent(Indentation, Out);
  11151. Out << "[noinline]\n";
  11152. break;
  11153. case clang::attr::HLSLExport:
  11154. Indent(Indentation, Out);
  11155. Out << "export\n";
  11156. break;
  11157. // Statement attributes
  11158. case clang::attr::HLSLAllowUAVCondition:
  11159. Indent(Indentation, Out);
  11160. Out << "[allow_uav_condition]\n";
  11161. break;
  11162. case clang::attr::HLSLBranch:
  11163. Indent(Indentation, Out);
  11164. Out << "[branch]\n";
  11165. break;
  11166. case clang::attr::HLSLCall:
  11167. Indent(Indentation, Out);
  11168. Out << "[call]\n";
  11169. break;
  11170. case clang::attr::HLSLFastOpt:
  11171. Indent(Indentation, Out);
  11172. Out << "[fastopt]\n";
  11173. break;
  11174. case clang::attr::HLSLFlatten:
  11175. Indent(Indentation, Out);
  11176. Out << "[flatten]\n";
  11177. break;
  11178. case clang::attr::HLSLForceCase:
  11179. Indent(Indentation, Out);
  11180. Out << "[forcecase]\n";
  11181. break;
  11182. case clang::attr::HLSLLoop:
  11183. Indent(Indentation, Out);
  11184. Out << "[loop]\n";
  11185. break;
  11186. case clang::attr::HLSLUnroll:
  11187. {
  11188. Attr * noconst = const_cast<Attr*>(A);
  11189. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  11190. Indent(Indentation, Out);
  11191. if (ACast->getCount() == 0)
  11192. Out << "[unroll]\n";
  11193. else
  11194. Out << "[unroll(" << ACast->getCount() << ")]\n";
  11195. break;
  11196. }
  11197. // Variable modifiers
  11198. case clang::attr::HLSLGroupShared:
  11199. Out << "groupshared ";
  11200. break;
  11201. case clang::attr::HLSLPrecise:
  11202. Out << "precise ";
  11203. break;
  11204. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  11205. break;
  11206. case clang::attr::HLSLShared:
  11207. Out << "shared ";
  11208. break;
  11209. case clang::attr::HLSLUniform:
  11210. Out << "uniform ";
  11211. break;
  11212. // These four cases are printed in TypePrinter::printAttributedBefore
  11213. case clang::attr::HLSLColumnMajor:
  11214. case clang::attr::HLSLRowMajor:
  11215. case clang::attr::HLSLSnorm:
  11216. case clang::attr::HLSLUnorm:
  11217. break;
  11218. case clang::attr::HLSLPoint:
  11219. Out << "point ";
  11220. break;
  11221. case clang::attr::HLSLLine:
  11222. Out << "line ";
  11223. break;
  11224. case clang::attr::HLSLLineAdj:
  11225. Out << "lineadj ";
  11226. break;
  11227. case clang::attr::HLSLTriangle:
  11228. Out << "triangle ";
  11229. break;
  11230. case clang::attr::HLSLTriangleAdj:
  11231. Out << "triangleadj ";
  11232. break;
  11233. case clang::attr::HLSLGloballyCoherent:
  11234. Out << "globallycoherent ";
  11235. break;
  11236. case clang::attr::HLSLIndices:
  11237. Out << "indices ";
  11238. break;
  11239. case clang::attr::HLSLVertices:
  11240. Out << "vertices ";
  11241. break;
  11242. case clang::attr::HLSLPrimitives:
  11243. Out << "primitives ";
  11244. break;
  11245. case clang::attr::HLSLPayload:
  11246. Out << "payload ";
  11247. break;
  11248. default:
  11249. A->printPretty(Out, Policy);
  11250. break;
  11251. }
  11252. }
  11253. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  11254. switch (AttrKind){
  11255. case clang::attr::HLSLAllowUAVCondition:
  11256. case clang::attr::HLSLBranch:
  11257. case clang::attr::HLSLCall:
  11258. case clang::attr::HLSLCentroid:
  11259. case clang::attr::HLSLClipPlanes:
  11260. case clang::attr::HLSLColumnMajor:
  11261. case clang::attr::HLSLDomain:
  11262. case clang::attr::HLSLEarlyDepthStencil:
  11263. case clang::attr::HLSLFastOpt:
  11264. case clang::attr::HLSLFlatten:
  11265. case clang::attr::HLSLForceCase:
  11266. case clang::attr::HLSLGroupShared:
  11267. case clang::attr::HLSLIn:
  11268. case clang::attr::HLSLInOut:
  11269. case clang::attr::HLSLInstance:
  11270. case clang::attr::HLSLLinear:
  11271. case clang::attr::HLSLCenter:
  11272. case clang::attr::HLSLLoop:
  11273. case clang::attr::HLSLMaxTessFactor:
  11274. case clang::attr::HLSLNoInterpolation:
  11275. case clang::attr::HLSLNoPerspective:
  11276. case clang::attr::HLSLNumThreads:
  11277. case clang::attr::HLSLRootSignature:
  11278. case clang::attr::HLSLOut:
  11279. case clang::attr::HLSLOutputControlPoints:
  11280. case clang::attr::HLSLOutputTopology:
  11281. case clang::attr::HLSLPartitioning:
  11282. case clang::attr::HLSLPatchConstantFunc:
  11283. case clang::attr::HLSLMaxVertexCount:
  11284. case clang::attr::HLSLPrecise:
  11285. case clang::attr::HLSLRowMajor:
  11286. case clang::attr::HLSLSample:
  11287. case clang::attr::HLSLSemantic:
  11288. case clang::attr::HLSLShared:
  11289. case clang::attr::HLSLSnorm:
  11290. case clang::attr::HLSLUniform:
  11291. case clang::attr::HLSLUnorm:
  11292. case clang::attr::HLSLUnroll:
  11293. case clang::attr::HLSLPoint:
  11294. case clang::attr::HLSLLine:
  11295. case clang::attr::HLSLLineAdj:
  11296. case clang::attr::HLSLTriangle:
  11297. case clang::attr::HLSLTriangleAdj:
  11298. case clang::attr::HLSLGloballyCoherent:
  11299. case clang::attr::HLSLIndices:
  11300. case clang::attr::HLSLVertices:
  11301. case clang::attr::HLSLPrimitives:
  11302. case clang::attr::HLSLPayload:
  11303. case clang::attr::NoInline:
  11304. case clang::attr::HLSLExport:
  11305. case clang::attr::HLSLWaveSensitive:
  11306. case clang::attr::VKBinding:
  11307. case clang::attr::VKBuiltIn:
  11308. case clang::attr::VKConstantId:
  11309. case clang::attr::VKCounterBinding:
  11310. case clang::attr::VKIndex:
  11311. case clang::attr::VKInputAttachmentIndex:
  11312. case clang::attr::VKLocation:
  11313. case clang::attr::VKOffset:
  11314. case clang::attr::VKPushConstant:
  11315. case clang::attr::VKShaderRecordNV:
  11316. return true;
  11317. default:
  11318. // Only HLSL/VK Attributes return true. Only used for printPretty(), which doesn't support them.
  11319. break;
  11320. }
  11321. return false;
  11322. }
  11323. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  11324. if (ClipPlane) {
  11325. Out << ", ";
  11326. ClipPlane->printPretty(Out, 0, Policy);
  11327. }
  11328. }
  11329. bool hlsl::IsObjectType(
  11330. _In_ clang::Sema* self,
  11331. _In_ clang::QualType type,
  11332. _Inout_opt_ bool *isDeprecatedEffectObject)
  11333. {
  11334. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  11335. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  11336. if (isDeprecatedEffectObject)
  11337. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  11338. return true;
  11339. }
  11340. if (isDeprecatedEffectObject)
  11341. *isDeprecatedEffectObject = false;
  11342. return false;
  11343. }
  11344. bool hlsl::CanConvert(
  11345. _In_ clang::Sema* self,
  11346. clang::SourceLocation loc,
  11347. _In_ clang::Expr* sourceExpr,
  11348. clang::QualType target,
  11349. bool explicitConversion,
  11350. _Inout_opt_ clang::StandardConversionSequence* standard)
  11351. {
  11352. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  11353. }
  11354. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  11355. {
  11356. for (unsigned i = 0; i != Indentation; ++i)
  11357. Out << " ";
  11358. }
  11359. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  11360. {
  11361. DXASSERT_NOMSG(self != nullptr);
  11362. DXASSERT_NOMSG(table != nullptr);
  11363. HLSLExternalSource* source = (HLSLExternalSource*)self;
  11364. source->RegisterIntrinsicTable(table);
  11365. }
  11366. clang::QualType hlsl::CheckVectorConditional(
  11367. _In_ clang::Sema* self,
  11368. _In_ clang::ExprResult &Cond,
  11369. _In_ clang::ExprResult &LHS,
  11370. _In_ clang::ExprResult &RHS,
  11371. _In_ clang::SourceLocation QuestionLoc)
  11372. {
  11373. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  11374. }
  11375. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  11376. UINT count;
  11377. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  11378. }
  11379. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  11380. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  11381. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  11382. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  11383. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  11384. llvm::APSInt index;
  11385. if (RHS->EvaluateAsInt(index, Context)) {
  11386. int64_t intIndex = index.getLimitedValue();
  11387. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  11388. if (IsVectorType(this, LHSQualType)) {
  11389. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  11390. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  11391. // we also have to check the first subscript oprator by recursively calling
  11392. // this funciton for the first CXXOperatorCallExpr
  11393. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  11394. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  11395. }
  11396. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  11397. Diag(RHS->getExprLoc(),
  11398. diag::err_hlsl_vector_element_index_out_of_bounds)
  11399. << (int)intIndex;
  11400. }
  11401. }
  11402. else if (IsMatrixType(this, LHSQualType)) {
  11403. uint32_t rowCount, colCount;
  11404. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  11405. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  11406. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  11407. << (int)intIndex;
  11408. }
  11409. }
  11410. }
  11411. }
  11412. clang::QualType ApplyTypeSpecSignToParsedType(
  11413. _In_ clang::Sema* self,
  11414. _In_ clang::QualType &type,
  11415. _In_ clang::TypeSpecifierSign TSS,
  11416. _In_ clang::SourceLocation Loc
  11417. )
  11418. {
  11419. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  11420. }